2

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.

Parashuram
  • 1,498
  • 2
  • 16
  • 36
  • Related answers can be found [here](https://stackoverflow.com/a/70659178/17865804) and [here](https://stackoverflow.com/a/74173023/17865804) as well – Chris Apr 12 '23 at 10:01

2 Answers2

1

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

sahasrara62
  • 10,069
  • 3
  • 29
  • 44
  • 1
    does this work? I have tried this and getting the error "ValueError: [TypeError("'coroutine' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')]". How do you make request to this api from Postman? – Parashuram May 24 '21 at 17:17
  • this is a basic example to take request as argument and then process the data according to the request. if you are facing error, you need to see how to handle request object in python. if still facing error, you can post a new question with all the prerequisite and error you are getting – sahasrara62 May 24 '21 at 18:06
1

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.