astersss92
astersss92

Reputation: 63

FastApi Post Request With Bytes Object Got 422 Error

I am writing a python post request with a bytes body:

with open('srt_file.srt', 'rb') as f:
    data = f.read()

    res = requests.post(url='http://localhost:8000/api/parse/srt',
                        data=data,
                        headers={'Content-Type': 'application/octet-stream'})

And in the server part, I tried to parse the body:

app = FastAPI()
BaseConfig.arbitrary_types_allowed = True


class Data(BaseModel):
    data: bytes

@app.post("/api/parse/{format}", response_model=CaptionJson)
async def parse_input(format: str, data: Data) -> CaptionJson:
    ...

However, I got the 422 error: {"detail":[{"loc":["body"],"msg":"value is not a valid dict","type":"type_error.dict"}]}

So where is wrong with my code, and how should I fix it? Thank you all in advance for helping out!!

Upvotes: 6

Views: 13264

Answers (2)

Ben
Ben

Reputation: 2027

FastAPI by default will expect you to pass json which will parse into a dict. It can't do that if it's isn't json, which is why you get the error you see.

You can use the Request object instead to receive arbitrary bytes from the POST body.

from fastapi import FastAPI, Request

app = FastAPI()

@app.get("/foo")
async def parse_input(request: Request):
    data: bytes = await request.body()
    # Do something with data

You might consider using Depends which will allow you to clean up your route function. FastAPI will first call your dependency function (parse_body in this example) and will inject that as an argument into your route function.

from fastapi import FastAPI, Request, Depends

app = FastAPI()

async def parse_body(request: Request):
    data: bytes = await request.body()
    return data


@app.get("/foo")
async def parse_input(data: bytes = Depends(parse_body)):
    # Do something with data
    pass

Upvotes: 11

LanderM
LanderM

Reputation: 11

If the endgoal of your request is to only send bytes then please look at the documentation of FastAPI to accept bytes-like objects: https://fastapi.tiangolo.com/tutorial/request-files.

There is no need for the bytes to be enclosed into a model.

Upvotes: 1

Related Questions