Path parameters vs query parameters

Difficulty: Beginner

Question

How does FastAPI distinguish between path parameters and query parameters? How are they declared?

Answer

Path parameters are part of the URL path, declared using `{param}` in the path string and as function arguments with matching names. They are required.

Query parameters are everything in the URL after `?`, declared as function arguments that are NOT path parameters. They can be optional with default values.

FastAPI uses Python type hints to automatically parse and validate both types. If a parameter has a default value of `None` with `Optional[T]`, it becomes an optional query parameter.

Code examples

Path and query parameters

from fastapi import FastAPI
from typing import Optional

app = FastAPI()

@app.get("/items/{item_id}")
def get_item(
    item_id: int,          # path parameter - required
    q: Optional[str] = None,  # query parameter - optional
    limit: int = 10,       # query parameter - optional with default
):
    result = {"item_id": item_id, "limit": limit}
    if q:
        result["q"] = q
    return result

# GET /items/5?q=search&limit=20
# => {"item_id": 5, "limit": 20, "q": "search"}

Key points

Concepts covered

path parameters, query parameters, type coercion, Optional