0
# Core Application
1
2
The 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.
3
4
## Capabilities
5
6
### FastAPI Application Class
7
8
The main application class that creates a FastAPI instance with comprehensive configuration options for API metadata, documentation, middleware, and behavior customization.
9
10
```python { .api }
11
class FastAPI:
12
def __init__(
13
self,
14
*,
15
debug: bool = False,
16
routes: List[BaseRoute] = None,
17
title: str = "FastAPI",
18
description: str = "",
19
version: str = "0.1.0",
20
openapi_url: str = "/openapi.json",
21
openapi_tags: List[dict] = None,
22
servers: List[dict] = None,
23
dependencies: List[Depends] = None,
24
default_response_class: Type[Response] = Default(JSONResponse),
25
docs_url: str = "/docs",
26
redoc_url: str = "/redoc",
27
swagger_ui_oauth2_redirect_url: str = "/docs/oauth2-redirect",
28
swagger_ui_init_oauth: dict = None,
29
middleware: List[Middleware] = None,
30
exception_handlers: dict = None,
31
on_startup: List[Callable] = None,
32
on_shutdown: List[Callable] = None,
33
lifespan: Lifespan = None,
34
root_path: str = "",
35
root_path_in_servers: bool = True,
36
responses: dict = None,
37
callbacks: List[BaseRoute] = None,
38
webhooks: APIRouter = None,
39
deprecated: bool = None,
40
include_in_schema: bool = True,
41
swagger_ui_parameters: dict = None,
42
generate_unique_id_function: Callable[[APIRoute], str] = Default(generate_unique_id),
43
**extra: Any,
44
) -> None:
45
"""
46
Create a FastAPI application instance.
47
48
Parameters:
49
- debug: Enable debug mode
50
- routes: List of routes to include in the application
51
- title: API title for documentation
52
- description: API description for documentation
53
- version: API version
54
- openapi_url: URL for the OpenAPI JSON schema
55
- openapi_tags: List of tags for grouping operations
56
- servers: List of servers for the API
57
- dependencies: List of global dependencies
58
- default_response_class: Default response class for routes
59
- docs_url: URL for Swagger UI documentation
60
- redoc_url: URL for ReDoc documentation
61
- middleware: List of middleware to include
62
- exception_handlers: Dictionary of exception handlers
63
- on_startup: List of startup event handlers
64
- on_shutdown: List of shutdown event handlers
65
- lifespan: Application lifespan context manager
66
"""
67
```
68
69
### HTTP Method Decorators
70
71
Decorators for defining API endpoints that handle different HTTP methods with automatic OpenAPI documentation generation.
72
73
```python { .api }
74
def get(
75
self,
76
path: str,
77
*,
78
response_model: Any = Default(None),
79
status_code: int = None,
80
tags: List[str] = None,
81
dependencies: List[Depends] = None,
82
summary: str = None,
83
description: str = None,
84
response_description: str = "Successful Response",
85
responses: dict = None,
86
deprecated: bool = None,
87
operation_id: str = None,
88
response_model_include: IncEx = None,
89
response_model_exclude: IncEx = None,
90
response_model_by_alias: bool = True,
91
response_model_exclude_unset: bool = False,
92
response_model_exclude_defaults: bool = False,
93
response_model_exclude_none: bool = False,
94
include_in_schema: bool = True,
95
response_class: Type[Response] = Default(JSONResponse),
96
name: str = None,
97
callbacks: List[BaseRoute] = None,
98
openapi_extra: dict = None,
99
generate_unique_id_function: Callable[[APIRoute], str] = Default(generate_unique_id),
100
) -> Callable[[DecoratedCallable], DecoratedCallable]:
101
"""
102
Decorator for GET endpoints.
103
104
Parameters:
105
- path: URL path for the endpoint
106
- response_model: Pydantic model for response serialization
107
- status_code: HTTP status code for successful responses
108
- tags: List of tags for grouping in documentation
109
- dependencies: List of dependencies for this endpoint
110
- summary: Short summary for documentation
111
- description: Detailed description for documentation
112
- responses: Additional response models for different status codes
113
- deprecated: Mark endpoint as deprecated
114
- include_in_schema: Include endpoint in OpenAPI schema
115
"""
116
117
def post(
118
self,
119
path: str,
120
*,
121
response_model: Any = Default(None),
122
status_code: int = None,
123
tags: List[str] = None,
124
dependencies: List[Depends] = None,
125
summary: str = None,
126
description: str = None,
127
response_description: str = "Successful Response",
128
responses: dict = None,
129
deprecated: bool = None,
130
operation_id: str = None,
131
response_model_include: IncEx = None,
132
response_model_exclude: IncEx = None,
133
response_model_by_alias: bool = True,
134
response_model_exclude_unset: bool = False,
135
response_model_exclude_defaults: bool = False,
136
response_model_exclude_none: bool = False,
137
include_in_schema: bool = True,
138
response_class: Type[Response] = Default(JSONResponse),
139
name: str = None,
140
callbacks: List[BaseRoute] = None,
141
openapi_extra: dict = None,
142
generate_unique_id_function: Callable[[APIRoute], str] = Default(generate_unique_id),
143
) -> Callable[[DecoratedCallable], DecoratedCallable]:
144
"""Decorator for POST endpoints."""
145
146
def put(self, path: str, **kwargs) -> Callable[[DecoratedCallable], DecoratedCallable]:
147
"""Decorator for PUT endpoints."""
148
149
def delete(self, path: str, **kwargs) -> Callable[[DecoratedCallable], DecoratedCallable]:
150
"""Decorator for DELETE endpoints."""
151
152
def patch(self, path: str, **kwargs) -> Callable[[DecoratedCallable], DecoratedCallable]:
153
"""Decorator for PATCH endpoints."""
154
155
def head(self, path: str, **kwargs) -> Callable[[DecoratedCallable], DecoratedCallable]:
156
"""Decorator for HEAD endpoints."""
157
158
def options(self, path: str, **kwargs) -> Callable[[DecoratedCallable], DecoratedCallable]:
159
"""Decorator for OPTIONS endpoints."""
160
161
def trace(self, path: str, **kwargs) -> Callable[[DecoratedCallable], DecoratedCallable]:
162
"""Decorator for TRACE endpoints."""
163
```
164
165
### WebSocket Decorator
166
167
Decorator for defining WebSocket endpoints for real-time bidirectional communication.
168
169
```python { .api }
170
def websocket(
171
self,
172
path: str,
173
*,
174
name: str = None,
175
dependencies: List[Depends] = None,
176
) -> Callable[[DecoratedCallable], DecoratedCallable]:
177
"""
178
Decorator for WebSocket endpoints.
179
180
Parameters:
181
- path: WebSocket URL path
182
- name: Endpoint name for URL generation
183
- dependencies: List of dependencies for this WebSocket
184
"""
185
```
186
187
### Router Integration
188
189
Methods for including APIRouter instances and adding routes programmatically.
190
191
```python { .api }
192
def include_router(
193
self,
194
router: APIRouter,
195
*,
196
prefix: str = "",
197
tags: List[str] = None,
198
dependencies: List[Depends] = None,
199
default_response_class: Type[Response] = Default(JSONResponse),
200
responses: dict = None,
201
callbacks: List[BaseRoute] = None,
202
deprecated: bool = None,
203
include_in_schema: bool = True,
204
generate_unique_id_function: Callable[[APIRoute], str] = Default(generate_unique_id),
205
) -> None:
206
"""
207
Include an APIRouter in the application.
208
209
Parameters:
210
- router: APIRouter instance to include
211
- prefix: URL prefix for all routes in the router
212
- tags: List of tags to add to all routes
213
- dependencies: List of dependencies to add to all routes
214
- responses: Additional response models for all routes
215
- deprecated: Mark all routes as deprecated
216
- include_in_schema: Include router routes in OpenAPI schema
217
"""
218
219
def add_api_route(
220
self,
221
path: str,
222
endpoint: Callable,
223
*,
224
methods: List[str] = None,
225
name: str = None,
226
response_model: Any = Default(None),
227
status_code: int = None,
228
tags: List[str] = None,
229
dependencies: List[Depends] = None,
230
summary: str = None,
231
description: str = None,
232
response_description: str = "Successful Response",
233
responses: dict = None,
234
deprecated: bool = None,
235
operation_id: str = None,
236
response_model_include: IncEx = None,
237
response_model_exclude: IncEx = None,
238
response_model_by_alias: bool = True,
239
response_model_exclude_unset: bool = False,
240
response_model_exclude_defaults: bool = False,
241
response_model_exclude_none: bool = False,
242
include_in_schema: bool = True,
243
response_class: Type[Response] = Default(JSONResponse),
244
callbacks: List[BaseRoute] = None,
245
openapi_extra: dict = None,
246
generate_unique_id_function: Callable[[APIRoute], str] = Default(generate_unique_id),
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: List of HTTP methods for the route
255
- Additional parameters same as HTTP method decorators
256
"""
257
258
def add_api_websocket_route(
259
self,
260
path: str,
261
endpoint: Callable,
262
*,
263
name: str = None,
264
dependencies: List[Depends] = None,
265
) -> None:
266
"""
267
Add a WebSocket route programmatically.
268
269
Parameters:
270
- path: WebSocket URL path
271
- endpoint: Function to handle the WebSocket
272
- name: Route name for URL generation
273
- dependencies: List of dependencies for the WebSocket
274
"""
275
```
276
277
### Middleware and Exception Handling
278
279
Methods for adding middleware and exception handlers to the application.
280
281
```python { .api }
282
def middleware(self, middleware_type: str) -> Callable[[Callable], Callable]:
283
"""
284
Decorator for adding middleware to the application.
285
286
Parameters:
287
- middleware_type: Type of middleware ("http" for HTTP middleware)
288
"""
289
290
def exception_handler(
291
self,
292
exc_class_or_status_code: Union[int, Exception]
293
) -> Callable[[Callable], Callable]:
294
"""
295
Decorator for adding exception handlers.
296
297
Parameters:
298
- exc_class_or_status_code: Exception class or HTTP status code to handle
299
"""
300
```
301
302
### OpenAPI Generation
303
304
Method for generating and accessing the OpenAPI schema.
305
306
```python { .api }
307
def openapi(self) -> dict:
308
"""
309
Generate and return the OpenAPI schema for the application.
310
311
Returns:
312
Dictionary containing the complete OpenAPI specification
313
"""
314
```
315
316
### Application Properties
317
318
Key properties available on FastAPI application instances.
319
320
```python { .api }
321
# Application properties
322
openapi_version: str # OpenAPI specification version
323
openapi_schema: dict # Generated OpenAPI schema (cached)
324
webhooks: APIRouter # APIRouter for webhook endpoints
325
root_path: str # Application root path
326
state: State # Application state object for sharing data
327
dependency_overrides: dict # Dependency override mapping
328
router: APIRouter # Main APIRouter instance
329
```
330
331
## Usage Examples
332
333
### Basic Application Setup
334
335
```python
336
from fastapi import FastAPI
337
338
# Create application with custom configuration
339
app = FastAPI(
340
title="My API",
341
description="A comprehensive API for my application",
342
version="1.0.0",
343
docs_url="/documentation",
344
redoc_url="/redoc-docs"
345
)
346
347
@app.get("/")
348
def read_root():
349
return {"message": "Welcome to my API"}
350
351
@app.get("/health")
352
def health_check():
353
return {"status": "healthy"}
354
```
355
356
### Application with Global Dependencies
357
358
```python
359
from fastapi import FastAPI, Depends, HTTPException
360
from fastapi.security import HTTPBearer
361
362
security = HTTPBearer()
363
364
def verify_token(token: str = Depends(security)):
365
if token.credentials != "valid-token":
366
raise HTTPException(status_code=401, detail="Invalid token")
367
return token
368
369
# Global dependency applied to all routes
370
app = FastAPI(dependencies=[Depends(verify_token)])
371
372
@app.get("/protected")
373
def protected_endpoint():
374
return {"message": "This is a protected endpoint"}
375
```
376
377
### Application with Custom Exception Handler
378
379
```python
380
from fastapi import FastAPI, HTTPException, Request
381
from fastapi.responses import JSONResponse
382
383
app = FastAPI()
384
385
@app.exception_handler(HTTPException)
386
async def custom_http_exception_handler(request: Request, exc: HTTPException):
387
return JSONResponse(
388
status_code=exc.status_code,
389
content={"error": exc.detail, "path": request.url.path}
390
)
391
392
@app.get("/error")
393
def trigger_error():
394
raise HTTPException(status_code=404, detail="Resource not found")
395
```