How POST Requests Work
Understand how POST sends data in the request body as JSON
How POST sends data
In Lesson 1, you learned that HTTP methods signal different actions. POST is the method for creating data.
Unlike GET, which puts everything in the URL (/expenses?category=food), POST sends data in the request body — a block of JSON attached to the request, separate from the URL.
What the client sends
When a client creates an expense, it sends a POST request with a JSON body:
POST /expenses
{
"description": "Lunch",
"amount": 12.50,
"category": "food"
}The JSON body contains the fields your Expense model defines. FastAPI reads this JSON, validates it against your model, and converts it into a Python object.
How FastAPI maps the body to your function
To receive POST data, you add a parameter with a Pydantic type to your function:
@app.post("/expenses")
def create_expense(expense: Expense):
print(expense.description) # "Lunch"
print(expense.amount) # 12.5FastAPI sees the Expense type hint and does three things automatically:
- Reads the JSON from the request body.
- Validates every field against your model (type, constraints, required fields).
- Rejects the request with a
422error if anything is wrong.
By the time your function runs, expense is a fully validated Expense object. You never need to check the data manually.