How do I return an image in fastAPI?

Hooked picture Hooked · Apr 26, 2019 · Viewed 19.4k times · Source

Using the python module fastAPI, I can't figure out how to return an image. In flask I would do something like this:

@app.route("/vector_image", methods=["POST"])
def image_endpoint():
    # img = ... # Create the image here
    return Response(img, mimetype="image/png")

what's the corresponding call in this module?

Answer

biophetik picture biophetik · Jan 6, 2020

I had a similar issue but with a cv2 image. This may be useful for others. Uses the StreamingResponse.

import io
from starlette.responses import StreamingResponse

app = FastAPI()

@app.post("/vector_image")
def image_endpoint(*, vector):
    # Returns a cv2 image array from the document vector
    cv2img = my_function(vector)
    res, im_png = cv2.imencode(".png", cv2img)
    return StreamingResponse(io.BytesIO(im_png.tobytes()), media_type="image/png")