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.00
# FastAPI-Slim
1
2
A 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.
3
4
## Package Information
5
6
- **Package Name**: fastapi-slim
7
- **Language**: Python
8
- **Installation**: `pip install fastapi-slim`
9
- **Standard dependencies**: `pip install fastapi-slim[standard]` (includes uvicorn, jinja2, etc.)
10
11
## Core Imports
12
13
```python
14
from fastapi import FastAPI
15
```
16
17
Common imports for building APIs:
18
19
```python
20
from fastapi import FastAPI, APIRouter
21
from fastapi import Depends, Path, Query, Body, Header, Cookie, Form, File
22
from fastapi import HTTPException, Request, Response
23
from fastapi import BackgroundTasks, UploadFile
24
```
25
26
WebSocket support:
27
28
```python
29
from fastapi import WebSocket, WebSocketDisconnect
30
```
31
32
## Basic Usage
33
34
```python
35
from fastapi import FastAPI, Query
36
from pydantic import BaseModel
37
38
# Create FastAPI app
39
app = FastAPI(title="My API", version="1.0.0")
40
41
# Simple route with path parameter
42
@app.get("/items/{item_id}")
43
async def get_item(item_id: int, q: str = Query(None, description="Query parameter")):
44
return {"item_id": item_id, "q": q}
45
46
# POST endpoint with request body
47
class Item(BaseModel):
48
name: str
49
price: float
50
is_offer: bool = False
51
52
@app.post("/items/")
53
async def create_item(item: Item):
54
return {"item": item}
55
56
# Background tasks
57
from fastapi import BackgroundTasks
58
59
def write_notification(email: str, message: str):
60
# Send notification logic here
61
pass
62
63
@app.post("/send-notification/")
64
async def send_notification(email: str, background_tasks: BackgroundTasks):
65
background_tasks.add_task(write_notification, email, "some notification")
66
return {"message": "Notification sent in the background"}
67
68
# Run with: uvicorn main:app --reload
69
```
70
71
## Architecture
72
73
FastAPI-slim provides a layered architecture built on Starlette:
74
75
- **FastAPI Application**: Main application class with automatic OpenAPI generation, dependency injection, and validation
76
- **APIRouter**: Modular routing system for organizing endpoints into logical groups
77
- **Parameter System**: Unified parameter declaration (Path, Query, Body, etc.) with automatic validation
78
- **Dependency Injection**: Hierarchical dependency resolution with automatic caching
79
- **Pydantic Integration**: Automatic request/response validation and serialization
80
- **Starlette Foundation**: High-performance ASGI framework providing core web functionality
81
82
## Capabilities
83
84
### Core Application
85
86
Main FastAPI application class providing the primary interface for creating web APIs with automatic OpenAPI documentation, request validation, and dependency injection.
87
88
```python { .api }
89
class FastAPI:
90
def __init__(
91
self,
92
*,
93
debug: bool = False,
94
routes: Optional[List[BaseRoute]] = None,
95
title: str = "FastAPI",
96
summary: Optional[str] = None,
97
description: str = "",
98
version: str = "0.1.0",
99
openapi_url: Optional[str] = "/openapi.json",
100
openapi_tags: Optional[List[Dict[str, Any]]] = None,
101
servers: Optional[List[Dict[str, Union[str, Any]]]] = None,
102
dependencies: Optional[Sequence[Depends]] = None,
103
default_response_class: Type[Response] = Default(JSONResponse),
104
redirect_slashes: bool = True,
105
docs_url: Optional[str] = "/docs",
106
redoc_url: Optional[str] = "/redoc",
107
swagger_ui_oauth2_redirect_url: Optional[str] = "/docs/oauth2-redirect",
108
swagger_ui_init_oauth: Optional[Dict[str, Any]] = None,
109
middleware: Optional[Sequence[Middleware]] = None,
110
exception_handlers: Optional[Dict[Union[int, Type[Exception]], Callable[[Request, Any], Coroutine[Any, Any, Response]]]] = None,
111
on_startup: Optional[Sequence[Callable[[], Any]]] = None,
112
on_shutdown: Optional[Sequence[Callable[[], Any]]] = None,
113
lifespan: Optional[Lifespan[AppType]] = None,
114
terms_of_service: Optional[str] = None,
115
contact: Optional[Dict[str, Union[str, Any]]] = None,
116
license_info: Optional[Dict[str, Union[str, Any]]] = None,
117
openapi_prefix: str = "",
118
root_path: str = "",
119
root_path_in_servers: bool = True,
120
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
121
callbacks: Optional[List[BaseRoute]] = None,
122
webhooks: Optional[APIRouter] = None,
123
deprecated: Optional[bool] = None,
124
include_in_schema: bool = True,
125
swagger_ui_parameters: Optional[Dict[str, Any]] = None,
126
generate_unique_id_function: Callable[[APIRoute], str] = Default(generate_unique_id),
127
separate_input_output_schemas: bool = True,
128
**extra: Any
129
): ...
130
131
def get(self, path: str, **kwargs): ... # HTTP method decorators
132
def post(self, path: str, **kwargs): ...
133
def put(self, path: str, **kwargs): ...
134
def delete(self, path: str, **kwargs): ...
135
def patch(self, path: str, **kwargs): ...
136
def options(self, path: str, **kwargs): ...
137
def head(self, path: str, **kwargs): ...
138
def trace(self, path: str, **kwargs): ...
139
def websocket(self, path: str, **kwargs): ...
140
141
def include_router(
142
self,
143
router: "APIRouter",
144
*,
145
prefix: str = "",
146
tags: list = None,
147
dependencies: list = None,
148
responses: dict = None,
149
deprecated: bool = None,
150
include_in_schema: bool = True,
151
default_response_class: type = None,
152
callbacks: list = None
153
): ...
154
```
155
156
[Core Application](./core-application.md)
157
158
### API Routing
159
160
Router system for organizing endpoints into logical groups with hierarchical inclusion, prefix support, and shared dependencies or tags.
161
162
```python { .api }
163
class APIRouter:
164
def __init__(
165
self,
166
*,
167
prefix: str = "",
168
tags: list = None,
169
dependencies: list = None,
170
default_response_class: type = None,
171
responses: dict = None,
172
callbacks: list = None,
173
routes: list = None,
174
redirect_slashes: bool = True,
175
default: callable = None,
176
dependency_overrides_provider: any = None,
177
route_class: type = None,
178
on_startup: list = None,
179
on_shutdown: list = None,
180
lifespan: callable = None,
181
deprecated: bool = None,
182
include_in_schema: bool = True,
183
generate_unique_id_function: callable = None
184
): ...
185
186
def get(self, path: str, **kwargs): ... # HTTP method decorators
187
def post(self, path: str, **kwargs): ...
188
# ... other HTTP methods
189
190
def include_router(self, router: "APIRouter", **kwargs): ...
191
```
192
193
[API Routing](./api-routing.md)
194
195
### Parameter Declaration
196
197
Functions for declaring and validating different types of request parameters with rich validation constraints and automatic OpenAPI schema generation.
198
199
```python { .api }
200
def Path(
201
default: any = ...,
202
*,
203
alias: str = None,
204
title: str = None,
205
description: str = None,
206
gt: float = None,
207
ge: float = None,
208
lt: float = None,
209
le: float = None,
210
min_length: int = None,
211
max_length: int = None,
212
regex: str = None,
213
example: any = None,
214
examples: dict = None,
215
deprecated: bool = None,
216
include_in_schema: bool = True,
217
json_schema_extra: dict = None,
218
**extra: any
219
): ...
220
221
def Query(default: any = ..., **kwargs): ... # Same signature as Path
222
def Header(default: any = ..., convert_underscores: bool = True, **kwargs): ...
223
def Cookie(default: any = ..., **kwargs): ...
224
def Body(default: any = ..., embed: bool = False, media_type: str = "application/json", **kwargs): ...
225
def Form(default: any = ..., media_type: str = "application/x-www-form-urlencoded", **kwargs): ...
226
def File(default: any = ..., media_type: str = "multipart/form-data", **kwargs): ...
227
```
228
229
[Parameter Declaration](./parameter-declaration.md)
230
231
### Dependency Injection
232
233
System for declaring and resolving dependencies with automatic caching, hierarchical resolution, and security integration.
234
235
```python { .api }
236
def Depends(dependency: callable = None, *, use_cache: bool = True): ...
237
238
def Security(
239
dependency: callable = None,
240
*,
241
scopes: list = None,
242
use_cache: bool = True
243
): ...
244
```
245
246
[Dependency Injection](./dependency-injection.md)
247
248
### Request and Response Handling
249
250
Objects for accessing request data and creating custom responses with full control over headers, status codes, and content types.
251
252
```python { .api }
253
class Request:
254
"""HTTP request object (from Starlette)"""
255
url: URL
256
method: str
257
headers: Headers
258
query_params: QueryParams
259
path_params: dict
260
cookies: dict
261
client: Address
262
session: dict
263
state: State
264
265
async def json(self): ...
266
async def form(self): ...
267
async def body(self): ...
268
def stream(self): ...
269
270
class Response:
271
"""HTTP response object (from Starlette)"""
272
def __init__(
273
self,
274
content: any = None,
275
status_code: int = 200,
276
headers: dict = None,
277
media_type: str = None,
278
background: BackgroundTask = None
279
): ...
280
```
281
282
[Request Response](./request-response.md)
283
284
### Exception Handling
285
286
Exception classes for HTTP errors and WebSocket errors with automatic response generation and proper status codes.
287
288
```python { .api }
289
class HTTPException(Exception):
290
def __init__(
291
self,
292
status_code: int,
293
detail: any = None,
294
headers: dict = None
295
): ...
296
297
class WebSocketException(Exception):
298
def __init__(self, code: int, reason: str = None): ...
299
```
300
301
[Exception Handling](./exception-handling.md)
302
303
### WebSocket Support
304
305
WebSocket connection handling with message sending/receiving, connection lifecycle management, and error handling.
306
307
```python { .api }
308
class WebSocket:
309
"""WebSocket connection object (from Starlette)"""
310
url: URL
311
headers: Headers
312
query_params: QueryParams
313
path_params: dict
314
cookies: dict
315
client: Address
316
state: State
317
318
async def accept(self, subprotocol: str = None, headers: dict = None): ...
319
async def close(self, code: int = 1000, reason: str = None): ...
320
async def send_text(self, data: str): ...
321
async def send_bytes(self, data: bytes): ...
322
async def send_json(self, data: any): ...
323
async def receive_text(self) -> str: ...
324
async def receive_bytes(self) -> bytes: ...
325
async def receive_json(self, mode: str = "text") -> any: ...
326
327
class WebSocketDisconnect(Exception):
328
def __init__(self, code: int = 1000, reason: str = None): ...
329
```
330
331
[WebSocket Support](./websocket-support.md)
332
333
### Background Tasks
334
335
System for executing tasks after response is sent, useful for operations like sending emails, logging, or cleanup tasks.
336
337
```python { .api }
338
class BackgroundTasks:
339
def add_task(self, func: callable, *args, **kwargs): ...
340
```
341
342
[Background Tasks](./background-tasks.md)
343
344
### File Handling
345
346
File upload handling with async methods for reading, writing, and managing uploaded files with proper content type detection.
347
348
```python { .api }
349
class UploadFile:
350
file: BinaryIO
351
filename: str
352
size: int
353
headers: Headers
354
content_type: str
355
356
async def read(self, size: int = -1) -> bytes: ...
357
async def write(self, data: bytes): ...
358
async def seek(self, offset: int): ...
359
async def close(self): ...
360
```
361
362
[File Handling](./file-handling.md)
363
364
## Types
365
366
```python { .api }
367
# Common type aliases used throughout FastAPI
368
from typing import Any, Callable, Dict, List, Optional, Union, Sequence
369
from starlette.types import ASGIApp, Receive, Scope, Send
370
371
# Key types for dependency injection
372
DependsCallable = Callable[..., Any]
373
SecurityCallable = Callable[..., Any]
374
375
# HTTP method types
376
HTTPMethods = Union[str, List[str]]
377
378
# Parameter validation types
379
ValidatorFunction = Callable[[Any], Any]
380
```