FastAPI framework, high performance, easy to learn, fast to code, ready for production - slim version without standard dependencies
npx @tessl/cli install tessl/pypi-fastapi-slim@0.116.0A high-performance, modern web framework for building APIs with Python based on standard Python type hints. FastAPI-slim is the minimal version of FastAPI that excludes standard optional dependencies (uvicorn, jinja2, python-multipart, email-validator, httpx) while maintaining full compatibility with the FastAPI ecosystem.
pip install fastapi-slimpip install fastapi-slim[standard] (includes uvicorn, jinja2, etc.)from fastapi import FastAPICommon imports for building APIs:
from fastapi import FastAPI, APIRouter
from fastapi import Depends, Path, Query, Body, Header, Cookie, Form, File
from fastapi import HTTPException, Request, Response
from fastapi import BackgroundTasks, UploadFileWebSocket support:
from fastapi import WebSocket, WebSocketDisconnectfrom fastapi import FastAPI, Query
from pydantic import BaseModel
# Create FastAPI app
app = FastAPI(title="My API", version="1.0.0")
# Simple route with path parameter
@app.get("/items/{item_id}")
async def get_item(item_id: int, q: str = Query(None, description="Query parameter")):
return {"item_id": item_id, "q": q}
# POST endpoint with request body
class Item(BaseModel):
name: str
price: float
is_offer: bool = False
@app.post("/items/")
async def create_item(item: Item):
return {"item": item}
# Background tasks
from fastapi import BackgroundTasks
def write_notification(email: str, message: str):
# Send notification logic here
pass
@app.post("/send-notification/")
async def send_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_notification, email, "some notification")
return {"message": "Notification sent in the background"}
# Run with: uvicorn main:app --reloadFastAPI-slim provides a layered architecture built on Starlette:
Main FastAPI application class providing the primary interface for creating web APIs with automatic OpenAPI documentation, request validation, and dependency injection.
class FastAPI:
def __init__(
self,
*,
debug: bool = False,
routes: Optional[List[BaseRoute]] = None,
title: str = "FastAPI",
summary: Optional[str] = None,
description: str = "",
version: str = "0.1.0",
openapi_url: Optional[str] = "/openapi.json",
openapi_tags: Optional[List[Dict[str, Any]]] = None,
servers: Optional[List[Dict[str, Union[str, Any]]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
default_response_class: Type[Response] = Default(JSONResponse),
redirect_slashes: bool = True,
docs_url: Optional[str] = "/docs",
redoc_url: Optional[str] = "/redoc",
swagger_ui_oauth2_redirect_url: Optional[str] = "/docs/oauth2-redirect",
swagger_ui_init_oauth: Optional[Dict[str, Any]] = None,
middleware: Optional[Sequence[Middleware]] = None,
exception_handlers: Optional[Dict[Union[int, Type[Exception]], Callable[[Request, Any], Coroutine[Any, Any, Response]]]] = None,
on_startup: Optional[Sequence[Callable[[], Any]]] = None,
on_shutdown: Optional[Sequence[Callable[[], Any]]] = None,
lifespan: Optional[Lifespan[AppType]] = None,
terms_of_service: Optional[str] = None,
contact: Optional[Dict[str, Union[str, Any]]] = None,
license_info: Optional[Dict[str, Union[str, Any]]] = None,
openapi_prefix: str = "",
root_path: str = "",
root_path_in_servers: bool = True,
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
callbacks: Optional[List[BaseRoute]] = None,
webhooks: Optional[APIRouter] = None,
deprecated: Optional[bool] = None,
include_in_schema: bool = True,
swagger_ui_parameters: Optional[Dict[str, Any]] = None,
generate_unique_id_function: Callable[[APIRoute], str] = Default(generate_unique_id),
separate_input_output_schemas: bool = True,
**extra: Any
): ...
def get(self, path: str, **kwargs): ... # HTTP method decorators
def post(self, path: str, **kwargs): ...
def put(self, path: str, **kwargs): ...
def delete(self, path: str, **kwargs): ...
def patch(self, path: str, **kwargs): ...
def options(self, path: str, **kwargs): ...
def head(self, path: str, **kwargs): ...
def trace(self, path: str, **kwargs): ...
def websocket(self, path: str, **kwargs): ...
def include_router(
self,
router: "APIRouter",
*,
prefix: str = "",
tags: list = None,
dependencies: list = None,
responses: dict = None,
deprecated: bool = None,
include_in_schema: bool = True,
default_response_class: type = None,
callbacks: list = None
): ...Router system for organizing endpoints into logical groups with hierarchical inclusion, prefix support, and shared dependencies or tags.
class APIRouter:
def __init__(
self,
*,
prefix: str = "",
tags: list = None,
dependencies: list = None,
default_response_class: type = None,
responses: dict = None,
callbacks: list = None,
routes: list = None,
redirect_slashes: bool = True,
default: callable = None,
dependency_overrides_provider: any = None,
route_class: type = None,
on_startup: list = None,
on_shutdown: list = None,
lifespan: callable = None,
deprecated: bool = None,
include_in_schema: bool = True,
generate_unique_id_function: callable = None
): ...
def get(self, path: str, **kwargs): ... # HTTP method decorators
def post(self, path: str, **kwargs): ...
# ... other HTTP methods
def include_router(self, router: "APIRouter", **kwargs): ...Functions for declaring and validating different types of request parameters with rich validation constraints and automatic OpenAPI schema generation.
def Path(
default: any = ...,
*,
alias: str = None,
title: str = None,
description: str = None,
gt: float = None,
ge: float = None,
lt: float = None,
le: float = None,
min_length: int = None,
max_length: int = None,
regex: str = None,
example: any = None,
examples: dict = None,
deprecated: bool = None,
include_in_schema: bool = True,
json_schema_extra: dict = None,
**extra: any
): ...
def Query(default: any = ..., **kwargs): ... # Same signature as Path
def Header(default: any = ..., convert_underscores: bool = True, **kwargs): ...
def Cookie(default: any = ..., **kwargs): ...
def Body(default: any = ..., embed: bool = False, media_type: str = "application/json", **kwargs): ...
def Form(default: any = ..., media_type: str = "application/x-www-form-urlencoded", **kwargs): ...
def File(default: any = ..., media_type: str = "multipart/form-data", **kwargs): ...System for declaring and resolving dependencies with automatic caching, hierarchical resolution, and security integration.
def Depends(dependency: callable = None, *, use_cache: bool = True): ...
def Security(
dependency: callable = None,
*,
scopes: list = None,
use_cache: bool = True
): ...Objects for accessing request data and creating custom responses with full control over headers, status codes, and content types.
class Request:
"""HTTP request object (from Starlette)"""
url: URL
method: str
headers: Headers
query_params: QueryParams
path_params: dict
cookies: dict
client: Address
session: dict
state: State
async def json(self): ...
async def form(self): ...
async def body(self): ...
def stream(self): ...
class Response:
"""HTTP response object (from Starlette)"""
def __init__(
self,
content: any = None,
status_code: int = 200,
headers: dict = None,
media_type: str = None,
background: BackgroundTask = None
): ...Exception classes for HTTP errors and WebSocket errors with automatic response generation and proper status codes.
class HTTPException(Exception):
def __init__(
self,
status_code: int,
detail: any = None,
headers: dict = None
): ...
class WebSocketException(Exception):
def __init__(self, code: int, reason: str = None): ...WebSocket connection handling with message sending/receiving, connection lifecycle management, and error handling.
class WebSocket:
"""WebSocket connection object (from Starlette)"""
url: URL
headers: Headers
query_params: QueryParams
path_params: dict
cookies: dict
client: Address
state: State
async def accept(self, subprotocol: str = None, headers: dict = None): ...
async def close(self, code: int = 1000, reason: str = None): ...
async def send_text(self, data: str): ...
async def send_bytes(self, data: bytes): ...
async def send_json(self, data: any): ...
async def receive_text(self) -> str: ...
async def receive_bytes(self) -> bytes: ...
async def receive_json(self, mode: str = "text") -> any: ...
class WebSocketDisconnect(Exception):
def __init__(self, code: int = 1000, reason: str = None): ...System for executing tasks after response is sent, useful for operations like sending emails, logging, or cleanup tasks.
class BackgroundTasks:
def add_task(self, func: callable, *args, **kwargs): ...File upload handling with async methods for reading, writing, and managing uploaded files with proper content type detection.
class UploadFile:
file: BinaryIO
filename: str
size: int
headers: Headers
content_type: str
async def read(self, size: int = -1) -> bytes: ...
async def write(self, data: bytes): ...
async def seek(self, offset: int): ...
async def close(self): ...# Common type aliases used throughout FastAPI
from typing import Any, Callable, Dict, List, Optional, Union, Sequence
from starlette.types import ASGIApp, Receive, Scope, Send
# Key types for dependency injection
DependsCallable = Callable[..., Any]
SecurityCallable = Callable[..., Any]
# HTTP method types
HTTPMethods = Union[str, List[str]]
# Parameter validation types
ValidatorFunction = Callable[[Any], Any]