0
# Core Application
1
2
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.
3
4
## Capabilities
5
6
### FastAPI Application Class
7
8
Main application class that extends Starlette's functionality with automatic OpenAPI schema generation, Pydantic integration, and enhanced developer experience.
9
10
```python { .api }
11
class FastAPI:
12
def __init__(
13
self,
14
*,
15
debug: bool = False,
16
routes: Optional[List[BaseRoute]] = None,
17
title: str = "FastAPI",
18
summary: Optional[str] = None,
19
description: str = "",
20
version: str = "0.1.0",
21
openapi_url: Optional[str] = "/openapi.json",
22
openapi_tags: Optional[List[Dict[str, Any]]] = None,
23
servers: Optional[List[Dict[str, Union[str, Any]]]] = None,
24
dependencies: Optional[Sequence[Depends]] = None,
25
default_response_class: Type[Response] = Default(JSONResponse),
26
redirect_slashes: bool = True,
27
docs_url: Optional[str] = "/docs",
28
redoc_url: Optional[str] = "/redoc",
29
swagger_ui_oauth2_redirect_url: Optional[str] = "/docs/oauth2-redirect",
30
swagger_ui_init_oauth: Optional[Dict[str, Any]] = None,
31
middleware: Optional[Sequence[Middleware]] = None,
32
exception_handlers: Optional[Dict[Union[int, Type[Exception]], Callable[[Request, Any], Coroutine[Any, Any, Response]]]] = None,
33
on_startup: Optional[Sequence[Callable[[], Any]]] = None,
34
on_shutdown: Optional[Sequence[Callable[[], Any]]] = None,
35
lifespan: Optional[Lifespan[AppType]] = None,
36
terms_of_service: Optional[str] = None,
37
contact: Optional[Dict[str, Union[str, Any]]] = None,
38
license_info: Optional[Dict[str, Union[str, Any]]] = None,
39
openapi_prefix: str = "",
40
root_path: str = "",
41
root_path_in_servers: bool = True,
42
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
43
callbacks: Optional[List[BaseRoute]] = None,
44
webhooks: Optional[APIRouter] = None,
45
deprecated: Optional[bool] = None,
46
include_in_schema: bool = True,
47
swagger_ui_parameters: Optional[Dict[str, Any]] = None,
48
generate_unique_id_function: Callable[[APIRoute], str] = Default(generate_unique_id),
49
separate_input_output_schemas: bool = True,
50
**extra: Any
51
):
52
"""
53
Create a FastAPI application instance.
54
55
Parameters:
56
- debug: Enable debug mode
57
- routes: List of route instances to include
58
- title: API title for OpenAPI documentation
59
- summary: Short summary of the API for OpenAPI documentation
60
- description: API description for OpenAPI documentation
61
- version: API version for OpenAPI documentation
62
- openapi_url: URL for OpenAPI JSON schema (set to None to disable)
63
- openapi_tags: List of tags for OpenAPI documentation
64
- servers: List of server configurations for OpenAPI
65
- dependencies: List of global dependencies applied to all routes
66
- default_response_class: Default response class for all routes
67
- docs_url: URL for Swagger UI documentation (set to None to disable)
68
- redoc_url: URL for ReDoc documentation (set to None to disable)
69
- swagger_ui_oauth2_redirect_url: OAuth2 redirect URL for Swagger UI
70
- swagger_ui_init_oauth: OAuth2 initialization configuration for Swagger UI
71
- middleware: List of middleware to include
72
- exception_handlers: Dictionary mapping exceptions to handler functions
73
- on_startup: List of functions to run on application startup (deprecated)
74
- on_shutdown: List of functions to run on application shutdown (deprecated)
75
- lifespan: Async context manager for application lifespan events
76
- terms_of_service: Terms of service URL for OpenAPI documentation
77
- contact: Contact information for OpenAPI documentation
78
- license_info: License information for OpenAPI documentation
79
- openapi_prefix: Prefix for OpenAPI URLs (deprecated, use root_path)
80
- root_path: Root path for the application
81
- root_path_in_servers: Include root_path in OpenAPI servers
82
- redirect_slashes: Automatically redirect trailing slashes
83
- responses: Default responses for all routes
84
- callbacks: List of callback routes
85
- webhooks: Optional APIRouter for webhook endpoints
86
- deprecated: Mark all routes as deprecated
87
- include_in_schema: Include routes in OpenAPI schema
88
- swagger_ui_parameters: Additional parameters for Swagger UI
89
- separate_input_output_schemas: Use separate schemas for input and output models
90
- generate_unique_id_function: Function to generate unique operation IDs
91
"""
92
```
93
94
### HTTP Method Decorators
95
96
Decorators for defining HTTP endpoints with automatic parameter parsing, validation, and OpenAPI documentation generation.
97
98
```python { .api }
99
def get(
100
self,
101
path: str,
102
*,
103
response_model: Any = Default(None),
104
status_code: Optional[int] = None,
105
tags: Optional[List[Union[str, Enum]]] = None,
106
dependencies: Optional[Sequence[Depends]] = None,
107
summary: Optional[str] = None,
108
description: Optional[str] = None,
109
response_description: str = "Successful Response",
110
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
111
deprecated: Optional[bool] = None,
112
operation_id: Optional[str] = None,
113
response_model_include: Optional[IncEx] = None,
114
response_model_exclude: Optional[IncEx] = None,
115
response_model_by_alias: bool = True,
116
response_model_exclude_unset: bool = False,
117
response_model_exclude_defaults: bool = False,
118
response_model_exclude_none: bool = False,
119
include_in_schema: bool = True,
120
response_class: Type[Response] = Default(JSONResponse),
121
name: Optional[str] = None,
122
callbacks: Optional[List[BaseRoute]] = None,
123
openapi_extra: Optional[Dict[str, Any]] = None,
124
generate_unique_id_function: Callable[[APIRoute], str] = Default(generate_unique_id)
125
) -> Callable[[DecoratedCallable], DecoratedCallable]:
126
"""
127
Create a GET endpoint decorator.
128
129
Parameters:
130
- path: URL path for the endpoint
131
- response_model: Pydantic model for response serialization
132
- status_code: HTTP status code for successful responses
133
- tags: List of tags for OpenAPI documentation
134
- dependencies: List of dependencies for this endpoint
135
- summary: Short summary for OpenAPI documentation
136
- description: Detailed description for OpenAPI documentation
137
- response_description: Description of the successful response
138
- responses: Additional response definitions
139
- deprecated: Mark endpoint as deprecated
140
- operation_id: Unique operation ID for OpenAPI
141
- response_model_include: Fields to include in response model
142
- response_model_exclude: Fields to exclude from response model
143
- response_model_by_alias: Use field aliases in response model
144
- response_model_exclude_unset: Exclude unset fields from response
145
- response_model_exclude_defaults: Exclude default values from response
146
- response_model_exclude_none: Exclude None values from response
147
- include_in_schema: Include endpoint in OpenAPI schema
148
- response_class: Response class to use for this endpoint
149
- name: Name for the endpoint (for URL reversing)
150
- callbacks: List of callback routes
151
- openapi_extra: Additional OpenAPI specification data
152
- generate_unique_id_function: Function to generate unique operation ID
153
"""
154
155
def post(self, path: str, **kwargs) -> Callable:
156
"""Create a POST endpoint decorator. Same parameters as get()."""
157
158
def put(self, path: str, **kwargs) -> Callable:
159
"""Create a PUT endpoint decorator. Same parameters as get()."""
160
161
def delete(self, path: str, **kwargs) -> Callable:
162
"""Create a DELETE endpoint decorator. Same parameters as get()."""
163
164
def patch(self, path: str, **kwargs) -> Callable:
165
"""Create a PATCH endpoint decorator. Same parameters as get()."""
166
167
def options(self, path: str, **kwargs) -> Callable:
168
"""Create an OPTIONS endpoint decorator. Same parameters as get()."""
169
170
def head(self, path: str, **kwargs) -> Callable:
171
"""Create a HEAD endpoint decorator. Same parameters as get()."""
172
173
def trace(self, path: str, **kwargs) -> Callable:
174
"""Create a TRACE endpoint decorator. Same parameters as get()."""
175
```
176
177
### WebSocket Decorator
178
179
Decorator for defining WebSocket endpoints with connection handling and message processing.
180
181
```python { .api }
182
def websocket(
183
self,
184
path: str,
185
*,
186
name: Optional[str] = None,
187
dependencies: Optional[Sequence[Depends]] = None,
188
) -> Callable[[DecoratedCallable], DecoratedCallable]:
189
"""
190
Create a WebSocket endpoint decorator.
191
192
Parameters:
193
- path: URL path for the WebSocket endpoint
194
- name: Name for the endpoint (for URL reversing)
195
- dependencies: List of dependencies for this endpoint
196
"""
197
```
198
199
### Router Management
200
201
Methods for including and managing sub-routers within the main application.
202
203
```python { .api }
204
def include_router(
205
self,
206
router: "APIRouter",
207
*,
208
prefix: str = "",
209
tags: Optional[List[Union[str, Enum]]] = None,
210
dependencies: Optional[Sequence[Depends]] = None,
211
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
212
deprecated: Optional[bool] = None,
213
include_in_schema: bool = True,
214
default_response_class: Type[Response] = Default(JSONResponse),
215
callbacks: Optional[List[BaseRoute]] = None
216
) -> None:
217
"""
218
Include an APIRouter with optional prefix and shared configuration.
219
220
Parameters:
221
- router: APIRouter instance to include
222
- prefix: URL prefix for all routes in the router
223
- tags: Tags to add to all routes in the router
224
- dependencies: Dependencies to add to all routes in the router
225
- responses: Additional responses for all routes in the router
226
- deprecated: Mark all routes in the router as deprecated
227
- include_in_schema: Include router routes in OpenAPI schema
228
- default_response_class: Default response class for router routes
229
- callbacks: Callbacks to add to all routes in the router
230
"""
231
```
232
233
### Route Management
234
235
Methods for programmatically adding routes to the application.
236
237
```python { .api }
238
def add_api_route(
239
self,
240
path: str,
241
endpoint: Callable,
242
*,
243
methods: Optional[Union[Set[str], List[str]]] = None,
244
name: Optional[str] = None,
245
dependencies: Optional[Sequence[Depends]] = None,
246
**kwargs: Any
247
) -> None:
248
"""
249
Add an API route programmatically.
250
251
Parameters:
252
- path: URL path for the route
253
- endpoint: Function to handle the route
254
- methods: HTTP methods for the route (defaults to ["GET"])
255
- name: Name for the route
256
- dependencies: Dependencies for the route
257
"""
258
259
def add_websocket_route(
260
self,
261
path: str,
262
endpoint: Callable,
263
name: Optional[str] = None
264
) -> None:
265
"""
266
Add a WebSocket route programmatically.
267
268
Parameters:
269
- path: URL path for the WebSocket route
270
- endpoint: Function to handle the WebSocket connection
271
- name: Name for the route
272
"""
273
```
274
275
### Middleware and Exception Handling
276
277
Methods for adding middleware and custom exception handlers.
278
279
```python { .api }
280
def middleware(self, middleware_type: str = "http") -> Callable:
281
"""
282
Decorator for adding middleware to the application.
283
284
Parameters:
285
- middleware_type: Type of middleware ("http" or "websocket")
286
"""
287
288
def exception_handler(
289
self,
290
exc_class_or_status_code: Union[int, Type[Exception]]
291
) -> Callable:
292
"""
293
Decorator for adding custom exception handlers.
294
295
Parameters:
296
- exc_class_or_status_code: Exception class or HTTP status code to handle
297
"""
298
```
299
300
### Application Mounting
301
302
Method for mounting WSGI or ASGI applications as sub-applications.
303
304
```python { .api }
305
def mount(
306
self,
307
path: str,
308
app: ASGIApp,
309
name: Optional[str] = None
310
) -> None:
311
"""
312
Mount a sub-application at the given path.
313
314
Parameters:
315
- path: Path to mount the application at
316
- app: WSGI or ASGI application to mount
317
- name: Name for the mounted application
318
"""
319
```
320
321
### Lifecycle Events
322
323
Method for handling application lifecycle events (deprecated in favor of lifespan parameter).
324
325
```python { .api }
326
def on_event(self, event_type: str) -> Callable:
327
"""
328
Decorator for handling application lifecycle events (deprecated).
329
330
Parameters:
331
- event_type: Event type ("startup" or "shutdown")
332
333
Note: Use the lifespan parameter in FastAPI constructor instead.
334
"""
335
```
336
337
## Usage Examples
338
339
### Basic Application Setup
340
341
```python
342
from fastapi import FastAPI
343
from pydantic import BaseModel
344
345
# Create application with metadata
346
app = FastAPI(
347
title="My API",
348
description="A sample API built with FastAPI",
349
version="1.0.0",
350
docs_url="/documentation",
351
redoc_url="/redoc"
352
)
353
354
class Item(BaseModel):
355
name: str
356
price: float
357
is_offer: bool = False
358
359
@app.get("/")
360
async def root():
361
return {"message": "Hello World"}
362
363
@app.post("/items/", response_model=Item)
364
async def create_item(item: Item):
365
return item
366
```
367
368
### Application with Global Dependencies
369
370
```python
371
from fastapi import FastAPI, Depends, HTTPException
372
from fastapi.security import HTTPBearer
373
374
security = HTTPBearer()
375
376
def verify_token(token: str = Depends(security)):
377
if token.credentials != "valid-token":
378
raise HTTPException(status_code=401, detail="Invalid token")
379
return token.credentials
380
381
# Global dependency applied to all routes
382
app = FastAPI(dependencies=[Depends(verify_token)])
383
384
@app.get("/protected")
385
async def protected_route():
386
return {"message": "This route requires authentication"}
387
```
388
389
### Application with Custom Exception Handler
390
391
```python
392
from fastapi import FastAPI, HTTPException
393
from fastapi.responses import JSONResponse
394
395
app = FastAPI()
396
397
@app.exception_handler(ValueError)
398
async def value_error_handler(request, exc):
399
return JSONResponse(
400
status_code=400,
401
content={"message": f"Value error: {str(exc)}"}
402
)
403
404
@app.get("/items/{item_id}")
405
async def get_item(item_id: int):
406
if item_id < 0:
407
raise ValueError("Item ID must be positive")
408
return {"item_id": item_id}
409
```
410
411
### Application with Lifespan Events
412
413
```python
414
from contextlib import asynccontextmanager
415
from fastapi import FastAPI
416
417
# Modern lifespan approach
418
@asynccontextmanager
419
async def lifespan(app: FastAPI):
420
# Startup
421
print("Application starting up")
422
yield
423
# Shutdown
424
print("Application shutting down")
425
426
app = FastAPI(lifespan=lifespan)
427
428
@app.get("/")
429
async def root():
430
return {"message": "Hello World"}
431
```