FastAPI Path, Query and Body Parameters: Reading a 422, response_model and Depends
One small posts app shows the three places data travels in a request. post_id comes from the path, q and limit from the query string, and a PostIn body is checked by Pydantic. You'll read every 422, cut the output with response_model and count Depends calls.
What you will learn
- Tell FastAPI to read a value from the path, the query string or the JSON body
- Read a 422 error by its type, location, message and input
- Use response_model to choose the fields that go out
- Share one piece of work between routes with Depends
Before you start
- A first FastAPI app with one route
- Python type hints
Until now our small FastAPI app only sent data out. Here it starts taking data in from the client, and FastAPI reads and checks that data from the type hints we write.
Think about sending a parcel. The address on the front says where it goes. A note stuck on the side can add a wish, like "leave it at the door", and it's optional. The contents inside the box are what you're really sending. An HTTP request has the same three places.
Set up and run the project
The project starts as an empty folder, made into a uv project. --bare creates only pyproject.toml, with no sample code:
uv init --bare
uv add "fastapi[standard]"
Initialized project `s01l02-firstapp`
Using CPython 3.12.14
Creating virtual environment at: .venv
Resolved 62 packages in 61ms
Installed 59 packages in 1.03s
Fifty nine packages for one line, because the standard extras bring uvicorn (the server), fastapi-cli (the fastapi command), Jinja2, python-multipart and httpx. uv tree --depth 1 shows there's still only one direct dependency:
s01l02-firstapp v0.1.0
└── fastapi[standard] v0.163.1
Resolved 62 packages in 1ms
There's nothing to activate. uv run always uses the project's .venv, pyproject.toml lists what you asked for, and uv.lock pins the rest, so you don't need pip freeze. More on uv in Set Up a Python Project with uv, and on plain virtual environments in Python Virtual Environments.
To run the app while you write code, use fastapi dev. It starts uvicorn for you, with a reloader that restarts the server when you save:
uv run fastapi dev main.py
Using import string: main:app
Server started at http://127.0.0.1:8000
Documentation at http://127.0.0.1:8000/docs
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [65744] using WatchFiles
Or start uvicorn yourself, with no reloader: uv run uvicorn main:app. The first route, a 404 for an unknown path and the free /docs page are covered in FastAPI Hello World.
The app: posts in a plain list
Here's the whole main.py. There's no database yet, so we can focus on how data comes in:
from fastapi import Depends, FastAPI
from fastapi import HTTPException
from pydantic import BaseModel, Field
app = FastAPI()
POSTS = [
{"id": 1, "title": "Hello blog", "body": "First"},
{"id": 2, "title": "Packing a bag", "body": "Bags"},
{"id": 3, "title": "A simple pasta", "body": "Boil"},
]
calls = {"count": 0}
class PostIn(BaseModel):
title: str = Field(min_length=3, max_length=80)
body: str
class PostOut(BaseModel):
id: int
title: str
def get_posts():
calls["count"] += 1
return POSTS
@app.get("/")
async def home():
return {"message": "Hello blog, my first app."}
@app.get("/posts")
async def list_posts(
q: str = "",
limit: int = 10,
posts: list = Depends(get_posts),
):
q = q.lower()
found = [p for p in posts if q in p["title"].lower()]
return found[:limit]
@app.get("/posts/{post_id}", response_model=PostOut)
async def read_post(
post_id: int, posts=Depends(get_posts)
):
for p in posts:
if p["id"] == post_id:
return p
raise HTTPException(404, detail="No such post")
@app.post("/posts", response_model=PostOut,
status_code=201)
async def create_post(
post: PostIn, posts=Depends(get_posts)
):
new = {"id": len(posts) + 1, **post.model_dump()}
posts.append(new)
return new
@app.get("/stats")
async def stats():
return {"dependency_calls": calls["count"]}
All the outputs below come from a capture script that calls the app with FastAPI's TestClient and prints the label, the status code and the JSON body.
Path parameters
In /posts/{post_id}, the curly braces make post_id a gap in the URL that the client fills in. The function takes post_id: int, so FastAPI turns the text 2 into the number 2 before the loop compares it:
GET /posts/2 200 {"id": 2, "title": "Packing a bag"}
When the path is wrong
GET /posts/abc 422 {"detail": [{"type": "int_parsing", "loc": ["path", "post_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "abc"}]}
GET /posts/99 404 {"detail": "No such post"}
Two different failures. abc can't become an int, so FastAPI stops and read_post never runs: that's the 422. 99 is a valid number, so our function does run, finds no post and raises HTTPException(404). A 422 means FastAPI rejected the input. A 404 is our own code saying the thing isn't there.
Query parameters
q and limit aren't in the path, so FastAPI reads them from the query string. They have defaults, so they're optional:
GET /posts 200 [{"id": 1, "title": "Hello blog", "body": "First"}, {"id": 2, "title": "Packing a bag", "body": "Bags"}, {"id": 3, "title": "A simple pasta", "body": "Boil"}]
GET /posts?limit=1 200 [{"id": 1, "title": "Hello blog", "body": "First"}]
GET /posts?q=pa 200 [{"id": 2, "title": "Packing a bag", "body": "Bags"}, {"id": 3, "title": "A simple pasta", "body": "Boil"}]
GET /posts?limit=x 422 {"detail": [{"type": "int_parsing", "loc": ["query", "limit"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "x"}]}
Same error type as before, but now the location says query, then limit. The error tells you exactly where the bad value was.
A Pydantic request body
PostIn inherits from BaseModel. Field(min_length=3, max_length=80) puts rules on the title. In create_post, the parameter post: PostIn has a Pydantic type, and that tells FastAPI to read it from the JSON body. Our function gets a ready, checked PostIn object:
ok = {"title": "Tea time", "body": "Brew"}
short = {"title": "Hi", "body": "x"}
show("POST ok", c.post("/posts", json=ok))
show("POST short title", c.post("/posts", json=short))
nobody = {"title": "Tea"}
show("POST no body", c.post("/posts", json=nobody))
POST ok 201 {"id": 4, "title": "Tea time"}
POST short title 422 {"detail": [{"type": "string_too_short", "loc": ["body", "title"], "msg": "String should have at least 3 characters", "input": "Hi", "ctx": {"min_length": 3}}]}
POST no body 422 {"detail": [{"type": "missing", "loc": ["body", "body"], "msg": "Field required", "input": {"title": "Tea"}}]}
The good post gets id 4 and status 201, because the route says status_code=201. The other two never reach our code. In the last one, ["body", "body"] reads as: the first body is where FastAPI looked, the second is the field's name.
Every error item gives you four things: the type, the location, a message and the input. That's enough to fix the request without guessing.
Shaping the response with response_model
PostOut has only id and title. read_post returns the whole dict from the list, body included, but response_model=PostOut passes it through PostOut first, so the body is dropped. That's why GET /posts/2 above showed no body, and why the new post came back without one. list_posts has no response model, so it returns everything.
A field you didn't list never leaks out by mistake. The longer version, with a database row and an internal column, is in FastAPI Request and Response Models with Pydantic.
Sharing work with Depends
Three routes need the posts list. Instead of writing that code in each one, get_posts returns the list (and counts its calls), and each route asks for it with posts=Depends(get_posts).
get_posts ourselves.The capture sent ten requests to the posts routes before asking /stats:
GET /stats 200 {"dependency_calls": 10}
Ten requests, ten calls: the dependency ran once per request. Later in the track the same pattern hands each request its own database session, in FastAPI with SQLAlchemy Models and Alembic Migrations.
The docs know it all
Everything above lands in /openapi.json too. From the capture:
paths ["/", "/posts", "/posts/{post_id}", "/stats"]
path param [{"name": "post_id", "in": "path", "required": true, "schema": {"type": "integer", "title": "Post Id"}}]
query params [["q", "query", false, ""], ["limit", "query", false, 10]]
schemas ["HTTPValidationError", "PostIn", "PostOut", "ValidationError"]
PostIn {"properties": {"title": {"type": "string", "maxLength": 80, "minLength": 3, "title": "Title"}, "body": {"type": "string", "title": "Body"}}, "type": "object", "required": ["title", "body"], "title": "PostIn"}
codes ["201", "422"]
post_id is a required integer in the path. q and limit are optional query values with their defaults. PostIn keeps its length rules, and the POST route lists 201 and 422. Your type hints became the documentation.
Common mistakes
- Mixing up 422 and 404. 422 is FastAPI refusing bad input before your function runs. 404 is your own
HTTPException. - Forgetting a default on a query parameter. Without one, the value becomes required, and leaving it out gives a 422.
- Returning the whole object with no
response_model. Every field goes out, including ones you meant to keep inside. - Calling the dependency yourself. Write
Depends(get_posts)and let FastAPI call it, so it can be swapped in tests.
Quick recap
| You write | FastAPI reads it from | Bad value gives |
|---|---|---|
post_id: int in /posts/{post_id} | the path | 422 at path, post_id |
limit: int = 10 | the query string | 422 at query, limit |
post: PostIn | the JSON body | 422 at body, title |
response_model=PostOut | (output) | only id and title go out |
Depends(get_posts) | (called first) | ran 10 times for 10 requests |
Try it yourself
Add a query parameter called skip to list_posts, an int with a default of 0, or ask an AI tool to add it and read its change. Then send ?skip=x and read the 422: which location does it point at?
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose
Stop sending your database rows to clients. A BookRequest model decides what may come in, a BookResponse model decides what goes out, and an internal shelf_code stays in the database.
Validation and Problem Details in FastAPI: From a 422 to One Error Shape for the Whole API
A book with an empty title and 0 pages is stopped at the door. See FastAPI's own 422 answer, then turn it into a 400 Problem Detail with field errors, and give the 404 for a missing book the same shape.
