FastAPI framework, high performance, easy to learn, fast to code, ready for production - slim version without standard dependencies
—
The FastAPI class provides the main application interface for creating web APIs with automatic OpenAPI documentation generation, request/response validation, dependency injection, and ASGI compatibility.
Main application class that extends Starlette's functionality with automatic OpenAPI schema generation, Pydantic integration, and enhanced developer experience.
class FastAPI:
def __init__(
self,
*,
debug: bool = False,
routes: Optional[List[BaseRoute]] = None,
title: str = "FastAPI",
summary: Optional[str] = None,
description: str = "",
version: str = "0.1.0",
openapi_url: Optional[str] = "/openapi.json",
openapi_tags: Optional[List[Dict[str, Any]]] = None,
servers: Optional[List[Dict[str, Union[str, Any]]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
default_response_class: Type[Response] = Default(JSONResponse),
redirect_slashes: bool = True,
docs_url: Optional[str] = "/docs",
redoc_url: Optional[str] = "/redoc",
swagger_ui_oauth2_redirect_url: Optional[str] = "/docs/oauth2-redirect",
swagger_ui_init_oauth: Optional[Dict[str, Any]] = None,
middleware: Optional[Sequence[Middleware]] = None,
exception_handlers: Optional[Dict[Union[int, Type[Exception]], Callable[[Request, Any], Coroutine[Any, Any, Response]]]] = None,
on_startup: Optional[Sequence[Callable[[], Any]]] = None,
on_shutdown: Optional[Sequence[Callable[[], Any]]] = None,
lifespan: Optional[Lifespan[AppType]] = None,
terms_of_service: Optional[str] = None,
contact: Optional[Dict[str, Union[str, Any]]] = None,
license_info: Optional[Dict[str, Union[str, Any]]] = None,
openapi_prefix: str = "",
root_path: str = "",
root_path_in_servers: bool = True,
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
callbacks: Optional[List[BaseRoute]] = None,
webhooks: Optional[APIRouter] = None,
deprecated: Optional[bool] = None,
include_in_schema: bool = True,
swagger_ui_parameters: Optional[Dict[str, Any]] = None,
generate_unique_id_function: Callable[[APIRoute], str] = Default(generate_unique_id),
separate_input_output_schemas: bool = True,
**extra: Any
):
"""
Create a FastAPI application instance.
Parameters:
- debug: Enable debug mode
- routes: List of route instances to include
- title: API title for OpenAPI documentation
- summary: Short summary of the API for OpenAPI documentation
- description: API description for OpenAPI documentation
- version: API version for OpenAPI documentation
- openapi_url: URL for OpenAPI JSON schema (set to None to disable)
- openapi_tags: List of tags for OpenAPI documentation
- servers: List of server configurations for OpenAPI
- dependencies: List of global dependencies applied to all routes
- default_response_class: Default response class for all routes
- docs_url: URL for Swagger UI documentation (set to None to disable)
- redoc_url: URL for ReDoc documentation (set to None to disable)
- swagger_ui_oauth2_redirect_url: OAuth2 redirect URL for Swagger UI
- swagger_ui_init_oauth: OAuth2 initialization configuration for Swagger UI
- middleware: List of middleware to include
- exception_handlers: Dictionary mapping exceptions to handler functions
- on_startup: List of functions to run on application startup (deprecated)
- on_shutdown: List of functions to run on application shutdown (deprecated)
- lifespan: Async context manager for application lifespan events
- terms_of_service: Terms of service URL for OpenAPI documentation
- contact: Contact information for OpenAPI documentation
- license_info: License information for OpenAPI documentation
- openapi_prefix: Prefix for OpenAPI URLs (deprecated, use root_path)
- root_path: Root path for the application
- root_path_in_servers: Include root_path in OpenAPI servers
- redirect_slashes: Automatically redirect trailing slashes
- responses: Default responses for all routes
- callbacks: List of callback routes
- webhooks: Optional APIRouter for webhook endpoints
- deprecated: Mark all routes as deprecated
- include_in_schema: Include routes in OpenAPI schema
- swagger_ui_parameters: Additional parameters for Swagger UI
- separate_input_output_schemas: Use separate schemas for input and output models
- generate_unique_id_function: Function to generate unique operation IDs
"""Decorators for defining HTTP endpoints with automatic parameter parsing, validation, and OpenAPI documentation generation.
def get(
self,
path: str,
*,
response_model: Any = Default(None),
status_code: Optional[int] = None,
tags: Optional[List[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
summary: Optional[str] = None,
description: Optional[str] = None,
response_description: str = "Successful Response",
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
deprecated: Optional[bool] = None,
operation_id: Optional[str] = None,
response_model_include: Optional[IncEx] = None,
response_model_exclude: Optional[IncEx] = None,
response_model_by_alias: bool = True,
response_model_exclude_unset: bool = False,
response_model_exclude_defaults: bool = False,
response_model_exclude_none: bool = False,
include_in_schema: bool = True,
response_class: Type[Response] = Default(JSONResponse),
name: Optional[str] = None,
callbacks: Optional[List[BaseRoute]] = None,
openapi_extra: Optional[Dict[str, Any]] = None,
generate_unique_id_function: Callable[[APIRoute], str] = Default(generate_unique_id)
) -> Callable[[DecoratedCallable], DecoratedCallable]:
"""
Create a GET endpoint decorator.
Parameters:
- path: URL path for the endpoint
- response_model: Pydantic model for response serialization
- status_code: HTTP status code for successful responses
- tags: List of tags for OpenAPI documentation
- dependencies: List of dependencies for this endpoint
- summary: Short summary for OpenAPI documentation
- description: Detailed description for OpenAPI documentation
- response_description: Description of the successful response
- responses: Additional response definitions
- deprecated: Mark endpoint as deprecated
- operation_id: Unique operation ID for OpenAPI
- response_model_include: Fields to include in response model
- response_model_exclude: Fields to exclude from response model
- response_model_by_alias: Use field aliases in response model
- response_model_exclude_unset: Exclude unset fields from response
- response_model_exclude_defaults: Exclude default values from response
- response_model_exclude_none: Exclude None values from response
- include_in_schema: Include endpoint in OpenAPI schema
- response_class: Response class to use for this endpoint
- name: Name for the endpoint (for URL reversing)
- callbacks: List of callback routes
- openapi_extra: Additional OpenAPI specification data
- generate_unique_id_function: Function to generate unique operation ID
"""
def post(self, path: str, **kwargs) -> Callable:
"""Create a POST endpoint decorator. Same parameters as get()."""
def put(self, path: str, **kwargs) -> Callable:
"""Create a PUT endpoint decorator. Same parameters as get()."""
def delete(self, path: str, **kwargs) -> Callable:
"""Create a DELETE endpoint decorator. Same parameters as get()."""
def patch(self, path: str, **kwargs) -> Callable:
"""Create a PATCH endpoint decorator. Same parameters as get()."""
def options(self, path: str, **kwargs) -> Callable:
"""Create an OPTIONS endpoint decorator. Same parameters as get()."""
def head(self, path: str, **kwargs) -> Callable:
"""Create a HEAD endpoint decorator. Same parameters as get()."""
def trace(self, path: str, **kwargs) -> Callable:
"""Create a TRACE endpoint decorator. Same parameters as get()."""Decorator for defining WebSocket endpoints with connection handling and message processing.
def websocket(
self,
path: str,
*,
name: Optional[str] = None,
dependencies: Optional[Sequence[Depends]] = None,
) -> Callable[[DecoratedCallable], DecoratedCallable]:
"""
Create a WebSocket endpoint decorator.
Parameters:
- path: URL path for the WebSocket endpoint
- name: Name for the endpoint (for URL reversing)
- dependencies: List of dependencies for this endpoint
"""Methods for including and managing sub-routers within the main application.
def include_router(
self,
router: "APIRouter",
*,
prefix: str = "",
tags: Optional[List[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
deprecated: Optional[bool] = None,
include_in_schema: bool = True,
default_response_class: Type[Response] = Default(JSONResponse),
callbacks: Optional[List[BaseRoute]] = None
) -> None:
"""
Include an APIRouter with optional prefix and shared configuration.
Parameters:
- router: APIRouter instance to include
- prefix: URL prefix for all routes in the router
- tags: Tags to add to all routes in the router
- dependencies: Dependencies to add to all routes in the router
- responses: Additional responses for all routes in the router
- deprecated: Mark all routes in the router as deprecated
- include_in_schema: Include router routes in OpenAPI schema
- default_response_class: Default response class for router routes
- callbacks: Callbacks to add to all routes in the router
"""Methods for programmatically adding routes to the application.
def add_api_route(
self,
path: str,
endpoint: Callable,
*,
methods: Optional[Union[Set[str], List[str]]] = None,
name: Optional[str] = None,
dependencies: Optional[Sequence[Depends]] = None,
**kwargs: Any
) -> None:
"""
Add an API route programmatically.
Parameters:
- path: URL path for the route
- endpoint: Function to handle the route
- methods: HTTP methods for the route (defaults to ["GET"])
- name: Name for the route
- dependencies: Dependencies for the route
"""
def add_websocket_route(
self,
path: str,
endpoint: Callable,
name: Optional[str] = None
) -> None:
"""
Add a WebSocket route programmatically.
Parameters:
- path: URL path for the WebSocket route
- endpoint: Function to handle the WebSocket connection
- name: Name for the route
"""Methods for adding middleware and custom exception handlers.
def middleware(self, middleware_type: str = "http") -> Callable:
"""
Decorator for adding middleware to the application.
Parameters:
- middleware_type: Type of middleware ("http" or "websocket")
"""
def exception_handler(
self,
exc_class_or_status_code: Union[int, Type[Exception]]
) -> Callable:
"""
Decorator for adding custom exception handlers.
Parameters:
- exc_class_or_status_code: Exception class or HTTP status code to handle
"""Method for mounting WSGI or ASGI applications as sub-applications.
def mount(
self,
path: str,
app: ASGIApp,
name: Optional[str] = None
) -> None:
"""
Mount a sub-application at the given path.
Parameters:
- path: Path to mount the application at
- app: WSGI or ASGI application to mount
- name: Name for the mounted application
"""Method for handling application lifecycle events (deprecated in favor of lifespan parameter).
def on_event(self, event_type: str) -> Callable:
"""
Decorator for handling application lifecycle events (deprecated).
Parameters:
- event_type: Event type ("startup" or "shutdown")
Note: Use the lifespan parameter in FastAPI constructor instead.
"""from fastapi import FastAPI
from pydantic import BaseModel
# Create application with metadata
app = FastAPI(
title="My API",
description="A sample API built with FastAPI",
version="1.0.0",
docs_url="/documentation",
redoc_url="/redoc"
)
class Item(BaseModel):
name: str
price: float
is_offer: bool = False
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.post("/items/", response_model=Item)
async def create_item(item: Item):
return itemfrom fastapi import FastAPI, Depends, HTTPException
from fastapi.security import HTTPBearer
security = HTTPBearer()
def verify_token(token: str = Depends(security)):
if token.credentials != "valid-token":
raise HTTPException(status_code=401, detail="Invalid token")
return token.credentials
# Global dependency applied to all routes
app = FastAPI(dependencies=[Depends(verify_token)])
@app.get("/protected")
async def protected_route():
return {"message": "This route requires authentication"}from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
app = FastAPI()
@app.exception_handler(ValueError)
async def value_error_handler(request, exc):
return JSONResponse(
status_code=400,
content={"message": f"Value error: {str(exc)}"}
)
@app.get("/items/{item_id}")
async def get_item(item_id: int):
if item_id < 0:
raise ValueError("Item ID must be positive")
return {"item_id": item_id}from contextlib import asynccontextmanager
from fastapi import FastAPI
# Modern lifespan approach
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup
print("Application starting up")
yield
# Shutdown
print("Application shutting down")
app = FastAPI(lifespan=lifespan)
@app.get("/")
async def root():
return {"message": "Hello World"}Install with Tessl CLI
npx tessl i tessl/pypi-fastapi-slim