3. Building Web APIs with FastAPI & Pydantic
FastAPI Essentials: Routes, Path/Query Parameters & OpenAPI Docs
Build fast, self-documenting Python web APIs with FastAPI: understand ASGI and uvicorn, route decorators, path vs query parameters, and automatic /docs Swagger UI.
- Define GET and POST route handlers using FastAPI decorators and type hints
- Distinguish required path parameters from optional query parameters
- Run a FastAPI server locally with uvicorn and inspect interactive /docs
FastAPI is one of the fastest-growing Python web frameworks because it turns standard Python type hints into request parsing, data validation, and interactive OpenAPI documentation (/docs) automatically.
1. Architecture: ASGI, Uvicorn & The FastAPI Request Flow
Older Python frameworks like Flask use WSGI (strictly synchronous, one request per thread). FastAPI is built on ASGI (Asynchronous Server Gateway Interface via Starlette + Uvicorn), allowing a single process to handle high-concurrency HTTP/WebSocket connections while still supporting regular synchronous def endpoints via a worker thread pool.
Here is what happens when a client hits a FastAPI endpoint:
Client HTTP Request (GET /courses/42?include_modules=true)
│
▼
Uvicorn (ASGI Server parses raw TCP/HTTP bytes)
│
▼
Middleware Stack (CORS, logging, compression)
│
▼
Router (Matches method + URL pattern top-to-bottom)
│
▼
Parameter & Dependency Resolution (Extracts path/query types, runs Depends())
│
▼
Route Handler ─▶ Returns dict / BaseModel ─▶ FastAPI serializes JSON Response2. Your First FastAPI App (main.py) & OpenAPI Docs
from fastapi import FastAPI
app = FastAPI(title="Yadav Academy API", version="1.0.0")
@app.get("/health")
def health_check():
return {"status": "ok"}To run it locally in your terminal with Uvicorn:
pip install "fastapi[standard]"
uvicorn main:app --reloadFastAPI automatically generates an OpenAPI 3.1 JSON specification at /openapi.json and serves two interactive documentation UIs out of the box:
/docs— Swagger UI where you can click "Try it out" and send live requests from your browser./redoc— Clean, printable ReDoc API reference for frontend teams and partners.
3. Path Parameters vs Query Parameters
FastAPI inspects both your URL template and your function signature to decide where every parameter comes from:
| Parameter Kind | Where It Appears | Required by Default? | Primary Use Case |
|---|---|---|---|
| Path parameter | Inside {...} in @app.get("/courses/{course_id}") | Yes (always required) | Identify a specific resource by ID or slug |
| Query parameter | Function arg not in URL path (after ?) | Only if no default value is given | Filter, search, sort, or paginate lists |
| Request body | Pydantic BaseModel parameter (POST/PUT/PATCH) | Yes (unless ` | None = None`) |
from typing import Annotated
from fastapi import FastAPI, Path, Query
app = FastAPI()
COURSES = [
{"id": 1, "title": "Python Fundamentals", "level": "Beginner"},
{"id": 2, "title": "Intermediate Python", "level": "Intermediate"},
{"id": 3, "title": "Python Backend", "level": "Intermediate"},
]
@app.get("/courses")
def list_courses(
level: str | None = None,
limit: Annotated[int, Query(ge=1, le=100)] = 10,
):
items = COURSES
if level:
items = [c for c in items if c["level"].lower() == level.lower()]
return items[:limit]
@app.get("/courses/{course_id}")
def get_course(course_id: Annotated[int, Path(ge=1)]):
# FastAPI automatically converts `course_id` to `int`
# and returns 422 if someone requests `/courses/abc` or `/courses/0`!
return {"requested_id": course_id}GET /courses?level=Intermediate&limit=1→level="Intermediate",limit=1GET /courses/2→course_id=2(int)GET /courses?limit=5000→422 Unprocessable Entityautomatically, protecting your database from unbounded queries!
Always define static routes like @app.get("/courses/featured") above dynamic routes like @app.get("/courses/{course_id}"). FastAPI matches routes top-to-bottom—if {course_id} comes first, "featured" matches {course_id} and crashes with a 422 trying to parse "featured" as an int!
Never write limit: int = 20 without Query(ge=1, le=100). Otherwise a client can request ?limit=10000000 or ?limit=-5, causing memory spikes or unexpected slicing behavior.
Try It Yourself in the Playground
Explore how FastAPI's URL path matching, type conversion, and query filtering work under the hood in pure Python:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: What URL query string filters list_courses(level: str | None = None, limit: int = 10) to return up to 5 "Intermediate" courses?
Quick Checkpoints
In @app.get('/users/{user_id}') def read_user(user_id: int, include_bio: bool = False):, how does FastAPI treat include_bio?
Why should @app.get('/users/me') be declared BEFORE @app.get('/users/{user_id}')?