- 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
core-application.md docs/
1# Core Application23The FastAPI class is the main application class that serves as the central instance for managing all routes, middleware, dependencies, and configuration. It provides decorators for all HTTP methods and handles the entire application lifecycle.45## Capabilities67### FastAPI Application Class89The main application class that creates a FastAPI instance with comprehensive configuration options for API metadata, documentation, middleware, and behavior customization.1011```python { .api }12class FastAPI:13def __init__(14self,15*,16debug: bool = False,17routes: List[BaseRoute] = None,18title: str = "FastAPI",19description: str = "",20version: str = "0.1.0",21openapi_url: str = "/openapi.json",22openapi_tags: List[dict] = None,23servers: List[dict] = None,24dependencies: List[Depends] = None,25default_response_class: Type[Response] = Default(JSONResponse),26docs_url: str = "/docs",27redoc_url: str = "/redoc",28swagger_ui_oauth2_redirect_url: str = "/docs/oauth2-redirect",29swagger_ui_init_oauth: dict = None,30middleware: List[Middleware] = None,31exception_handlers: dict = None,32on_startup: List[Callable] = None,33on_shutdown: List[Callable] = None,34lifespan: Lifespan = None,35root_path: str = "",36root_path_in_servers: bool = True,37responses: dict = None,38callbacks: List[BaseRoute] = None,39webhooks: APIRouter = None,40deprecated: bool = None,41include_in_schema: bool = True,42swagger_ui_parameters: dict = None,43generate_unique_id_function: Callable[[APIRoute], str] = Default(generate_unique_id),44**extra: Any,45) -> None:46"""47Create a FastAPI application instance.4849Parameters:50- debug: Enable debug mode51- routes: List of routes to include in the application52- title: API title for documentation53- description: API description for documentation54- version: API version55- openapi_url: URL for the OpenAPI JSON schema56- openapi_tags: List of tags for grouping operations57- servers: List of servers for the API58- dependencies: List of global dependencies59- default_response_class: Default response class for routes60- docs_url: URL for Swagger UI documentation61- redoc_url: URL for ReDoc documentation62- middleware: List of middleware to include63- exception_handlers: Dictionary of exception handlers64- on_startup: List of startup event handlers65- on_shutdown: List of shutdown event handlers66- lifespan: Application lifespan context manager67"""68```6970### HTTP Method Decorators7172Decorators for defining API endpoints that handle different HTTP methods with automatic OpenAPI documentation generation.7374```python { .api }75def get(76self,77path: str,78*,79response_model: Any = Default(None),80status_code: int = None,81tags: List[str] = None,82dependencies: List[Depends] = None,83summary: str = None,84description: str = None,85response_description: str = "Successful Response",86responses: dict = None,87deprecated: bool = None,88operation_id: str = None,89response_model_include: IncEx = None,90response_model_exclude: IncEx = None,91response_model_by_alias: bool = True,92response_model_exclude_unset: bool = False,93response_model_exclude_defaults: bool = False,94response_model_exclude_none: bool = False,95include_in_schema: bool = True,96response_class: Type[Response] = Default(JSONResponse),97name: str = None,98callbacks: List[BaseRoute] = None,99openapi_extra: dict = None,100generate_unique_id_function: Callable[[APIRoute], str] = Default(generate_unique_id),101) -> Callable[[DecoratedCallable], DecoratedCallable]:102"""103Decorator for GET endpoints.104105Parameters:106- path: URL path for the endpoint107- response_model: Pydantic model for response serialization108- status_code: HTTP status code for successful responses109- tags: List of tags for grouping in documentation110- dependencies: List of dependencies for this endpoint111- summary: Short summary for documentation112- description: Detailed description for documentation113- responses: Additional response models for different status codes114- deprecated: Mark endpoint as deprecated115- include_in_schema: Include endpoint in OpenAPI schema116"""117118def post(119self,120path: str,121*,122response_model: Any = Default(None),123status_code: int = None,124tags: List[str] = None,125dependencies: List[Depends] = None,126summary: str = None,127description: str = None,128response_description: str = "Successful Response",129responses: dict = None,130deprecated: bool = None,131operation_id: str = None,132response_model_include: IncEx = None,133response_model_exclude: IncEx = None,134response_model_by_alias: bool = True,135response_model_exclude_unset: bool = False,136response_model_exclude_defaults: bool = False,137response_model_exclude_none: bool = False,138include_in_schema: bool = True,139response_class: Type[Response] = Default(JSONResponse),140name: str = None,141callbacks: List[BaseRoute] = None,142openapi_extra: dict = None,143generate_unique_id_function: Callable[[APIRoute], str] = Default(generate_unique_id),144) -> Callable[[DecoratedCallable], DecoratedCallable]:145"""Decorator for POST endpoints."""146147def put(self, path: str, **kwargs) -> Callable[[DecoratedCallable], DecoratedCallable]:148"""Decorator for PUT endpoints."""149150def delete(self, path: str, **kwargs) -> Callable[[DecoratedCallable], DecoratedCallable]:151"""Decorator for DELETE endpoints."""152153def patch(self, path: str, **kwargs) -> Callable[[DecoratedCallable], DecoratedCallable]:154"""Decorator for PATCH endpoints."""155156def head(self, path: str, **kwargs) -> Callable[[DecoratedCallable], DecoratedCallable]:157"""Decorator for HEAD endpoints."""158159def options(self, path: str, **kwargs) -> Callable[[DecoratedCallable], DecoratedCallable]:160"""Decorator for OPTIONS endpoints."""161162def trace(self, path: str, **kwargs) -> Callable[[DecoratedCallable], DecoratedCallable]:163"""Decorator for TRACE endpoints."""164```165166### WebSocket Decorator167168Decorator for defining WebSocket endpoints for real-time bidirectional communication.169170```python { .api }171def websocket(172self,173path: str,174*,175name: str = None,176dependencies: List[Depends] = None,177) -> Callable[[DecoratedCallable], DecoratedCallable]:178"""179Decorator for WebSocket endpoints.180181Parameters:182- path: WebSocket URL path183- name: Endpoint name for URL generation184- dependencies: List of dependencies for this WebSocket185"""186```187188### Router Integration189190Methods for including APIRouter instances and adding routes programmatically.191192```python { .api }193def include_router(194self,195router: APIRouter,196*,197prefix: str = "",198tags: List[str] = None,199dependencies: List[Depends] = None,200default_response_class: Type[Response] = Default(JSONResponse),201responses: dict = None,202callbacks: List[BaseRoute] = None,203deprecated: bool = None,204include_in_schema: bool = True,205generate_unique_id_function: Callable[[APIRoute], str] = Default(generate_unique_id),206) -> None:207"""208Include an APIRouter in the application.209210Parameters:211- router: APIRouter instance to include212- prefix: URL prefix for all routes in the router213- tags: List of tags to add to all routes214- dependencies: List of dependencies to add to all routes215- responses: Additional response models for all routes216- deprecated: Mark all routes as deprecated217- include_in_schema: Include router routes in OpenAPI schema218"""219220def add_api_route(221self,222path: str,223endpoint: Callable,224*,225methods: List[str] = None,226name: str = None,227response_model: Any = Default(None),228status_code: int = None,229tags: List[str] = None,230dependencies: List[Depends] = None,231summary: str = None,232description: str = None,233response_description: str = "Successful Response",234responses: dict = None,235deprecated: bool = None,236operation_id: str = None,237response_model_include: IncEx = None,238response_model_exclude: IncEx = None,239response_model_by_alias: bool = True,240response_model_exclude_unset: bool = False,241response_model_exclude_defaults: bool = False,242response_model_exclude_none: bool = False,243include_in_schema: bool = True,244response_class: Type[Response] = Default(JSONResponse),245callbacks: List[BaseRoute] = None,246openapi_extra: dict = None,247generate_unique_id_function: Callable[[APIRoute], str] = Default(generate_unique_id),248) -> None:249"""250Add an API route programmatically.251252Parameters:253- path: URL path for the route254- endpoint: Function to handle the route255- methods: List of HTTP methods for the route256- Additional parameters same as HTTP method decorators257"""258259def add_api_websocket_route(260self,261path: str,262endpoint: Callable,263*,264name: str = None,265dependencies: List[Depends] = None,266) -> None:267"""268Add a WebSocket route programmatically.269270Parameters:271- path: WebSocket URL path272- endpoint: Function to handle the WebSocket273- name: Route name for URL generation274- dependencies: List of dependencies for the WebSocket275"""276```277278### Middleware and Exception Handling279280Methods for adding middleware and exception handlers to the application.281282```python { .api }283def middleware(self, middleware_type: str) -> Callable[[Callable], Callable]:284"""285Decorator for adding middleware to the application.286287Parameters:288- middleware_type: Type of middleware ("http" for HTTP middleware)289"""290291def exception_handler(292self,293exc_class_or_status_code: Union[int, Exception]294) -> Callable[[Callable], Callable]:295"""296Decorator for adding exception handlers.297298Parameters:299- exc_class_or_status_code: Exception class or HTTP status code to handle300"""301```302303### OpenAPI Generation304305Method for generating and accessing the OpenAPI schema.306307```python { .api }308def openapi(self) -> dict:309"""310Generate and return the OpenAPI schema for the application.311312Returns:313Dictionary containing the complete OpenAPI specification314"""315```316317### Application Properties318319Key properties available on FastAPI application instances.320321```python { .api }322# Application properties323openapi_version: str # OpenAPI specification version324openapi_schema: dict # Generated OpenAPI schema (cached)325webhooks: APIRouter # APIRouter for webhook endpoints326root_path: str # Application root path327state: State # Application state object for sharing data328dependency_overrides: dict # Dependency override mapping329router: APIRouter # Main APIRouter instance330```331332## Usage Examples333334### Basic Application Setup335336```python337from fastapi import FastAPI338339# Create application with custom configuration340app = FastAPI(341title="My API",342description="A comprehensive API for my application",343version="1.0.0",344docs_url="/documentation",345redoc_url="/redoc-docs"346)347348@app.get("/")349def read_root():350return {"message": "Welcome to my API"}351352@app.get("/health")353def health_check():354return {"status": "healthy"}355```356357### Application with Global Dependencies358359```python360from fastapi import FastAPI, Depends, HTTPException361from fastapi.security import HTTPBearer362363security = HTTPBearer()364365def verify_token(token: str = Depends(security)):366if token.credentials != "valid-token":367raise HTTPException(status_code=401, detail="Invalid token")368return token369370# Global dependency applied to all routes371app = FastAPI(dependencies=[Depends(verify_token)])372373@app.get("/protected")374def protected_endpoint():375return {"message": "This is a protected endpoint"}376```377378### Application with Custom Exception Handler379380```python381from fastapi import FastAPI, HTTPException, Request382from fastapi.responses import JSONResponse383384app = FastAPI()385386@app.exception_handler(HTTPException)387async def custom_http_exception_handler(request: Request, exc: HTTPException):388return JSONResponse(389status_code=exc.status_code,390content={"error": exc.detail, "path": request.url.path}391)392393@app.get("/error")394def trigger_error():395raise HTTPException(status_code=404, detail="Resource not found")396```