Send Parameters to POST Request | FastAPI


How to pass parameters in POST request in FastAPI ?

Unlike GET request where you pass data as query string, in POST request you send the data in request body.

Let’s first create a POST endpoint and it’s corresponding method.

from fastapi import FastAPI
my_app = FastAPI()

@my_app.post("/getInformation")
def getInformation():
    return {
        "status" : "SUCCESS",
        "data" : []
    }

To pass request data object, you need to create a class of the data object that you intend to pass as POST body request.

from pydantic import BaseModel
my_app = FastAPI()

class Info(BaseModel):
    id : int
    name : str

As seen in the above code, you have imported BaseModel from pydantic and the Info class inherits from BaseModel.

I have created Info class with members id and name. Receiving POST request data is same as receiving GET request. In the getInformation method define a variable of type Info.

@my_app.post("/getInformation")
def getInformation(info : Info):
    return {
        "status" : "SUCCESS",
        "data" : info
    }

Here is how the complete app.py file looks:

from fastapi import FastAPI
from pydantic import BaseModel
my_app = FastAPI()

class Info(BaseModel):
    id : int
    name : str

@my_app.post("/getInformation")
def getInformation(info : Info):
    return {
        "status" : "SUCCESS",
        "data" : info
    }

Save the above changes and restart the server. Try posting some data to the endpoint http://localhost:8000/getInformation. Whatever data you post, you’ll get in the response. I tried posting the following JSON,

{
	"id" : 100,
	"name" : "Jay"
}

Here is the response JSON from the POST endpoint.

{
    "status": "SUCCESS",
    "data": {
        "id": 100,
        "name": "Jay"
    }
}