Search Topics

Search across all FastAPI topics

GitHub

Routing

3 topics

The 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.

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 data
If 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.