- Spec files
pypi-fastapi
Describes: pkg:pypi/fastapi@0.116.x
- Description
- FastAPI framework, high performance, easy to learn, fast to code, ready for production
- Author
- tessl
- Last updated
api-routing.md docs/
1# API Routing23APIRouter allows organizing and grouping related API endpoints with shared configuration, middleware, and dependencies. Routers enable modular API design and can be included in the main FastAPI application or nested within other routers.45## Capabilities67### APIRouter Class89Router for organizing related endpoints with shared configuration including URL prefixes, tags, dependencies, and response models.1011```python { .api }12class APIRouter:13def __init__(14self,15*,16prefix: str = "",17tags: List[str] = None,18dependencies: List[Depends] = None,19default_response_class: Type[Response] = Default(JSONResponse),20responses: dict = None,21callbacks: List[BaseRoute] = None,22routes: List[BaseRoute] = None,23redirect_slashes: bool = True,24default: ASGIApp = None,25dependency_overrides_provider: Any = None,26route_class: Type[APIRoute] = APIRoute,27on_startup: List[Callable] = None,28on_shutdown: List[Callable] = None,29lifespan: Lifespan = None,30deprecated: bool = None,31include_in_schema: bool = True,32generate_unique_id_function: Callable[[APIRoute], str] = Default(generate_unique_id),33**kwargs: Any,34) -> None:35"""36Create an APIRouter instance.3738Parameters:39- prefix: Common URL prefix for all routes in this router40- tags: List of tags for grouping routes in documentation41- dependencies: List of dependencies applied to all routes42- default_response_class: Default response class for all routes43- responses: Additional response models for all routes44- callbacks: List of callback routes45- routes: List of routes to include in the router46- deprecated: Mark all routes as deprecated47- include_in_schema: Include router routes in OpenAPI schema48"""49```5051### HTTP Method Decorators5253Decorators for defining API endpoints on the router with the same functionality as FastAPI application decorators.5455```python { .api }56def get(57self,58path: str,59*,60response_model: Any = Default(None),61status_code: int = None,62tags: List[str] = None,63dependencies: List[Depends] = None,64summary: str = None,65description: str = None,66response_description: str = "Successful Response",67responses: dict = None,68deprecated: bool = None,69operation_id: str = None,70response_model_include: IncEx = None,71response_model_exclude: IncEx = None,72response_model_by_alias: bool = True,73response_model_exclude_unset: bool = False,74response_model_exclude_defaults: bool = False,75response_model_exclude_none: bool = False,76include_in_schema: bool = True,77response_class: Type[Response] = Default(JSONResponse),78name: str = None,79callbacks: List[BaseRoute] = None,80openapi_extra: dict = None,81generate_unique_id_function: Callable[[APIRoute], str] = Default(generate_unique_id),82) -> Callable[[DecoratedCallable], DecoratedCallable]:83"""84Decorator for GET endpoints on this router.8586Parameters same as FastAPI.get() decorator.87"""8889def post(self, path: str, **kwargs) -> Callable[[DecoratedCallable], DecoratedCallable]:90"""Decorator for POST endpoints on this router."""9192def put(self, path: str, **kwargs) -> Callable[[DecoratedCallable], DecoratedCallable]:93"""Decorator for PUT endpoints on this router."""9495def delete(self, path: str, **kwargs) -> Callable[[DecoratedCallable], DecoratedCallable]:96"""Decorator for DELETE endpoints on this router."""9798def patch(self, path: str, **kwargs) -> Callable[[DecoratedCallable], DecoratedCallable]:99"""Decorator for PATCH endpoints on this router."""100101def head(self, path: str, **kwargs) -> Callable[[DecoratedCallable], DecoratedCallable]:102"""Decorator for HEAD endpoints on this router."""103104def options(self, path: str, **kwargs) -> Callable[[DecoratedCallable], DecoratedCallable]:105"""Decorator for OPTIONS endpoints on this router."""106107def trace(self, path: str, **kwargs) -> Callable[[DecoratedCallable], DecoratedCallable]:108"""Decorator for TRACE endpoints on this router."""109110def websocket(111self,112path: str,113*,114name: str = None,115dependencies: List[Depends] = None,116) -> Callable[[DecoratedCallable], DecoratedCallable]:117"""Decorator for WebSocket endpoints on this router."""118```119120### Router Composition121122Methods for including sub-routers and adding routes programmatically to create hierarchical API structures.123124```python { .api }125def include_router(126self,127router: APIRouter,128*,129prefix: str = "",130tags: List[str] = None,131dependencies: List[Depends] = None,132default_response_class: Type[Response] = Default(JSONResponse),133responses: dict = None,134callbacks: List[BaseRoute] = None,135deprecated: bool = None,136include_in_schema: bool = True,137generate_unique_id_function: Callable[[APIRoute], str] = Default(generate_unique_id),138) -> None:139"""140Include another APIRouter in this router.141142Parameters:143- router: APIRouter instance to include144- prefix: Additional URL prefix for the included router145- tags: Additional tags for all routes in the included router146- dependencies: Additional dependencies for all routes147- responses: Additional response models148- deprecated: Mark all included routes as deprecated149- include_in_schema: Include routes in OpenAPI schema150"""151152def add_api_route(153self,154path: str,155endpoint: Callable,156*,157methods: List[str] = None,158name: str = None,159response_model: Any = Default(None),160status_code: int = None,161tags: List[str] = None,162dependencies: List[Depends] = None,163summary: str = None,164description: str = None,165response_description: str = "Successful Response",166responses: dict = None,167deprecated: bool = None,168operation_id: str = None,169response_model_include: IncEx = None,170response_model_exclude: IncEx = None,171response_model_by_alias: bool = True,172response_model_exclude_unset: bool = False,173response_model_exclude_defaults: bool = False,174response_model_exclude_none: bool = False,175include_in_schema: bool = True,176response_class: Type[Response] = Default(JSONResponse),177callbacks: List[BaseRoute] = None,178openapi_extra: dict = None,179generate_unique_id_function: Callable[[APIRoute], str] = Default(generate_unique_id),180) -> None:181"""182Add an API route programmatically to this router.183184Parameters same as FastAPI.add_api_route() method.185"""186187def add_api_websocket_route(188self,189path: str,190endpoint: Callable,191*,192name: str = None,193dependencies: List[Depends] = None,194) -> None:195"""196Add a WebSocket route programmatically to this router.197198Parameters same as FastAPI.add_api_websocket_route() method.199"""200```201202### Route Mounting203204Method for mounting ASGI applications and static file servers.205206```python { .api }207def mount(208self,209path: str,210app: ASGIApp,211*,212name: str = None,213) -> None:214"""215Mount an ASGI application at the given path.216217Parameters:218- path: URL path where the application should be mounted219- app: ASGI application to mount220- name: Name for the mount (for URL generation)221"""222```223224### Route Classes225226Individual route representation classes used internally by APIRouter.227228```python { .api }229class APIRoute:230"""231Individual API route representation with all route metadata,232path parameters, dependencies, and response models.233"""234def __init__(235self,236path: str,237endpoint: Callable,238*,239response_model: Any = Default(None),240status_code: int = None,241tags: List[str] = None,242dependencies: List[Depends] = None,243summary: str = None,244description: str = None,245response_description: str = "Successful Response",246responses: dict = None,247deprecated: bool = None,248name: str = None,249methods: List[str] = None,250operation_id: str = None,251response_model_include: IncEx = None,252response_model_exclude: IncEx = None,253response_model_by_alias: bool = True,254response_model_exclude_unset: bool = False,255response_model_exclude_defaults: bool = False,256response_model_exclude_none: bool = False,257include_in_schema: bool = True,258response_class: Type[Response] = Default(JSONResponse),259callbacks: List[BaseRoute] = None,260generate_unique_id_function: Callable[[APIRoute], str] = Default(generate_unique_id),261openapi_extra: dict = None,262) -> None: ...263264class APIWebSocketRoute:265"""266WebSocket route representation for real-time communication endpoints.267"""268def __init__(269self,270path: str,271endpoint: Callable,272*,273name: str = None,274dependencies: List[Depends] = None,275) -> None: ...276```277278## Usage Examples279280### Basic Router Usage281282```python283from fastapi import APIRouter, FastAPI284285# Create router for user-related endpoints286users_router = APIRouter(287prefix="/users",288tags=["users"],289responses={404: {"description": "Not found"}}290)291292@users_router.get("/")293def get_users():294return [{"username": "john"}, {"username": "jane"}]295296@users_router.get("/{user_id}")297def get_user(user_id: int):298return {"user_id": user_id, "username": "john"}299300@users_router.post("/")301def create_user(user: dict):302return {"message": "User created", "user": user}303304# Include router in main application305app = FastAPI()306app.include_router(users_router)307```308309### Router with Dependencies310311```python312from fastapi import APIRouter, Depends, HTTPException313314def get_current_user():315# Authentication logic here316return {"username": "current_user"}317318def admin_required(current_user: dict = Depends(get_current_user)):319if not current_user.get("is_admin"):320raise HTTPException(status_code=403, detail="Admin access required")321return current_user322323# Router with shared dependencies324admin_router = APIRouter(325prefix="/admin",326tags=["admin"],327dependencies=[Depends(admin_required)]328)329330@admin_router.get("/users")331def list_all_users():332return {"users": ["admin", "user1", "user2"]}333334@admin_router.delete("/users/{user_id}")335def delete_user(user_id: int):336return {"message": f"User {user_id} deleted"}337```338339### Nested Routers340341```python342from fastapi import APIRouter, FastAPI343344# Create nested router structure345api_v1_router = APIRouter(prefix="/api/v1")346347users_router = APIRouter(prefix="/users", tags=["users"])348posts_router = APIRouter(prefix="/posts", tags=["posts"])349350@users_router.get("/")351def get_users():352return {"users": []}353354@posts_router.get("/")355def get_posts():356return {"posts": []}357358# Include sub-routers in API v1 router359api_v1_router.include_router(users_router)360api_v1_router.include_router(posts_router)361362# Include API v1 router in main application363app = FastAPI()364app.include_router(api_v1_router)365366# This creates endpoints:367# GET /api/v1/users/368# GET /api/v1/posts/369```370371### Router with Custom Response Models372373```python374from fastapi import APIRouter375from pydantic import BaseModel376from typing import List377378class User(BaseModel):379id: int380username: str381email: str382383class UserCreate(BaseModel):384username: str385email: str386387# Router with default response class388users_router = APIRouter(389prefix="/users",390tags=["users"],391responses={392404: {"description": "User not found"},393422: {"description": "Validation error"}394}395)396397@users_router.get("/", response_model=List[User])398def get_users():399return [400{"id": 1, "username": "john", "email": "john@example.com"},401{"id": 2, "username": "jane", "email": "jane@example.com"}402]403404@users_router.post("/", response_model=User, status_code=201)405def create_user(user: UserCreate):406return {"id": 3, **user.dict()}407```