A request body allows the client to send structured JSON data to the API.
Request bodies are commonly used when creating or updating resources. In FastAPI, you can use a Pydantic model to define the expected structure of the request data.
Code
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
name: str
email: str
age: int
@app.post("/users")
def create_user(user: User):
return user
Understanding the Code
First, import FastAPI and Pydantic: BaseModel:
from fastapi import FastAPI
from pydantic import BaseModel
Create a User model:
class User(BaseModel):
name: str
email: str
age: int
This model defines the structure of the data that the API expects.
The create_user() endpoint accepts a User object:
@app.post("/users")
def create_user(user: User):
return user
FastAPI reads the JSON request body and validates it against the User model.
Example Request
Send a POST request to:
POST /users
With the following JSON request body:
{
"name": "Tarun",
"email": "tarun@example.com",
"age": 25
}
Output
The API returns the received user data:
{
"name": "Tarun",
"email": "tarun@example.com",
"age": 25
}
Summary
A request body is used to send structured data to an API.
In FastAPI, a Pydantic model can define the expected request body:
class User(BaseModel):
name: str
email: str
age: int
Then the model can be used directly in the endpoint:
@app.post("/users")
def create_user(user: User):
return user