When a client sends data to your API (like a form), you often want it to be structured. FastAPI uses Pydantic models to define this structure.
1. Define a Pydantic Model
A Pydantic model is a Python class that describes what the data should look like:
from fastapi import FastAPI
from typing import List
from pydantic import BaseModel, Field
app = FastAPI()
class Student(BaseModel):
id: int
name: str = Field(None, title="Name of the student", max_length=10)
subjects: List[str] = []
Here:
idis an integernameis a string (max 10 characters)subjectsis a list of strings, default empty
2. Use POST to Accept the Model
To get data from a client, use the POST method:
@app.post("/students/")
async def student_data(s1: Student):
return s1
Explanation:
@app.post("/students/")defines the URL and POST methods1: Studenttells FastAPI to expect a JSON body matching theStudentmodel- The function returns the same data back as JSON
3. Test in Swagger UI
- Start the server:
uvicorn main:app --reload - Open in browser: http://localhost:8000/docs
- Find the
/students/route under POST - Click Try it out, fill in test data, and click Execute
- You get a JSON response with the same data you sent
4. Using Individual Fields Instead of a Model
You can accept individual fields using Body:
from fastapi import Body
@app.post("/students")
async def student_data(name: str = Body(...), marks: int = Body(...)):
return {"name": name, "marks": marks}
- `name` and `marks` are sent in the request body separately
- Works the same as the model, just with individual fields
5. Combining Path, Query, and Body
@app.post("/students/{college}")
async def student_data(college: str, age: int, student: Student):
retval = {"college": college, "age": age, **student.dict()}
return retval
Explanation:
college→ path parameter (`/students/XYZ`)age→ query parameter (`?age=20`)student→ JSON request body (Pydantic model)**student.dict()→ converts the Student object to a dictionary
Example request:
POST /students/ABC?age=20
{
"id": 1,
"name": "Alice",
"subjects": ["Math", "Physics"]
}
Response:
{
"college": "ABC",
"age": 20,
"id": 1,
"name": "Alice",
"subjects": ["Math", "Physics"]
}
Summary
- Use Pydantic models to structure request body data.
- Use
Body(...)for individual fields. - POST method is used to receive request body.
- You can combine path + query + body in a single endpoint.
- FastAPI automatically validates data and converts JSON to Python objects.