How to pass JSON to POST request in FastAPI ?
You can pass paramters to the FastAPI POST endpoint using pydantic
. But to use pydantic
you need to pre define the JSON structure. What if you don’t know the structure?
You can access the passed request body using request
. Start by importing request
from FastAPI
.
from fastapi import Request
Declare the type of the parameter as Request
. When passing pre defined JSON structure or model to POST request we had set the parameter type as the pre defined model.
from fastapi import FastAPI, Request
my_app = FastAPI()
@my_app.post("/getInformation")
async def getInformation(info : Request):
req_info = await info.json()
return {
"status" : "SUCCESS",
"data" : req_info
}
As seen in the above code, you need to await the info.json()
to read the JSON data. Save the changes and hit a POST request to the http://localhost:8000/getInformation and you will get the passed in request in the data
key of the response.
I tried posting the following JSON,
{
"id" : 100,
"name" : "Jay",
"city" : "Kochi"
}
Here is the response JSON from the POST endpoint.
{
"status": "SUCCESS",
"data": {
"id": 100,
"name": "Jay",
"city":"Kochi"
}
}