FastAPI Reads Each Parameter from the Path, Query, Body or Headers According to Its Declaration
A FastAPI endpoint never says "read this from the URL" in code: the function signature does. Where a parameter's name and type appear decides whether FastAPI looks for it in the path, the query string, the JSON body or the headers, so a misplaced declaration silently changes what clients must send.
The Rules FastAPI Applies
| Declaration | Read from | Example request |
|---|---|---|
| name appears in the path template | path | @app.get("/users/{user_id}") → /users/123 |
singular type (str, int, bool…) not in the path |
query string | def search(q: str, limit: int = 10) → /search?q=django&limit=5 |
| Pydantic model | JSON body | def create(book: BookCreate) |
Body(embed=True) |
JSON body, as a key | name: str = Body(embed=True) → {"name": "Jefferson"} |
Header() |
request header | user_agent: str = Header() reads User-Agent |
A query parameter without a default is required; give it a default (or None) to make it optional. Header() converts underscores to hyphens, since header names rarely use underscores.
Why GET Carries Its Input in the URL
GET is a safe, idempotent retrieval: caches, proxies and browser history key on the URL. HTTP defines no meaning for a GET body, and some clients and proxies drop it. Filters and search terms therefore go in the query string; bodies belong to POST, PUT and PATCH.
References
- FastAPI MOC - hub for FastAPI notes.
- Django Path Converters Validate and Type URL Segments Before the View Runs - the Django counterpart: path segments typed by converters, filters in the query string.
- FastAPI documentation: Query Parameters - how FastAPI tells path, query and body parameters apart.
- FastAPI documentation: Body - Multiple Parameters -
Body(embed=True). - FastAPI documentation: Header Parameters - underscore-to-hyphen conversion.
- HTTPie documentation: Request items -
=,==and:separators.
Review cards
Flashcard How do you make a FastAPI query parameter optional?
Give it a default value (or None). A query parameter without a default is required.
Flashcard Which header does user_agent: str = Header() read, and why?
User-Agent: Header() converts underscores to hyphens, since header names rarely use underscores.
Flashcard A client POSTs to /hello, but the route is declared GET-only as /hello/. Which two responses does it get?
First a 307 redirect to /hello/ (Starlette's redirect_slashes), then 405 Method Not Allowed, because the route doesn't accept POST.