We use request body declaration to tell FastAPI what data to expect from a client when they send information to our server. This helps us get the data in a clear and organized way.
Request body declaration in FastAPI
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float @app.post("/items/") async def create_item(item: Item): return item
Use a BaseModel class to define the shape of the data you expect.
Declare the request body by adding a parameter with the model type in your path operation function.
from pydantic import BaseModel class User(BaseModel): username: str age: int @app.post("/users/") async def create_user(user: User): return user
from pydantic import BaseModel class Product(BaseModel): id: int description: str @app.post("/products/") async def add_product(product: Product): return product
This program defines a Book model with title and author. When a client sends a POST request with this data, the server responds with a confirmation message.
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Book(BaseModel): title: str author: str @app.post("/books/") async def create_book(book: Book): return {"message": f"Book '{book.title}' by {book.author} created."}
FastAPI automatically converts JSON request bodies into your model objects.
If the client sends wrong or missing data, FastAPI returns an error explaining what is wrong.
Use BaseModel to add validation and clear data structure.
Request body declaration tells FastAPI what data to expect from clients.
Use Pydantic models (BaseModel) to define the data shape.
FastAPI handles data parsing and validation automatically.
Practice
Solution
Step 1: Understand request body role
The request body contains data sent by the client to the server, usually in POST or PUT requests.Step 2: Role of Pydantic model in FastAPI
Using a Pydantic model tells FastAPI the expected data shape and automatically validates it.Final Answer:
To tell FastAPI what data structure to expect and validate from the client -> Option BQuick Check:
Request body declaration = Data validation [OK]
- Confusing request body with URL path
- Thinking request body sets HTTP method
- Assuming request body controls response code
Solution
Step 1: Recognize Pydantic model usage
FastAPI expects a Pydantic model class (like Item) to declare request body parameters.Step 2: Check each option
def create_item(item: dict): uses dict which works but is not recommended; def create_item(item: BaseModel): uses BaseModel directly which is abstract; def create_item(item: Item): uses a user-defined model Item which is correct; def create_item(item: str): uses str which is not a model.Final Answer:
def create_item(item: Item): -> Option CQuick Check:
Use Pydantic model class for request body [OK]
- Using dict instead of a Pydantic model
- Using BaseModel directly instead of subclass
- Using primitive types like str for complex data
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.post("/items/")
async def create_item(item: Item):
return {"item_name": item.name, "item_price": item.price}Solution
Step 1: Understand Pydantic type conversion
Pydantic automatically converts compatible types, so int 5 converts to float 5.0.Step 2: Check returned dictionary
The function returns a dict with keys "item_name" and "item_price" using the values from the item object.Final Answer:
{"item_name": "apple", "item_price": 5.0} -> Option DQuick Check:
Int converts to float automatically in Pydantic [OK]
- Thinking int and float types cause validation error
- Expecting string instead of float for price
- Assuming server error on type mismatch
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
username: str
age: int
@app.post("/users/")
def create_user(user: User = None):
return {"username": user.username, "age": user.age}Solution
Step 1: Check request body parameter declaration
In FastAPI, request body parameters cannot have a default value of None because the body is required by default.Step 2: Review other options
Async is optional for FastAPI endpoints; BaseModel inheritance is correct; return works in sync functions.Final Answer:
Request body parameter cannot have a default value None -> Option AQuick Check:
Request body params must not default to None [OK]
- Adding default None to request body param
- Thinking async is mandatory
- Misunderstanding BaseModel inheritance
description which can be missing or null. How should you declare the Pydantic model to handle this correctly?Solution
Step 1: Understand optional fields in Pydantic
To allow a field to be optional or null, use Optional[type] with a default value None.Step 2: Analyze each option
from pydantic import BaseModel from typing import Optional class Item(BaseModel): name: str description: Optional[str] = None correctly uses Optional[str] with default None; from pydantic import BaseModel class Item(BaseModel): name: str description: str requires description always; from pydantic import BaseModel from typing import Union class Item(BaseModel): name: str description: Union[str, None] = None uses Union[str, None] with default None; from pydantic import BaseModel class Item(BaseModel): name: str description: None sets description to None type which is invalid.Final Answer:
Use Optional[str] with default None for optional nullable field -> Option AQuick Check:
Optional field = Optional[type] + default None [OK]
- Forgetting to set default None for optional fields
- Using plain type without Optional for nullable fields
- Assigning None as a type instead of a value
Ready to prove it?
Pass the test and this pattern moves unknown
