PYTHON FASTAPI · LESSON 3 OF 8
Request bodies and response models
Validate JSON with Pydantic and define a predictable response.
- BaseModel
- Field
- POST
- 201
Your runnable checkpoint
Extract into a new practice folder. Each download includes complete source, requirements.txt and README.md. Stop any earlier server before running this example.
Create and activate a virtual environment as shown in lesson 1. Install with python -m pip install -r requirements.txt, then run fastapi dev main.py. Lessons 6–8 require TASK_API_KEY as explained in lesson 6.
1. Understand the concepts
A POST request sends JSON in its body. TaskCreate describes that input. title is required; done defaults to False. Class attributes with type hints become model fields. In JSON write false; in Python write False.
Field bounds the title length. ConfigDict trims whitespace and rejects unknown keys, so a spelling mistake such as titel does not silently disappear. A blank title becomes empty after trimming and fails validation.
TaskRead adds a server-generated id to the input fields. response_model validates and filters the output, documenting what clients can rely on. Never include secrets in a public response model.
model_dump() converts the validated model to a dictionary; ** expands its fields into the response dictionary. This demonstration always returns id 1 and does not save anything. The next lesson introduces storage.
2. Build and run
These are complete files, not fragments. Save them beside each other in the extracted project folder. Open http://127.0.0.1:8000/docs to send requests.
main.py
from fastapi import FastAPI
from pydantic import BaseModel, ConfigDict, Field
app = FastAPI()
class TaskCreate(BaseModel):
model_config = ConfigDict(str_strip_whitespace=True, extra="forbid")
title: str = Field(min_length=1, max_length=120)
done: bool = False
class TaskRead(TaskCreate):
id: int
@app.post("/tasks", response_model=TaskRead, status_code=201)
def create_task(task: TaskCreate):
return {"id": 1, **task.model_dump()}
requirements.txt
fastapi[standard]>=0.115,<1
pydantic>=2,<3
httpx>=0.27,<1
pytest>=8,<10
3. Check the result
- POST /tasks with {"title":"Learn Python"} returns 201, id 1 and done false.
- An empty title, missing title or unexpected field returns 422.
4. Practice independently
Require a title of at least three characters.
Show the explanation
Change min_length=1 to min_length=3, then try titles of length two and three.
When something goes wrong
For import errors, confirm the virtual environment is active and install requirements.txt using that environment’s Python. For 422, read the response detail and compare your input to the model. For 404, check the method, path and resource id. For 401 in later lessons, use Authorize in /docs with the same key configured on the server.
