How do I return an image in fastAPI?
I had a similar issue but with a cv2 image. This may be useful for others. Uses the StreamingResponse
.
import iofrom starlette.responses import StreamingResponseapp = 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")
It's not properly documented yet, but you can use anything from Starlette.
So, you can use a FileResponse
if it's a file in disk with a path: https://www.starlette.io/responses/#fileresponse
If it's a file-like object created in your path operation, in the next stable release of Starlette (used internally by FastAPI) you will also be able to return it in a StreamingResponse
.