pypi-fastapi

Description
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/pypi-fastapi@0.116.0

core-application.md docs/

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