How to read non json data from request in fastapi?

by haylee.mertz , in category: Third Party Scripts , 12 days ago

How to read non json data from request in fastapi?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , 11 days ago

@haylee.mertz 

To read non-JSON data from a request in FastAPI, you can use the Request object provided by FastAPI. The Request object has attributes that allow you to access the raw request body data.


Here is an example of how you can read non-JSON data from a request in FastAPI:

1
2
3
4
5
6
7
8
9
from fastapi import FastAPI, Request

app = FastAPI()

@app.post("/uploadfile/")
async def upload_file(request: Request):
    data = await request.body()
    data_str = data.decode("utf-8")
    return {"data": data_str}


In this example, the upload_file endpoint reads the raw request body data using request.body() and decodes it from bytes to a string using decode("utf-8"). The decoded data is then returned as a response.


You can test this endpoint by sending a POST request with non-JSON data to /uploadfile/. The data will be read and returned in the response.