Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return an image in fastAPI?

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?

like image 885
Hooked Avatar asked Apr 26 '19 18:04

Hooked


People also ask

How do I return a response to FastAPI?

When you create a FastAPI path operation you can normally return any data from it: a dict , a list , a Pydantic model, a database model, etc. By default, FastAPI would automatically convert that return value to JSON using the jsonable_encoder explained in JSON Compatible Encoder.


1 Answers

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") 
like image 78
biophetik Avatar answered Oct 04 '22 20:10

biophetik