📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials FastAPI Path and Query Parameters

Path and Query Parameters

5 min read Quiz at the end
Declare and validate path params with Path(), query params with Query(), and type converters.

Path and Query Parameters

from fastapi import FastAPI, Query, Path
from typing import Optional

app = FastAPI()

# Path parameter with validation
@app.get("/users/{user_id}")
def get_user(
    user_id: int = Path(ge=1, description="User ID (must be >= 1)")
):
    return {"user_id": user_id}

# Query parameters
@app.get("/posts")
def list_posts(
    page:     int           = Query(default=1, ge=1),
    per_page: int           = Query(default=10, ge=1, le=100),
    q:        Optional[str] = Query(default=None, min_length=2),
    sort:     str           = Query(default="created_at", regex="^(created_at|views|title)$"),
):
    return {"page": page, "per_page": per_page, "q": q, "sort": sort}

# Multiple values
@app.get("/items")
def list_items(tags: list[str] = Query(default=[])):
    return {"tags": tags}
# GET /items?tags=python&tags=fastapi
Topic Quiz · 2 questions

Test your understanding before moving on

1. What does Query(ge=1) validate?
💡 ge=1 means greater than or equal to 1 — Pydantic validates this automatically.
2. How do you declare optional query params?
💡 Both Query(default=None) and = None declare optional query parameters.