Instructions for FastAPI Routing
Handle FastAPI routing as follows:
- •
Path Operations:
- •Use decorators:
@app.get("/items/{item_id}"),@app.post("/items/"), etc. - •Support GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD, TRACE.
- •Use decorators:
- •
Path Parameters:
- •Define in path:
{item_id}. - •Type hint:
def get_item(item_id: int): .... - •Validation: Automatic type conversion and error handling.
- •Define in path:
- •
Query Parameters:
- •Not in path:
def list_items(skip: int = 0, limit: int = 10): .... - •Optional: Use
= NoneorQuery(None)for advanced.
- •Not in path:
- •
Request Body:
- •Use Pydantic models:
from pydantic import BaseModel. - •
def create_item(item: Item): ...where Item is a BaseModel.
- •Use Pydantic models:
- •
Advanced Routing:
- •Path converters:
{item_id:uuid}. - •Sub-applications:
app.include_router(router, prefix="/api/v1").
- •Path converters:
- •
Best Practices:
- •Keep routes organized in routers.
- •Handle status codes:
return {"item": item}, status_code=201. - •Use enums for fixed values.
References
Use the shared references located at: ../_shared/reference.md