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

index.md docs/

1
# FastAPI
2
3
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints. It provides automatic API documentation, data validation, serialization, and authentication capabilities with exceptional performance on par with NodeJS and Go.
4
5
## Package Information
6
7
- **Package Name**: fastapi
8
- **Language**: Python
9
- **Installation**: `pip install fastapi`
10
- **Requirements**: Python 3.8+
11
- **Main Dependencies**: Starlette, Pydantic
12
13
## Core Imports
14
15
```python
16
from fastapi import FastAPI
17
```
18
19
Common imports for building APIs:
20
21
```python
22
from fastapi import FastAPI, APIRouter, Depends, HTTPException
23
from fastapi import Query, Path, Body, Header, Cookie, Form, File
24
from fastapi import Request, Response, BackgroundTasks
25
from fastapi import WebSocket, WebSocketDisconnect
26
from fastapi import UploadFile, __version__, status
27
from fastapi.security import HTTPBearer, OAuth2PasswordBearer, APIKeyHeader
28
from fastapi.middleware.cors import CORSMiddleware
29
from fastapi.responses import JSONResponse, HTMLResponse, RedirectResponse
30
from fastapi.staticfiles import StaticFiles
31
from fastapi.templating import Jinja2Templates
32
from fastapi.testclient import TestClient
33
from fastapi.encoders import jsonable_encoder
34
```
35
36
## Basic Usage
37
38
```python
39
from fastapi import FastAPI, Query
40
from typing import Optional
41
42
# Create FastAPI application
43
app = FastAPI(
44
title="My API",
45
description="A simple API example",
46
version="1.0.0"
47
)
48
49
# Simple GET endpoint
50
@app.get("/")
51
def read_root():
52
return {"Hello": "World"}
53
54
# GET endpoint with path parameter
55
@app.get("/items/{item_id}")
56
def read_item(item_id: int, q: Optional[str] = Query(None)):
57
return {"item_id": item_id, "q": q}
58
59
# POST endpoint with request body
60
from pydantic import BaseModel
61
62
class Item(BaseModel):
63
name: str
64
price: float
65
is_offer: Optional[bool] = None
66
67
@app.post("/items/")
68
def create_item(item: Item):
69
return item
70
71
# Run the application (for development)
72
if __name__ == "__main__":
73
import uvicorn
74
uvicorn.run(app, host="0.0.0.0", port=8000)
75
```
76
77
## Architecture
78
79
FastAPI builds on the Starlette ASGI framework and uses Pydantic for data validation:
80
81
- **FastAPI Application**: Main application class that manages routes, middleware, and configuration
82
- **APIRouter**: Router for organizing and grouping related endpoints
83
- **Parameter Functions**: Type-safe parameter declaration (Query, Path, Body, etc.)
84
- **Pydantic Integration**: Automatic request/response validation and serialization
85
- **Starlette Foundation**: High-performance ASGI framework providing core web functionality
86
- **Automatic Documentation**: OpenAPI schema generation with interactive Swagger UI and ReDoc
87
88
This architecture enables rapid development of production-ready APIs with automatic validation, serialization, and documentation generation while maintaining high performance and type safety.
89
90
## Capabilities
91
92
### Core Application
93
94
Main FastAPI application class and basic routing functionality. The FastAPI class serves as the central application instance that manages all routes, middleware, dependencies, and configuration.
95
96
```python { .api }
97
class FastAPI:
98
def __init__(
99
self,
100
*,
101
debug: bool = False,
102
routes: List[BaseRoute] = None,
103
title: str = "FastAPI",
104
description: str = "",
105
version: str = "0.1.0",
106
openapi_url: str = "/openapi.json",
107
openapi_tags: List[dict] = None,
108
servers: List[dict] = None,
109
dependencies: List[Depends] = None,
110
default_response_class: Type[Response] = Default(JSONResponse),
111
docs_url: str = "/docs",
112
redoc_url: str = "/redoc",
113
swagger_ui_oauth2_redirect_url: str = "/docs/oauth2-redirect",
114
swagger_ui_init_oauth: dict = None,
115
middleware: List[Middleware] = None,
116
exception_handlers: dict = None,
117
on_startup: List[Callable] = None,
118
on_shutdown: List[Callable] = None,
119
lifespan: Lifespan = None,
120
**extra: Any,
121
) -> None: ...
122
123
def get(self, path: str, **kwargs) -> Callable: ...
124
def post(self, path: str, **kwargs) -> Callable: ...
125
def put(self, path: str, **kwargs) -> Callable: ...
126
def delete(self, path: str, **kwargs) -> Callable: ...
127
def patch(self, path: str, **kwargs) -> Callable: ...
128
def head(self, path: str, **kwargs) -> Callable: ...
129
def options(self, path: str, **kwargs) -> Callable: ...
130
def trace(self, path: str, **kwargs) -> Callable: ...
131
def websocket(self, path: str, **kwargs) -> Callable: ...
132
133
def include_router(self, router: APIRouter, **kwargs) -> None: ...
134
def add_api_route(self, path: str, endpoint: Callable, **kwargs) -> None: ...
135
def add_api_websocket_route(self, path: str, endpoint: Callable, **kwargs) -> None: ...
136
def middleware(self, middleware_type: str) -> Callable: ...
137
def exception_handler(self, exc_class_or_status_code: Union[int, Exception]) -> Callable: ...
138
```
139
140
[Core Application](./core-application.md)
141
142
### API Routing
143
144
Router for organizing and grouping related API endpoints with shared configuration, middleware, and dependencies.
145
146
```python { .api }
147
class APIRouter:
148
def __init__(
149
self,
150
*,
151
prefix: str = "",
152
tags: List[str] = None,
153
dependencies: List[Depends] = None,
154
default_response_class: Type[Response] = Default(JSONResponse),
155
responses: dict = None,
156
callbacks: List[BaseRoute] = None,
157
routes: List[BaseRoute] = None,
158
redirect_slashes: bool = True,
159
default: ASGIApp = None,
160
dependency_overrides_provider: Any = None,
161
route_class: Type[APIRoute] = APIRoute,
162
on_startup: List[Callable] = None,
163
on_shutdown: List[Callable] = None,
164
lifespan: Lifespan = None,
165
deprecated: bool = None,
166
include_in_schema: bool = True,
167
**kwargs: Any,
168
) -> None: ...
169
170
def get(self, path: str, **kwargs) -> Callable: ...
171
def post(self, path: str, **kwargs) -> Callable: ...
172
def put(self, path: str, **kwargs) -> Callable: ...
173
def delete(self, path: str, **kwargs) -> Callable: ...
174
def patch(self, path: str, **kwargs) -> Callable: ...
175
def head(self, path: str, **kwargs) -> Callable: ...
176
def options(self, path: str, **kwargs) -> Callable: ...
177
def trace(self, path: str, **kwargs) -> Callable: ...
178
def websocket(self, path: str, **kwargs) -> Callable: ...
179
180
def include_router(self, router: APIRouter, **kwargs) -> None: ...
181
def add_api_route(self, path: str, endpoint: Callable, **kwargs) -> None: ...
182
```
183
184
[API Routing](./api-routing.md)
185
186
### Request Parameters
187
188
Type-safe parameter declaration functions for handling path parameters, query parameters, headers, cookies, request bodies, form data, and file uploads.
189
190
```python { .api }
191
def Path(
192
default: Any = ...,
193
*,
194
alias: str = None,
195
title: str = None,
196
description: str = None,
197
gt: float = None,
198
ge: float = None,
199
lt: float = None,
200
le: float = None,
201
min_length: int = None,
202
max_length: int = None,
203
regex: str = None,
204
example: Any = None,
205
examples: dict = None,
206
deprecated: bool = None,
207
include_in_schema: bool = True,
208
**extra: Any,
209
) -> Any: ...
210
211
def Query(
212
default: Any = Undefined,
213
*,
214
alias: str = None,
215
title: str = None,
216
description: str = None,
217
gt: float = None,
218
ge: float = None,
219
lt: float = None,
220
le: float = None,
221
min_length: int = None,
222
max_length: int = None,
223
regex: str = None,
224
example: Any = None,
225
examples: dict = None,
226
deprecated: bool = None,
227
include_in_schema: bool = True,
228
**extra: Any,
229
) -> Any: ...
230
231
def Body(
232
default: Any = Undefined,
233
*,
234
embed: bool = None,
235
media_type: str = "application/json",
236
alias: str = None,
237
title: str = None,
238
description: str = None,
239
example: Any = None,
240
examples: dict = None,
241
deprecated: bool = None,
242
include_in_schema: bool = True,
243
**extra: Any,
244
) -> Any: ...
245
246
def Form(
247
default: Any = Undefined,
248
*,
249
media_type: str = "application/x-www-form-urlencoded",
250
alias: str = None,
251
title: str = None,
252
description: str = None,
253
example: Any = None,
254
examples: dict = None,
255
deprecated: bool = None,
256
include_in_schema: bool = True,
257
**extra: Any,
258
) -> Any: ...
259
260
def File(
261
default: Any = Undefined,
262
*,
263
media_type: str = "multipart/form-data",
264
alias: str = None,
265
title: str = None,
266
description: str = None,
267
example: Any = None,
268
examples: dict = None,
269
deprecated: bool = None,
270
include_in_schema: bool = True,
271
**extra: Any,
272
) -> Any: ...
273
```
274
275
[Request Parameters](./request-parameters.md)
276
277
### Dependency Injection
278
279
Powerful dependency injection system for sharing code, database connections, authentication, and other common functionality across endpoints.
280
281
```python { .api }
282
def Depends(dependency: Callable = None, *, use_cache: bool = True) -> Any: ...
283
284
def Security(
285
dependency: Callable = None,
286
*,
287
scopes: List[str] = None,
288
use_cache: bool = True,
289
) -> Any: ...
290
```
291
292
[Dependency Injection](./dependency-injection.md)
293
294
### Request and Response Handling
295
296
Request and response objects for accessing HTTP data and customizing response behavior.
297
298
```python { .api }
299
class Request:
300
# Starlette Request object with all HTTP request functionality
301
pass
302
303
class Response:
304
def __init__(
305
self,
306
content: Any = None,
307
status_code: int = 200,
308
headers: dict = None,
309
media_type: str = None,
310
background: BackgroundTask = None,
311
) -> None: ...
312
313
class JSONResponse(Response):
314
def __init__(
315
self,
316
content: Any = None,
317
status_code: int = 200,
318
headers: dict = None,
319
media_type: str = "application/json",
320
background: BackgroundTask = None,
321
) -> None: ...
322
323
class UploadFile:
324
filename: str
325
content_type: str
326
file: BinaryIO
327
328
async def read(self, size: int = -1) -> bytes: ...
329
async def readline(self, size: int = -1) -> bytes: ...
330
async def readlines(self) -> List[bytes]: ...
331
async def write(self, data: bytes) -> None: ...
332
async def seek(self, offset: int) -> None: ...
333
async def close(self) -> None: ...
334
```
335
336
[Request and Response](./request-response.md)
337
338
### WebSocket Support
339
340
WebSocket support for real-time bidirectional communication between client and server.
341
342
```python { .api }
343
class WebSocket:
344
# Starlette WebSocket object with full WebSocket functionality
345
async def accept(self, subprotocol: str = None, headers: dict = None) -> None: ...
346
async def receive_text(self) -> str: ...
347
async def receive_bytes(self) -> bytes: ...
348
async def receive_json(self) -> Any: ...
349
async def send_text(self, data: str) -> None: ...
350
async def send_bytes(self, data: bytes) -> None: ...
351
async def send_json(self, data: Any) -> None: ...
352
async def close(self, code: int = 1000, reason: str = None) -> None: ...
353
354
class WebSocketDisconnect(Exception):
355
def __init__(self, code: int = 1000, reason: str = None) -> None: ...
356
```
357
358
[WebSocket Support](./websocket-support.md)
359
360
### Security and Authentication
361
362
Comprehensive security components for API key authentication, HTTP authentication (Basic, Bearer, Digest), and OAuth2 flows.
363
364
```python { .api }
365
class HTTPBearer:
366
def __init__(
367
self,
368
*,
369
bearerFormat: str = None,
370
scheme_name: str = None,
371
description: str = None,
372
auto_error: bool = True,
373
) -> None: ...
374
375
class OAuth2PasswordBearer:
376
def __init__(
377
self,
378
tokenUrl: str,
379
*,
380
scheme_name: str = None,
381
scopes: dict = None,
382
description: str = None,
383
auto_error: bool = True,
384
) -> None: ...
385
386
class APIKeyHeader:
387
def __init__(
388
self,
389
*,
390
name: str,
391
scheme_name: str = None,
392
description: str = None,
393
auto_error: bool = True,
394
) -> None: ...
395
```
396
397
[Security and Authentication](./security-authentication.md)
398
399
### Exception Handling
400
401
Exception classes for handling HTTP errors and WebSocket errors with proper status codes and error details.
402
403
```python { .api }
404
class HTTPException(Exception):
405
def __init__(
406
self,
407
status_code: int,
408
detail: Any = None,
409
headers: dict = None,
410
) -> None: ...
411
412
status_code: int
413
detail: Any
414
headers: dict
415
416
class WebSocketException(Exception):
417
def __init__(self, code: int, reason: str = None) -> None: ...
418
419
code: int
420
reason: str
421
```
422
423
[Exception Handling](./exception-handling.md)
424
425
### Middleware
426
427
Middleware components for cross-cutting concerns like CORS, compression, security headers, and custom request/response processing.
428
429
```python { .api }
430
class CORSMiddleware:
431
def __init__(
432
self,
433
app: ASGIApp,
434
*,
435
allow_origins: List[str] = None,
436
allow_methods: List[str] = None,
437
allow_headers: List[str] = None,
438
allow_credentials: bool = False,
439
allow_origin_regex: str = None,
440
expose_headers: List[str] = None,
441
max_age: int = 600,
442
) -> None: ...
443
```
444
445
[Middleware](./middleware.md)
446
447
### Background Tasks
448
449
Background task execution system for running tasks after sending the response to the client.
450
451
```python { .api }
452
class BackgroundTasks:
453
def add_task(
454
self,
455
func: Callable,
456
*args: Any,
457
**kwargs: Any,
458
) -> None: ...
459
```
460
461
[Background Tasks](./background-tasks.md)
462
463
### Static Files and Templating
464
465
Static file serving and HTML template rendering capabilities for web applications that need to serve frontend content alongside API endpoints.
466
467
```python { .api }
468
class StaticFiles:
469
def __init__(
470
self,
471
*,
472
directory: str = None,
473
packages: List[str] = None,
474
html: bool = False,
475
check_dir: bool = True,
476
follow_symlink: bool = False,
477
) -> None: ...
478
479
class Jinja2Templates:
480
def __init__(self, directory: str) -> None: ...
481
def TemplateResponse(
482
self,
483
name: str,
484
context: dict,
485
status_code: int = 200,
486
headers: dict = None,
487
media_type: str = None,
488
background: BackgroundTask = None,
489
) -> TemplateResponse: ...
490
```
491
492
[Static Files and Templating](./static-templating.md)
493
494
### Testing Support
495
496
Test client for testing FastAPI applications with comprehensive HTTP request simulation capabilities.
497
498
```python { .api }
499
class TestClient:
500
def __init__(
501
self,
502
app: ASGIApp,
503
base_url: str = "http://testserver",
504
raise_server_exceptions: bool = True,
505
root_path: str = "",
506
backend: str = "asyncio",
507
backend_options: dict = None,
508
cookies: httpx.Cookies = None,
509
headers: dict = None,
510
follow_redirects: bool = False,
511
) -> None: ...
512
513
def get(self, url: str, **kwargs) -> httpx.Response: ...
514
def post(self, url: str, **kwargs) -> httpx.Response: ...
515
def put(self, url: str, **kwargs) -> httpx.Response: ...
516
def delete(self, url: str, **kwargs) -> httpx.Response: ...
517
def patch(self, url: str, **kwargs) -> httpx.Response: ...
518
def head(self, url: str, **kwargs) -> httpx.Response: ...
519
def options(self, url: str, **kwargs) -> httpx.Response: ...
520
```
521
522
[Testing Support](./testing.md)
523
524
### Data Utilities
525
526
Utility functions for data encoding and serialization, particularly for converting Python objects to JSON-compatible formats.
527
528
```python { .api }
529
def jsonable_encoder(
530
obj: Any,
531
include: Union[Set[int], Set[str], Dict[int, Any], Dict[str, Any]] = None,
532
exclude: Union[Set[int], Set[str], Dict[int, Any], Dict[str, Any]] = None,
533
by_alias: bool = True,
534
exclude_unset: bool = False,
535
exclude_defaults: bool = False,
536
exclude_none: bool = False,
537
round_trip: bool = True,
538
timedelta_isoformat: str = "iso8601",
539
sqlalchemy_safe: bool = True,
540
fallback: Callable[[Any], Any] = None,
541
) -> Any: ...
542
```
543
544
[Data Utilities](./data-utilities.md)
545
546
### Advanced Response Types
547
548
High-performance JSON response classes and additional response types for various content delivery needs.
549
550
```python { .api }
551
class UJSONResponse(Response):
552
def __init__(
553
self,
554
content: Any = None,
555
status_code: int = 200,
556
headers: dict = None,
557
media_type: str = "application/json",
558
background: BackgroundTask = None,
559
) -> None: ...
560
561
class ORJSONResponse(Response):
562
def __init__(
563
self,
564
content: Any = None,
565
status_code: int = 200,
566
headers: dict = None,
567
media_type: str = "application/json",
568
background: BackgroundTask = None,
569
) -> None: ...
570
571
class HTMLResponse(Response):
572
def __init__(
573
self,
574
content: str = "",
575
status_code: int = 200,
576
headers: dict = None,
577
media_type: str = "text/html",
578
background: BackgroundTask = None,
579
) -> None: ...
580
581
class RedirectResponse(Response):
582
def __init__(
583
self,
584
url: str,
585
status_code: int = 307,
586
headers: dict = None,
587
background: BackgroundTask = None,
588
) -> None: ...
589
590
class FileResponse(Response):
591
def __init__(
592
self,
593
path: str,
594
status_code: int = 200,
595
headers: dict = None,
596
media_type: str = None,
597
filename: str = None,
598
background: BackgroundTask = None,
599
) -> None: ...
600
601
class StreamingResponse(Response):
602
def __init__(
603
self,
604
content: Iterator[Any],
605
status_code: int = 200,
606
headers: dict = None,
607
media_type: str = None,
608
background: BackgroundTask = None,
609
) -> None: ...
610
```
611
612
[Advanced Response Types](./advanced-responses.md)
613
614
## Types
615
616
```python { .api }
617
# Core type definitions used across FastAPI
618
619
from typing import Any, Callable, Dict, List, Optional, Union, Set, Iterator
620
from starlette.types import ASGIApp, Receive, Scope, Send
621
from starlette.responses import Response
622
from starlette.routing import BaseRoute
623
from starlette.middleware import Middleware
624
from starlette.background import BackgroundTask
625
from starlette.templating import _TemplateResponse as TemplateResponse
626
from starlette.datastructures import URL, Address, FormData, Headers, QueryParams, State
627
from pydantic import BaseModel
628
import httpx
629
630
# FastAPI specific types
631
DecoratedCallable = Callable[..., Any]
632
DependsCallable = Callable[..., Any]
633
IncEx = Union[Set[int], Set[str], Dict[int, Any], Dict[str, Any], None]
634
Lifespan = Callable[[Any], Any]
635
636
# Version information
637
__version__: str # Current FastAPI version
638
```