How do I return an image in fastAPI? How do I return an image in fastAPI? python python

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.


All the other answer(s) is on point, but now it's so easy to return an image

from fastapi.responses import FileResponse@app.get("/")async def main():    return FileResponse("your_image.jpeg")