- Spec files
pypi-fastapi
Describes: pkg:pypi/fastapi@0.116.x
- Description
- FastAPI framework, high performance, easy to learn, fast to code, ready for production
- Author
- tessl
- Last updated
index.md docs/
1# FastAPI23FastAPI 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.45## Package Information67- **Package Name**: fastapi8- **Language**: Python9- **Installation**: `pip install fastapi`10- **Requirements**: Python 3.8+11- **Main Dependencies**: Starlette, Pydantic1213## Core Imports1415```python16from fastapi import FastAPI17```1819Common imports for building APIs:2021```python22from fastapi import FastAPI, APIRouter, Depends, HTTPException23from fastapi import Query, Path, Body, Header, Cookie, Form, File24from fastapi import Request, Response, BackgroundTasks25from fastapi import WebSocket, WebSocketDisconnect26from fastapi import UploadFile, __version__, status27from fastapi.security import HTTPBearer, OAuth2PasswordBearer, APIKeyHeader28from fastapi.middleware.cors import CORSMiddleware29from fastapi.responses import JSONResponse, HTMLResponse, RedirectResponse30from fastapi.staticfiles import StaticFiles31from fastapi.templating import Jinja2Templates32from fastapi.testclient import TestClient33from fastapi.encoders import jsonable_encoder34```3536## Basic Usage3738```python39from fastapi import FastAPI, Query40from typing import Optional4142# Create FastAPI application43app = FastAPI(44title="My API",45description="A simple API example",46version="1.0.0"47)4849# Simple GET endpoint50@app.get("/")51def read_root():52return {"Hello": "World"}5354# GET endpoint with path parameter55@app.get("/items/{item_id}")56def read_item(item_id: int, q: Optional[str] = Query(None)):57return {"item_id": item_id, "q": q}5859# POST endpoint with request body60from pydantic import BaseModel6162class Item(BaseModel):63name: str64price: float65is_offer: Optional[bool] = None6667@app.post("/items/")68def create_item(item: Item):69return item7071# Run the application (for development)72if __name__ == "__main__":73import uvicorn74uvicorn.run(app, host="0.0.0.0", port=8000)75```7677## Architecture7879FastAPI builds on the Starlette ASGI framework and uses Pydantic for data validation:8081- **FastAPI Application**: Main application class that manages routes, middleware, and configuration82- **APIRouter**: Router for organizing and grouping related endpoints83- **Parameter Functions**: Type-safe parameter declaration (Query, Path, Body, etc.)84- **Pydantic Integration**: Automatic request/response validation and serialization85- **Starlette Foundation**: High-performance ASGI framework providing core web functionality86- **Automatic Documentation**: OpenAPI schema generation with interactive Swagger UI and ReDoc8788This architecture enables rapid development of production-ready APIs with automatic validation, serialization, and documentation generation while maintaining high performance and type safety.8990## Capabilities9192### Core Application9394Main FastAPI application class and basic routing functionality. The FastAPI class serves as the central application instance that manages all routes, middleware, dependencies, and configuration.9596```python { .api }97class FastAPI:98def __init__(99self,100*,101debug: bool = False,102routes: List[BaseRoute] = None,103title: str = "FastAPI",104description: str = "",105version: str = "0.1.0",106openapi_url: str = "/openapi.json",107openapi_tags: List[dict] = None,108servers: List[dict] = None,109dependencies: List[Depends] = None,110default_response_class: Type[Response] = Default(JSONResponse),111docs_url: str = "/docs",112redoc_url: str = "/redoc",113swagger_ui_oauth2_redirect_url: str = "/docs/oauth2-redirect",114swagger_ui_init_oauth: dict = None,115middleware: List[Middleware] = None,116exception_handlers: dict = None,117on_startup: List[Callable] = None,118on_shutdown: List[Callable] = None,119lifespan: Lifespan = None,120**extra: Any,121) -> None: ...122123def get(self, path: str, **kwargs) -> Callable: ...124def post(self, path: str, **kwargs) -> Callable: ...125def put(self, path: str, **kwargs) -> Callable: ...126def delete(self, path: str, **kwargs) -> Callable: ...127def patch(self, path: str, **kwargs) -> Callable: ...128def head(self, path: str, **kwargs) -> Callable: ...129def options(self, path: str, **kwargs) -> Callable: ...130def trace(self, path: str, **kwargs) -> Callable: ...131def websocket(self, path: str, **kwargs) -> Callable: ...132133def include_router(self, router: APIRouter, **kwargs) -> None: ...134def add_api_route(self, path: str, endpoint: Callable, **kwargs) -> None: ...135def add_api_websocket_route(self, path: str, endpoint: Callable, **kwargs) -> None: ...136def middleware(self, middleware_type: str) -> Callable: ...137def exception_handler(self, exc_class_or_status_code: Union[int, Exception]) -> Callable: ...138```139140[Core Application](./core-application.md)141142### API Routing143144Router for organizing and grouping related API endpoints with shared configuration, middleware, and dependencies.145146```python { .api }147class APIRouter:148def __init__(149self,150*,151prefix: str = "",152tags: List[str] = None,153dependencies: List[Depends] = None,154default_response_class: Type[Response] = Default(JSONResponse),155responses: dict = None,156callbacks: List[BaseRoute] = None,157routes: List[BaseRoute] = None,158redirect_slashes: bool = True,159default: ASGIApp = None,160dependency_overrides_provider: Any = None,161route_class: Type[APIRoute] = APIRoute,162on_startup: List[Callable] = None,163on_shutdown: List[Callable] = None,164lifespan: Lifespan = None,165deprecated: bool = None,166include_in_schema: bool = True,167**kwargs: Any,168) -> None: ...169170def get(self, path: str, **kwargs) -> Callable: ...171def post(self, path: str, **kwargs) -> Callable: ...172def put(self, path: str, **kwargs) -> Callable: ...173def delete(self, path: str, **kwargs) -> Callable: ...174def patch(self, path: str, **kwargs) -> Callable: ...175def head(self, path: str, **kwargs) -> Callable: ...176def options(self, path: str, **kwargs) -> Callable: ...177def trace(self, path: str, **kwargs) -> Callable: ...178def websocket(self, path: str, **kwargs) -> Callable: ...179180def include_router(self, router: APIRouter, **kwargs) -> None: ...181def add_api_route(self, path: str, endpoint: Callable, **kwargs) -> None: ...182```183184[API Routing](./api-routing.md)185186### Request Parameters187188Type-safe parameter declaration functions for handling path parameters, query parameters, headers, cookies, request bodies, form data, and file uploads.189190```python { .api }191def Path(192default: Any = ...,193*,194alias: str = None,195title: str = None,196description: str = None,197gt: float = None,198ge: float = None,199lt: float = None,200le: float = None,201min_length: int = None,202max_length: int = None,203regex: str = None,204example: Any = None,205examples: dict = None,206deprecated: bool = None,207include_in_schema: bool = True,208**extra: Any,209) -> Any: ...210211def Query(212default: Any = Undefined,213*,214alias: str = None,215title: str = None,216description: str = None,217gt: float = None,218ge: float = None,219lt: float = None,220le: float = None,221min_length: int = None,222max_length: int = None,223regex: str = None,224example: Any = None,225examples: dict = None,226deprecated: bool = None,227include_in_schema: bool = True,228**extra: Any,229) -> Any: ...230231def Body(232default: Any = Undefined,233*,234embed: bool = None,235media_type: str = "application/json",236alias: str = None,237title: str = None,238description: str = None,239example: Any = None,240examples: dict = None,241deprecated: bool = None,242include_in_schema: bool = True,243**extra: Any,244) -> Any: ...245246def Form(247default: Any = Undefined,248*,249media_type: str = "application/x-www-form-urlencoded",250alias: str = None,251title: str = None,252description: str = None,253example: Any = None,254examples: dict = None,255deprecated: bool = None,256include_in_schema: bool = True,257**extra: Any,258) -> Any: ...259260def File(261default: Any = Undefined,262*,263media_type: str = "multipart/form-data",264alias: str = None,265title: str = None,266description: str = None,267example: Any = None,268examples: dict = None,269deprecated: bool = None,270include_in_schema: bool = True,271**extra: Any,272) -> Any: ...273```274275[Request Parameters](./request-parameters.md)276277### Dependency Injection278279Powerful dependency injection system for sharing code, database connections, authentication, and other common functionality across endpoints.280281```python { .api }282def Depends(dependency: Callable = None, *, use_cache: bool = True) -> Any: ...283284def Security(285dependency: Callable = None,286*,287scopes: List[str] = None,288use_cache: bool = True,289) -> Any: ...290```291292[Dependency Injection](./dependency-injection.md)293294### Request and Response Handling295296Request and response objects for accessing HTTP data and customizing response behavior.297298```python { .api }299class Request:300# Starlette Request object with all HTTP request functionality301pass302303class Response:304def __init__(305self,306content: Any = None,307status_code: int = 200,308headers: dict = None,309media_type: str = None,310background: BackgroundTask = None,311) -> None: ...312313class JSONResponse(Response):314def __init__(315self,316content: Any = None,317status_code: int = 200,318headers: dict = None,319media_type: str = "application/json",320background: BackgroundTask = None,321) -> None: ...322323class UploadFile:324filename: str325content_type: str326file: BinaryIO327328async def read(self, size: int = -1) -> bytes: ...329async def readline(self, size: int = -1) -> bytes: ...330async def readlines(self) -> List[bytes]: ...331async def write(self, data: bytes) -> None: ...332async def seek(self, offset: int) -> None: ...333async def close(self) -> None: ...334```335336[Request and Response](./request-response.md)337338### WebSocket Support339340WebSocket support for real-time bidirectional communication between client and server.341342```python { .api }343class WebSocket:344# Starlette WebSocket object with full WebSocket functionality345async def accept(self, subprotocol: str = None, headers: dict = None) -> None: ...346async def receive_text(self) -> str: ...347async def receive_bytes(self) -> bytes: ...348async def receive_json(self) -> Any: ...349async def send_text(self, data: str) -> None: ...350async def send_bytes(self, data: bytes) -> None: ...351async def send_json(self, data: Any) -> None: ...352async def close(self, code: int = 1000, reason: str = None) -> None: ...353354class WebSocketDisconnect(Exception):355def __init__(self, code: int = 1000, reason: str = None) -> None: ...356```357358[WebSocket Support](./websocket-support.md)359360### Security and Authentication361362Comprehensive security components for API key authentication, HTTP authentication (Basic, Bearer, Digest), and OAuth2 flows.363364```python { .api }365class HTTPBearer:366def __init__(367self,368*,369bearerFormat: str = None,370scheme_name: str = None,371description: str = None,372auto_error: bool = True,373) -> None: ...374375class OAuth2PasswordBearer:376def __init__(377self,378tokenUrl: str,379*,380scheme_name: str = None,381scopes: dict = None,382description: str = None,383auto_error: bool = True,384) -> None: ...385386class APIKeyHeader:387def __init__(388self,389*,390name: str,391scheme_name: str = None,392description: str = None,393auto_error: bool = True,394) -> None: ...395```396397[Security and Authentication](./security-authentication.md)398399### Exception Handling400401Exception classes for handling HTTP errors and WebSocket errors with proper status codes and error details.402403```python { .api }404class HTTPException(Exception):405def __init__(406self,407status_code: int,408detail: Any = None,409headers: dict = None,410) -> None: ...411412status_code: int413detail: Any414headers: dict415416class WebSocketException(Exception):417def __init__(self, code: int, reason: str = None) -> None: ...418419code: int420reason: str421```422423[Exception Handling](./exception-handling.md)424425### Middleware426427Middleware components for cross-cutting concerns like CORS, compression, security headers, and custom request/response processing.428429```python { .api }430class CORSMiddleware:431def __init__(432self,433app: ASGIApp,434*,435allow_origins: List[str] = None,436allow_methods: List[str] = None,437allow_headers: List[str] = None,438allow_credentials: bool = False,439allow_origin_regex: str = None,440expose_headers: List[str] = None,441max_age: int = 600,442) -> None: ...443```444445[Middleware](./middleware.md)446447### Background Tasks448449Background task execution system for running tasks after sending the response to the client.450451```python { .api }452class BackgroundTasks:453def add_task(454self,455func: Callable,456*args: Any,457**kwargs: Any,458) -> None: ...459```460461[Background Tasks](./background-tasks.md)462463### Static Files and Templating464465Static file serving and HTML template rendering capabilities for web applications that need to serve frontend content alongside API endpoints.466467```python { .api }468class StaticFiles:469def __init__(470self,471*,472directory: str = None,473packages: List[str] = None,474html: bool = False,475check_dir: bool = True,476follow_symlink: bool = False,477) -> None: ...478479class Jinja2Templates:480def __init__(self, directory: str) -> None: ...481def TemplateResponse(482self,483name: str,484context: dict,485status_code: int = 200,486headers: dict = None,487media_type: str = None,488background: BackgroundTask = None,489) -> TemplateResponse: ...490```491492[Static Files and Templating](./static-templating.md)493494### Testing Support495496Test client for testing FastAPI applications with comprehensive HTTP request simulation capabilities.497498```python { .api }499class TestClient:500def __init__(501self,502app: ASGIApp,503base_url: str = "http://testserver",504raise_server_exceptions: bool = True,505root_path: str = "",506backend: str = "asyncio",507backend_options: dict = None,508cookies: httpx.Cookies = None,509headers: dict = None,510follow_redirects: bool = False,511) -> None: ...512513def get(self, url: str, **kwargs) -> httpx.Response: ...514def post(self, url: str, **kwargs) -> httpx.Response: ...515def put(self, url: str, **kwargs) -> httpx.Response: ...516def delete(self, url: str, **kwargs) -> httpx.Response: ...517def patch(self, url: str, **kwargs) -> httpx.Response: ...518def head(self, url: str, **kwargs) -> httpx.Response: ...519def options(self, url: str, **kwargs) -> httpx.Response: ...520```521522[Testing Support](./testing.md)523524### Data Utilities525526Utility functions for data encoding and serialization, particularly for converting Python objects to JSON-compatible formats.527528```python { .api }529def jsonable_encoder(530obj: Any,531include: Union[Set[int], Set[str], Dict[int, Any], Dict[str, Any]] = None,532exclude: Union[Set[int], Set[str], Dict[int, Any], Dict[str, Any]] = None,533by_alias: bool = True,534exclude_unset: bool = False,535exclude_defaults: bool = False,536exclude_none: bool = False,537round_trip: bool = True,538timedelta_isoformat: str = "iso8601",539sqlalchemy_safe: bool = True,540fallback: Callable[[Any], Any] = None,541) -> Any: ...542```543544[Data Utilities](./data-utilities.md)545546### Advanced Response Types547548High-performance JSON response classes and additional response types for various content delivery needs.549550```python { .api }551class UJSONResponse(Response):552def __init__(553self,554content: Any = None,555status_code: int = 200,556headers: dict = None,557media_type: str = "application/json",558background: BackgroundTask = None,559) -> None: ...560561class ORJSONResponse(Response):562def __init__(563self,564content: Any = None,565status_code: int = 200,566headers: dict = None,567media_type: str = "application/json",568background: BackgroundTask = None,569) -> None: ...570571class HTMLResponse(Response):572def __init__(573self,574content: str = "",575status_code: int = 200,576headers: dict = None,577media_type: str = "text/html",578background: BackgroundTask = None,579) -> None: ...580581class RedirectResponse(Response):582def __init__(583self,584url: str,585status_code: int = 307,586headers: dict = None,587background: BackgroundTask = None,588) -> None: ...589590class FileResponse(Response):591def __init__(592self,593path: str,594status_code: int = 200,595headers: dict = None,596media_type: str = None,597filename: str = None,598background: BackgroundTask = None,599) -> None: ...600601class StreamingResponse(Response):602def __init__(603self,604content: Iterator[Any],605status_code: int = 200,606headers: dict = None,607media_type: str = None,608background: BackgroundTask = None,609) -> None: ...610```611612[Advanced Response Types](./advanced-responses.md)613614## Types615616```python { .api }617# Core type definitions used across FastAPI618619from typing import Any, Callable, Dict, List, Optional, Union, Set, Iterator620from starlette.types import ASGIApp, Receive, Scope, Send621from starlette.responses import Response622from starlette.routing import BaseRoute623from starlette.middleware import Middleware624from starlette.background import BackgroundTask625from starlette.templating import _TemplateResponse as TemplateResponse626from starlette.datastructures import URL, Address, FormData, Headers, QueryParams, State627from pydantic import BaseModel628import httpx629630# FastAPI specific types631DecoratedCallable = Callable[..., Any]632DependsCallable = Callable[..., Any]633IncEx = Union[Set[int], Set[str], Dict[int, Any], Dict[str, Any], None]634Lifespan = Callable[[Any], Any]635636# Version information637__version__: str # Current FastAPI version638```