Wrong specified media type using FastAPI

1k Views Asked by At

I'm trying to create a POST route where the media type would be set to "image/*" but when my route requires an argument, it's media type become "application/json" (even when I specify the response_class value).

Do you have an idea why?

Here is my source code:

from io import BytesIO

from fastapi.responses import ORJSONResponse
from fastapi import FastAPI
from fastapi.responses import StreamingResponse, JSONResponse, FileResponse


app = FastAPI(default_response_class=ORJSONResponse)


@app.post("/working", response_class=FileResponse)
async def send_w():

    with open("/tmp/test/b.jpg", "rb") as f:
        image = BytesIO(f.read())

    image.seek(0)

    return StreamingResponse(image, media_type="image/jpeg")


@app.post("/a", response_class=FileResponse)
async def send_a(a):

    with open("/tmp/test/b.jpg", "rb") as f:
        image = BytesIO(f.read())

    image.seek(0)

    return StreamingResponse(image, media_type="image/jpeg")


@app.post("/b", response_class=FileResponse)
async def send_b(b):

    return "/tmp/test/b.jpg"

/a route:

Resulting rout

1

There are 1 best solutions below

1
zzob On

You need to create function args to handle file type.

e.g.

from fastapi import FastAPI, File, UploadFile

@app.post("/image")
async def upload(data : UploadFile = File(...)):
    image = await data.read() 
    # do your process here

read more: https://fastapi.tiangolo.com/tutorial/request-files/