Parashuram
Parashuram

Reputation: 1569

How to read non json data from request in FastApi

I have below code snippet which simply reads from form data and returns it.

@my_app.post("/items2/{item_id}")
def read_root(username: str = Form(...), password: str = Form(...)):
    # return request.body()
    return {"username": username, "password":password}

My question here is, is there any other way i can pick this data from request object ? I don't want to use form data here. Also my input data is not in json format so don't want to use the model also.

I have gone through the Fastapi docs and could not find something related to this.

Upvotes: 2

Views: 2209

Answers (2)

Markus Stenberg
Markus Stenberg

Reputation: 11

The solution from 2021 is actually wrong (at least for recent-ish fastapis); request's body method is async method. This is how you would get + return raw bytes:

from fastapi import Request, Response, FastAPI
@my_app.post("/items2")
async def read_root(request: Request):

    body = await request.body() 
    return Response(content=body) 
    # if you want to return bytes as-is, you might want to set media_type 

However, 'not json' isn't really helping much in describing what exactly you want to put in or get out, so due to that it is hard to provide real answer. fastapi is pretty bad platform for non-json structures anyway, so I would perhaps not go with it at all if you have some ASN.1 BER encoded legacy thing going on.

Upvotes: 1

sahasrara62
sahasrara62

Reputation: 11228

if you want to read the data from the request body then this is what you can do

from fastapi import Request, FastAPI
@my_app.post("/items2/{item_id}")
def read_root(request: Request):

    # if want to process request as json
    # return request.json() 
    return request.body() # if want to process request as string

Basically, add the data in the request object, read that object in the api, then process it and then return it

Upvotes: 1

Related Questions