Request Body in FastAPI
What is a Request Body?
In FastAPI, a Request Body is the data sent by the client to the API in JSON or other formats, typically used in POST, PUT, or PATCH requests. It allows you to receive structured data (like Pydantic models) from the client, and the
Define a Pydantic Model
A Pydantic Model in FastAPI is a class that defines the structure, data types, and validation rules for request and response bodies using Python type hints. It ensures that the data is automatically validated and parsed before being used in your API logic.
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
in_stock: bool | None = None
Single Request Body
Single Request Body is a single JSON object sent by the client, typically used in POST or PUT requests. In FastAPI, it is validated and parsed using one Pydantic model for easy access to its fields.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
name: str
age: int
bio: str | None = None
@app.post("/user/")
def create_user(user: User):
return {"message": f"Hello {user.name}, age {user.age}"}
Embedding a Single Request Body
Embedding a Single Request Body means wrapping the entire request data under a key using embed=True. This is useful when you want the body to be nested under a specific name, especially for clarity or when combining multiple inputs.
from fastapi import FastAPI, Body
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
username: str
email: str
@app.patch("/update-user/{user_id}")
def update_user(user_id: int, user: User = Body(embed=True)):
return {"user_id": user_id, "user_data": user}
Multiple Request Bodies
Multiple Request Bodies in FastAPI refer to sending more than one Pydantic model or value in a single request. FastAPI can parse and validate each part separately by using multiple parameters in the endpoint function.
from fastapi import FastAPI, Body
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
name: str
age: int
class Address(BaseModel):
city: str
zipcode: str
@app.post("/submit/")
def submit_data(user: User, address: Address, secret_key:str=Body()):
return {"user": user, "address": address}
Field() in Request Body
Field() in Request Body is used in FastAPI with Pydantic models to add validation, default values, and metadata to individual fields. It helps enforce constraints like length, value limits, and improves API documentation. You can use similar attributes as in Path and Query parameters, such as min_length, max_length, ge, le, pattern, etc.
from fastapi import FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
class Product(BaseModel):
name: str = Field(max_length=50, title="Product Name", pattern="^[A-Za-z0-9 ]+$")
price: float = Field(gt=0, description="Price must be greater than zero")
available: bool = Field(default=True, description="Is the product available?")
@app.post("/products/")
def create_product(product: Product):
return product
Using with Query and Path Parameters
Using with Query and Path Parameters in FastAPI refers to combining data passed through the URL path (path parameters) and query strings (query parameters) with request bodies. This allows endpoints to handle dynamic URLs and additional optional input, making the API more powerful and flexible.
from fastapi import FastAPI, Path, Query
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.put("/items/{item_id}")
def update_item(
item_id: int = Path(title="The ID of the item to update"),
confirm: bool = Query(default=False, description="Confirm the update"),
item: Item
):
return {"item_id": item_id, "confirmed": confirm, "updated_item": item}
Exercise
- Fill in the Blanks:
- - Django is a __________ written in Python that simplifies web development.
- - Django follows the __________ architecture, which stands for __________.
- - To install Django, the package manager used is __________.
- - You can check the installed Django version using the command __________.
- - MVC stands for __________.