From Function to Endpoint: Path Operations
Declare routes as decorated functions, let the signature say where each parameter comes from, set success status codes explicitly, and get the generated docs for free.
Contentsand lesson path
On this page
- Why it matters
- The route table, and why declaration order matters
- One signature, three parameter sources
- Success codes are part of the declaration
- The documentation writes itself
- Check your understanding
- Apply it
- Review prompt
Lessons of FastAPI Fundamentals
- From Function to Endpoint: Path Operations Concept · 15 min
- Lab: A CRUD Resource Held in Memory Lab · 30 min
- Validating Input and Shaping Output with Pydantic Worked example · 25 min
- Dependencies: Sharing Resources Without Globals Worked example · 20 min
- Routers, Settings and Application Lifespan Lab · 25 min
- Check: Trace a Request Through the App Knowledge check · 8 questions
What you will learn
- Implement CRUD path operations with typed path, query and body parameters and explicit success status codes.
Prerequisites: HTTP & APIs
01. Why it matters
In the HTTP API lab you served your first JSON endpoint with FastAPI: a health route, one create route, one read route. You also saw how much the framework did for you. This lesson looks closely at the mechanism behind that, because every FastAPI service you build will rest on it.
A path operation is the framework’s unit of behaviour: one decorator, such as @app.get(...), plus the function under it. That single declaration tells FastAPI which method and URL pattern the route answers, where each parameter comes from, what types are acceptable, and what appears in the generated documentation. You write plain functions; the framework does the routing, the type conversion, the validation and the serialisation.
The examples keep one running domain, a reading-list API for books, which the rest of this skill builds on. By the end of this lesson you will be able to read a route declaration and predict exactly which requests it matches, which parameters it expects, and what status code a client receives.
02. The route table, and why declaration order matters
Each decorator call registers an entry in a route table: the HTTP method, a URL pattern and the function to call. When a request arrives, the router walks that table in the order you declared the routes and uses the first entry whose pattern fits the request path. Matching is about shape, not types: the pattern /books/{book_id} fits /books/7, but it equally fits /books/search or /books/anything-at-all.
from fastapi import FastAPI, HTTPException
app = FastAPI(title='Reading List API')
BOOKS = {
1: {'id': 1, 'title': 'The Pragmatic Programmer', 'author': 'Hunt'},
2: {'id': 2, 'title': 'Refactoring', 'author': 'Fowler'},
}
@app.get('/books/search')
def search(q: str):
matches = [b for b in BOOKS.values() if q.lower() in b['title'].lower()]
return {'query': q, 'results': matches}
@app.get('/books/{book_id}')
def get_book(book_id: int):
if book_id not in BOOKS:
raise HTTPException(status_code=404, detail='book not found')
return BOOKS[book_id]from fastapi.testclient import TestClient
client = TestClient(app)
r = client.get('/books/search', params={'q': 'pro'})
print(r.status_code, [b['title'] for b in r.json()['results']])
r = client.get('/books/1')
print(r.status_code, r.json()['title'])200 ['The Pragmatic Programmer']
200 The Pragmatic ProgrammerThe first request succeeds on the first route, because search was declared before the parameterised one. Swap the two decorators and the same request still finds a route — the generic one — and the path segment search then fails the int annotation before the handler runs. The code below shows it.
A validation failure produces 422, and the response body says where the problem is. This is the rule to internalise: matching is pattern-only, types are checked afterwards, inside the framework, before your function runs. Your handler never sees a value that failed its annotation.
app2 = FastAPI()
@app2.get('/books/{book_id}')
def get_book_first(book_id: int):
return {'id': book_id}
@app2.get('/books/search')
def search_second(q: str):
return {'query': q}
client2 = TestClient(app2)
r = client2.get('/books/search', params={'q': 'pro'})
print(r.status_code, [e["loc"] for e in r.json()["detail"]])422 [['path', 'book_id']]03. One signature, three parameter sources
FastAPI decides where each function parameter comes from by looking at its type:
- a name that appears in the path template, like
book_idin/books/{book_id}, is read from the URL; - a parameter annotated with a Pydantic
BaseModelis read from the request body and validated against the model; - any other simple-typed parameter is read from the query string. Giving it a default makes it optional.
No further wiring is needed. The signature below has all three kinds: shelf from the path, book from the JSON body, quiet from the query string with a default.
from pydantic import BaseModel
class BookIn(BaseModel):
title: str
author: str
@app.post('/shelves/{shelf}/books', status_code=201)
def shelve_book(shelf: str, book: BookIn, quiet: bool = False):
return {'shelf': shelf, 'book': book.model_dump(), 'quiet': quiet}r = client.post('/shelves/to-read/books',
json={'title': 'Domain-Driven Design', 'author': 'Evans'})
print(r.status_code, r.json()['shelf'], r.json()['quiet'])
print(r.json()['book'])201 to-read False
{'title': 'Domain-Driven Design', 'author': 'Evans'}The body arrived as a typed BookIn object, not a dictionary, so a missing or misnamed field is a 422 rather than a KeyError deep inside the handler. The query parameter quiet was not sent, so the default False applied. When you want optional parameters with constraints, the modern style wraps them in Annotated, which the dependencies lesson uses for paging. Query strings and path segments are plain strings at the transport layer; FastAPI converts them to the annotated types for you.
04. Success codes are part of the declaration
A route answers 200 OK unless you say otherwise, and saying so belongs in the decorator, where it also lands in the documentation. The two codes worth setting by habit: 201 Created for routes that create a resource, and 204 No Content for deletes that return nothing. For failures, raise HTTPException with a status code and a detail message; the methods and status codes lesson explains the code families behind these choices.
@app.delete('/books/{book_id}', status_code=204)
def delete_book(book_id: int):
if book_id not in BOOKS:
raise HTTPException(status_code=404, detail='book not found')
del BOOKS[book_id]r = client.delete("/books/2")
print(r.status_code, repr(r.content))
r = client.delete("/books/2")
print(r.status_code, r.json())204 b''
404 {'detail': 'book not found'}The first delete succeeds with an empty body, exactly what 204 promises. The second still matches the route and passes validation, so it reaches the handler, which reports the missing resource. Repeating a delete that ends in 404 is fine — DELETE is idempotent, and the resource ends up deleted however many times the request is sent.
One habit is worth forming now: when a client could reasonably need the location of a new resource, return it in a Location header alongside the 201 body, as the first JSON endpoint lab did. The header costs one line and saves every client a guessing step. Errors beyond “not found” get their own machinery — exception handlers that shape whole classes of failures — which belongs to the API error handling skill later in this roadmap.
05. The documentation writes itself
Because routes, types and status codes all live in code, FastAPI generates an OpenAPI document at /openapi.json describing every route: its parameters, their types, the responses it can give. Two human-friendly pages render it: /docs, an interactive browser (Swagger UI) where you can send real requests to your running app, and /redoc for reading. Open the server, visit /docs, and try a route — this is also the cheapest way to check your own work while developing.
The document is assembled from your declarations, so its paths, parameters and schemas cannot drift from the code the way a hand-written API reference can. It knows only what you declare, though: the 404 that get_book raises appears in the document only if you also list it in the decorator's responses= argument.
r = client.get('/openapi.json')
for path in sorted(r.json()["paths"]):
print(path)/books/search
/books/{book_id}
/shelves/{shelf}/books06. Check your understanding
07. Apply it
Sketch the reading-list API you will build across this skill. On paper, write each of the five operations with its method, path and success status code: create a book, list books, read one book, replace a book, delete a book. For each, note which parameters come from the path, which from the query string and which from the body, then check your sketch against the plan in the skill page. In the next lesson you will implement exactly this set.
08. Review prompt
Without looking back: name the three sources a function parameter can come from and the rule that decides each one. Explain why /books/search can be swallowed by /books/{book_id} and what that failure looks like to a client. Finally, say which decorator argument sets the success status code and what body a 204 response carries.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.