Core Application
The FastAPI class is the central entry point for building APIs in this codebase. Inheriting from starlette.applications.Starlette, it extends the base ASGI application with features for OpenAPI schema generation, Pydantic data validation, and automatic interactive documentation.
The FastAPI Application Classโ
The FastAPI class (defined in fastapi/applications.py) serves as the primary registry for routes, middleware, and exception handlers. When you instantiate app = FastAPI(), you are creating a specialized Starlette application that manages an internal APIRouter.
Application Metadata and OpenAPIโ
The constructor accepts several parameters that configure the generated OpenAPI schema. These settings are visible in the automatic documentation at /docs (Swagger UI) or /redoc (ReDoc).
from fastapi import FastAPI
app = FastAPI(
title="ChimichangApp",
description="ChimichangApp API helps you do awesome stuff. ๐",
version="0.0.1",
contact={
"name": "Deadpoolio the Amazing",
"url": "http://x-force.example.com/contact/",
"email": "dp@x-force.example.com",
},
license_info={
"name": "Apache 2.0",
"url": "https://www.apache.org/licenses/LICENSE-2.0.html",
},
)
Key configuration attributes include:
title,summary,description, andversion: Basic API metadata.openapi_url: The path where the OpenAPI JSON is served (defaults to/openapi.json). Setting this toNonedisables all automatic documentation.root_path: Used when the application is behind a proxy (e.g., in a sub-path like/api/v1).
Lifecycle Managementโ
FastAPI manages the application lifecycle using the lifespan parameter, which accepts an asynchronous context manager. This is the modern replacement for the deprecated on_startup and on_shutdown event handlers.
The lifespan context manager allows you to perform setup (like connecting to a database or loading a machine learning model) before the application starts receiving requests, and cleanup after it stops.
from contextlib import asynccontextmanager
from fastapi import FastAPI
@asynccontextmanager
async def lifespan(app: FastAPI):
# Setup: Load resources
print("Starting up...")
yield
# Teardown: Release resources
print("Shutting down...")
app = FastAPI(lifespan=lifespan)
Routing and Path Operationsโ
While FastAPI inherits from Starlette, it does not typically use the routes parameter for configuration. Instead, it provides decorators that proxy to an internal routing.APIRouter instance.
Methods like @app.get(), @app.post(), and @app.put() are used to define "path operations". These decorators handle:
- Path Registration: Adding the route to the internal router.
- OpenAPI Integration: Extracting metadata from the function signature and docstrings.
- Dependency Injection: Resolving requirements defined via
Depends().
@app.get("/items/")
async def read_items():
return [{"name": "Katana"}]
Global Configurationโ
FastAPI allows configuring behavior globally across all routes in the application.
Global Dependenciesโ
You can apply dependencies to every path operation in the application by passing them to the dependencies parameter during instantiation.
from fastapi import Depends, FastAPI
async def verify_token():
# Global verification logic
pass
app = FastAPI(dependencies=[Depends(verify_token)])
Exception Handlersโ
Custom exception handlers are registered using the @app.exception_handler() decorator. FastAPI provides default handlers for HTTPException and RequestValidationError, but these can be overridden.
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
class CustomException(Exception):
def __init__(self, name: str):
self.name = name
app = FastAPI()
@app.exception_handler(CustomException)
async def custom_exception_handler(request: Request, exc: CustomException):
return JSONResponse(
status_code=418,
content={"message": f"Error: {exc.name}"},
)
Middleware Stackโ
FastAPI overrides Starlette's build_middleware_stack to inject AsyncExitStackMiddleware. This middleware ensures that resources (like files or dependencies with yield) are properly closed even if an exception occurs during the request. You can add your own middleware using @app.middleware("http") or app.add_middleware().
Integration with Starletteโ
The FastAPI class is a thin but powerful wrapper around Starlette. It maintains compatibility with the ASGI standard while providing a more declarative API.
app.state: Inherited from Starlette, this object allows storing arbitrary state that persists across the application's lifetime.app.user_middleware: A list ofMiddlewareobjects that are composed into the final ASGI application stack.__call__: The entry point for ASGI servers (like Uvicorn). It handles theroot_pathconfiguration before delegating to the Starlette implementation.