Path params - type coercion + validation
Pathfrom fastapi import FastAPI, Path
from enum import Enum
# Basic - type declared in signature, auto-coerced
@app.get("/users/{user_id}")
async def get_user(user_id: int):
return {"user_id": user_id}
# GET /users/42 -> {"user_id": 42} (int, not "42")
# GET /users/abc -> 422 Validation Error
# Path() with numeric constraints
@app.get("/items/{item_id}")
async def get_item(
item_id: int = Path(..., gt=0, le=1000, description="Item ID (1-1000)")
):
return {"item_id": item_id}
# String path with regex pattern
@app.get("/products/{slug}")
async def get_product(
slug: str = Path(..., min_length=3, pattern=r"^[a-z0-9\-]+$")
):
return {"slug": slug}
# Enum path - restrict to specific values
class Role(str, Enum):
admin = "admin"
user = "user"
guest = "guest"
@app.get("/roles/{role}")
async def get_role(role: Role):
return {"role": role.value}
# GET /roles/admin -> OK
# GET /roles/boss -> 422 Validation Error
# Catch-all path (file paths etc.)
@app.get("/files/{file_path:path}")
async def get_file(file_path: str):
return {"path": file_path}
# GET /files/home/chandu/report.pdf -> OK