close

How do I return an image in fastAPI?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How do I return an image in fastAPI in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How do I return an image in fastAPI?

  1. 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.

  2. 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.

Method 1

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")

Method 2

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

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.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read