Search Topics
Search across all FastAPI topics
Routing
3 topicsThe foundation of every FastAPI application. Learn how to define endpoints, extract parameters from URLs, and handle query strings.
Tip
FastAPI uses Python type hints to automatically validate path and query parameters. The same types that help your editor also power runtime validation.
How Routing Works
Step 1: URL Request
Client sends GET /items/42 to the server.
Path Operations
Define GET, POST, PUT, DELETE endpoints using Python decorators.
Path Parameters
Extract dynamic values from URL paths with automatic type validation.
Query Parameters
Handle optional and required query string parameters with defaults.
Try It: URL Pattern Matcher
These are the patterns that trip up developers most often. Switch between Wrong and Fixed to compare the code side by side.
1
Forgetting the async keyword
Using await inside a non-async function
Don't do this
main.py
@app.get("/items")
def read_items():
data = await fetch_from_db() # Error!
return dataIf you use await inside your path operation function, you must declare it as async def. Otherwise, Python will raise a SyntaxError.
2
Path order matters
Static paths should come before dynamic ones
Don't do this
main.py
@app.get("/users/{user_id}")
async def get_user(user_id: str):
return {"user_id": user_id}
@app.get("/users/me") # Never reached!
async def get_current_user():
return {"user": "current"}FastAPI evaluates paths in order. If /users/{user_id} comes first, /users/me will match it with user_id='me'. Always put fixed paths before parameterized ones.