API Reference¶
This page documents every public class and function exported from FasterAPI.
For the full list of re-exports, see
FasterAPI/__init__.py.
Application¶
Faster¶
The main ASGI application class.
from FasterAPI import Faster
app = Faster(
title="My API", # shown in Swagger UI
version="1.0.0", # shown in Swagger UI
description="...", # Markdown description
openapi_url="/openapi.json", # set to None to disable
docs_url="/docs", # Swagger UI; None to disable
redoc_url="/redoc", # ReDoc; None to disable
)
Route decorators: @app.get, @app.post, @app.put, @app.delete,
@app.patch, @app.websocket
Lifecycle: @app.on_startup, @app.on_shutdown
Middleware: app.add_middleware(MiddlewareClass, **kwargs)
Exception handlers: app.add_exception_handler(ExcClass, handler)
Router inclusion: app.include_router(router, prefix="", tags=())
FasterRouter¶
Groups related routes into a reusable router.
from FasterAPI import FasterRouter
router = FasterRouter()
@router.get("/")
async def list_items(): ...
app.include_router(router, prefix="/items", tags=["items"])
Request & Response¶
Request¶
Represents an incoming HTTP request.
from FasterAPI import Request
@app.get("/info")
async def info(request: Request):
return {
"method": request.method,
"path": request.url.path,
"client": request.client,
}
Key attributes:
| Attribute | Type | Description |
|---|---|---|
method |
str |
HTTP verb |
url |
URL | Full URL |
headers |
Headers | Request headers (case-insensitive) |
query_params |
QueryParams | Parsed query string |
cookies |
dict[str, str] |
Parsed cookies |
client |
tuple[str, int] \| None |
Client IP and port |
path_params |
dict[str, str] |
Matched path segments |
Async methods: await request.body(), await request.json(),
await request.form()
Response¶
Base HTTP response. All response classes accept content, status_code, headers,
and optionally media_type.
from FasterAPI import Response
return Response(content=b"raw bytes", status_code=200, media_type="text/plain")
JSONResponse¶
Serialises content with msgspec.json.encode.
HTMLResponse¶
Sets Content-Type: text/html.
PlainTextResponse¶
Sets Content-Type: text/plain.
RedirectResponse¶
Issues an HTTP redirect.
StreamingResponse¶
Streams body from an async or sync iterator.
from FasterAPI import StreamingResponse
async def gen():
yield b"chunk1"
yield b"chunk2"
return StreamingResponse(gen(), media_type="text/plain")
FileResponse¶
Serves a file from disk with Content-Disposition: attachment.
Parameters¶
Path¶
Marks a parameter as coming from the URL path. Usage: item_id: int = Path().
Query¶
Marks a parameter as coming from the query string.
from FasterAPI import Query
async def search(q: str | None = Query(default=None, alias="search")): ...
Header¶
Marks a parameter as coming from a request header. Underscores in the parameter name
are converted to hyphens by default (convert_underscores=True).
from FasterAPI import Header
async def handler(user_agent: str | None = Header(default=None)): ...
# reads "User-Agent" header
Cookie¶
Marks a parameter as coming from a cookie.
Body¶
Marks a parameter as coming from the raw JSON request body.
Form¶
Marks a parameter as coming from form data.
File¶
Marks a parameter as an uploaded file.
Dependency Injection¶
Depends¶
Declares a dependency to be resolved before the route handler.
from FasterAPI import Depends
async def get_db(): ...
@app.get("/items")
async def handler(db = Depends(get_db)): ...
Parameters:
- dependency — callable to resolve
- use_cache=True — if True, calls dependency once per request
Exceptions¶
HTTPException¶
from FasterAPI import HTTPException
raise HTTPException(status_code=404, detail="Not found")
raise HTTPException(status_code=401, headers={"WWW-Authenticate": "Bearer"})
RequestValidationError¶
Raised automatically when a path/query/body parameter fails validation.
from FasterAPI.exceptions import RequestValidationError
app.add_exception_handler(RequestValidationError, my_handler)
Middleware¶
BaseHTTPMiddleware¶
Subclass to write custom middleware:
from FasterAPI import BaseHTTPMiddleware
class MyMiddleware(BaseHTTPMiddleware):
async def dispatch(self, scope, receive, send):
# before
await self.app(scope, receive, send)
# after
CORSMiddleware¶
from FasterAPI import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
allow_credentials=False,
max_age=600,
)
GZipMiddleware¶
TrustedHostMiddleware¶
from FasterAPI import TrustedHostMiddleware
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["example.com"])
HTTPSRedirectMiddleware¶
Background Tasks¶
BackgroundTasks¶
from FasterAPI import BackgroundTasks
@app.post("/items")
async def create(tasks: BackgroundTasks):
tasks.add_task(send_email, "user@example.com")
return {"queued": True}
BackgroundTask¶
Single task wrapper:
WebSocket¶
WebSocket¶
from FasterAPI import WebSocket
@app.websocket("/ws")
async def ws_handler(ws: WebSocket):
await ws.accept()
data = await ws.receive_text()
await ws.send_text(f"Echo: {data}")
Methods: accept(), receive_text(), receive_bytes(), receive_json(),
send_text(), send_bytes(), send_json(), close(code=1000)
WebSocketDisconnect¶
Exception raised when the client disconnects.
WebSocketState¶
Enum: CONNECTING, CONNECTED, DISCONNECTED
Data Structures¶
UploadFile¶
Represents an uploaded file:
| Attribute / method | Description |
|---|---|
filename |
Original filename |
content_type |
MIME type |
await file.read() |
Read all bytes |
FormData¶
Mapping-like object returned by await request.form().
Concurrency¶
SubInterpreterPool¶
CPU-parallel worker pool using Python 3.13 sub-interpreters (falls back to
ProcessPoolExecutor on earlier versions).
run_in_subinterpreter¶
Run a function in a sub-interpreter and return an asyncio.Future:
from FasterAPI import run_in_subinterpreter
result = await run_in_subinterpreter(heavy_function, arg1, arg2)
Auto-generated docs¶
FasterAPI
¶
FasterAPI — A high-performance ASGI web framework.
Drop-in FastAPI replacement powered by msgspec (C extension JSON), radix-tree routing, uvloop, and Python 3.13 sub-interpreters.
APIKeyCookie
¶
Bases: _APIKeyBase
API key extracted from a cookie.
api_key_cookie = APIKeyCookie(name="session")
@app.get("/secure") async def secure(key: str = Depends(api_key_cookie)): ...
Source code in FasterAPI/security.py
APIKeyHeader
¶
Bases: _APIKeyBase
API key extracted from an HTTP request header.
api_key_header = APIKeyHeader(name="X-API-Key")
@app.get("/secure") async def secure(key: str = Depends(api_key_header)): ...
Source code in FasterAPI/security.py
APIKeyQuery
¶
Bases: _APIKeyBase
API key extracted from a query parameter.
api_key_query = APIKeyQuery(name="api_key")
@app.get("/secure") async def secure(key: str = Depends(api_key_query)): ...
Source code in FasterAPI/security.py
BackgroundTask
¶
A single background task to be executed after a response is sent.
Source code in FasterAPI/background.py
run()
async
¶
Execute the background task.
BackgroundTasks
¶
A collection of background tasks to be executed after a response is sent.
Source code in FasterAPI/background.py
add_task(func, *args, **kwargs)
¶
BaseHTTPMiddleware
¶
Base class for HTTP middleware that wraps an ASGI application.
Source code in FasterAPI/middleware.py
dispatch(scope, receive, send)
async
¶
Process the request. Override this method in subclasses.
Source code in FasterAPI/middleware.py
Body
¶
Declare a request body parameter with optional default and embed mode.
Source code in FasterAPI/params.py
CORSMiddleware
¶
Bases: BaseHTTPMiddleware
Middleware that handles Cross-Origin Resource Sharing (CORS) headers.
Source code in FasterAPI/middleware.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 | |
dispatch(scope, receive, send)
async
¶
Handle CORS preflight requests and inject CORS headers into responses.
Source code in FasterAPI/middleware.py
Cookie
¶
Declare a cookie parameter with an optional default value.
Source code in FasterAPI/params.py
DatabasePoolMiddleware
¶
Bases: BaseHTTPMiddleware
Attach a shared pool/engine object to scope["state"] for handlers.
Typical usage with SQLAlchemy::
engine = create_async_engine(url, pool_size=20)
app.add_middleware(DatabasePoolMiddleware, pool=engine, state_key="engine")
def get_engine(request: Request):
return request.state["engine"]
For asyncpg, pass the asyncpg.Pool instance as pool.
Source code in FasterAPI/production.py
Depends
¶
Declare a dependency to be resolved and injected into a route handler.
Source code in FasterAPI/dependencies.py
EventSourceResponse
¶
Server-Sent Events (SSE) response.
Streams events to the client in the text/event-stream format.
Usage::
async def event_generator():
yield {"data": "hello"}
yield {"event": "update", "data": "world", "id": "1"}
@app.get("/stream")
async def stream():
return EventSourceResponse(event_generator())
Source code in FasterAPI/response.py
Faster
¶
The main FasterAPI application class, implementing the ASGI interface.
Source code in FasterAPI/app.py
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 | |
mount(path, app, name=None)
¶
Mount an ASGI sub-application (e.g. StaticFiles) at path.
Example::
app.mount("/static", StaticFiles(directory="static"), name="static")
Source code in FasterAPI/app.py
FasterRouter
¶
API router for grouping routes with a common prefix, tags, and dependencies.
Source code in FasterAPI/router.py
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 | |
File
¶
Declare a file upload parameter.
Source code in FasterAPI/params.py
FileResponse
¶
Response that sends a file as an attachment.
Source code in FasterAPI/response.py
to_asgi(send)
async
¶
Read the file and send it through the ASGI interface.
Source code in FasterAPI/response.py
Form
¶
Declare a form field parameter with an optional default value.
Source code in FasterAPI/params.py
FormData
¶
Bases: dict[str, Any]
Dict subclass for form data that may contain UploadFile values.
Source code in FasterAPI/datastructures.py
GZipMiddleware
¶
Bases: BaseHTTPMiddleware
Middleware that compresses responses using gzip when the client supports it.
Source code in FasterAPI/middleware.py
dispatch(scope, receive, send)
async
¶
Compress the response body with gzip if it exceeds the minimum size.
Source code in FasterAPI/middleware.py
HTMLResponse
¶
HTTPBasic
¶
Extracts credentials from an HTTP Basic Authorization header.
Use as a dependency:
http_basic = HTTPBasic()
@app.get("/protected")
async def protected(creds: HTTPBasicCredentials = Depends(http_basic)):
...
Source code in FasterAPI/security.py
HTTPBasicCredentials
¶
Username and password extracted from an HTTP Basic Authorization header.
Source code in FasterAPI/security.py
HTTPException
¶
Bases: Exception
An HTTP exception that results in an error response with the given status code.
Source code in FasterAPI/exceptions.py
HTTPSRedirectMiddleware
¶
Bases: BaseHTTPMiddleware
Middleware that redirects all HTTP requests to HTTPS.
Source code in FasterAPI/middleware.py
Header
¶
Declare a header parameter with optional default and alias.
Source code in FasterAPI/params.py
JSONResponse
¶
Bases: Response
Response that serializes content as JSON using msgspec (with datetime/UUID/Decimal support).
Pass bytes, bytearray, or memoryview to skip encoding and send pre-serialised
JSON (hot-path optimisation when the payload is fixed at import time or cached externally).
Source code in FasterAPI/response.py
JWTBearer
¶
Decode a Bearer JWT from Authorization and inject claims as a dict.
Usage::
jwt_scheme = JWTBearer(secret=settings.jwt_secret)
@app.get("/me")
async def me(claims: dict = Depends(jwt_scheme)):
user_id = claims.get("sub")
Source code in FasterAPI/jwt_auth.py
Jinja2Templates
¶
Render Jinja2 templates as HTML responses.
Usage::
templates = Jinja2Templates(directory="templates")
@app.get("/hello/{name}")
async def hello(request: Request, name: str):
return templates.TemplateResponse(request, "hello.html", {"name": name})
Requires jinja2 to be installed: pip install jinja2.
Source code in FasterAPI/templating.py
OAuth2PasswordBearer
¶
Extracts a Bearer token from the Authorization header.
Use as a dependency:
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token")
@app.get("/me")
async def me(token: str = Depends(oauth2_scheme)):
...
Source code in FasterAPI/security.py
OAuth2PasswordRequestForm
¶
Parses an OAuth2 password flow form submission.
Use as a dependency:
@app.post("/token")
async def login(form: OAuth2PasswordRequestForm = Depends()):
form.username, form.password, form.scopes
Source code in FasterAPI/security.py
from_request(request)
async
classmethod
¶
Parse form data from a request and return a populated instance.
Source code in FasterAPI/security.py
Path
¶
Declare a path parameter with optional default and description.
Source code in FasterAPI/params.py
PlainTextResponse
¶
Query
¶
Declare a query parameter with optional default, description, and alias.
Source code in FasterAPI/params.py
RadixRouter
¶
O(k) URL router using a compressed radix tree (k = path segments).
Source code in FasterAPI/router.py
add_route(method, path, handler, metadata=None)
¶
Register a handler for the given HTTP method and path pattern.
Source code in FasterAPI/router.py
resolve(method, path)
¶
Resolve a path to (handler, path_params, metadata) or None.
Source code in FasterAPI/router.py
RateLimitMiddleware
¶
Bases: BaseHTTPMiddleware
Simple sliding-window rate limit per client IP (in-memory).
Not suitable for multi-process deployments without a shared store—use Redis etc. for horizontal scale. For single-worker or development this is enough.
client from ASGI scope is used unless forwarded_for_header is set and
the header exists (first hop).
Source code in FasterAPI/production.py
RedirectResponse
¶
Bases: Response
Response that redirects to a different URL.
Source code in FasterAPI/response.py
RedisCacheMiddleware
¶
Bases: BaseHTTPMiddleware
Cache GET responses (small bodies) in Redis.
Skips caching when the client sends Cache-Control: no-cache or when the
response status is not in cacheable_statuses. Suitable for idempotent JSON
APIs; validate before caching authenticated routes.
Requires redis>=5 with redis.asyncio and pip install redis.
Source code in FasterAPI/redis_cache.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | |
Request
¶
Represents an incoming HTTP request with lazy attribute parsing.
Source code in FasterAPI/request.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | |
state
property
¶
Mutable per-request state (ASGI scope["state"]).
form()
async
¶
Read the request body and parse as form / multipart data.
Source code in FasterAPI/request.py
json()
async
¶
stream()
async
¶
Yield body chunks from the ASGI receive channel.
When Faster(stream_request_body=False) (default), chunks are also
concatenated so :meth:body, :meth:json, and :meth:form still work.
With stream_request_body=True, bytes are not retained after
iteration—use this for large uploads written straight to disk.
Source code in FasterAPI/request.py
RequestIDMiddleware
¶
Bases: BaseHTTPMiddleware
Ensure each request has X-Request-ID (generate or propagate).
The ID is stored in scope["state"]["request_id"] (also available as
request.state["request_id"]).
Source code in FasterAPI/production.py
RequestValidationError
¶
Bases: Exception
Raised when request data fails validation.
Source code in FasterAPI/exceptions.py
Response
¶
Base HTTP response class.
Source code in FasterAPI/response.py
to_asgi(send)
async
¶
Send the response through the ASGI interface.
Source code in FasterAPI/response.py
SecurityScopes
¶
Holds the list of OAuth2 security scopes required by a dependency tree.
Source code in FasterAPI/security.py
StaticFiles
¶
Serve static files from a local directory as an ASGI application.
Behaviour aligns with common Starlette patterns: conditional GET (ETag /
Last-Modified, 304 Not Modified), Range requests (206 including
multipart byte ranges), HEAD without a body, and async chunked reads via
anyio.
Source code in FasterAPI/staticfiles.py
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 | |
StreamingResponse
¶
Response that streams content from an async or sync iterator.
Source code in FasterAPI/response.py
to_asgi(send)
async
¶
Stream the response body through the ASGI interface.
Source code in FasterAPI/response.py
SubInterpreterPool
¶
Fallback pool using ProcessPoolExecutor.
Provides the same run() / shutdown() API as the
sub-interpreter pool. Upgrade to a Python version with the
interpreters module for true per-interpreter GIL support.
Source code in FasterAPI/concurrency.py
run(func, *args)
async
¶
Execute func in a worker process (pickle-based).
Source code in FasterAPI/concurrency.py
TestClient
¶
Synchronous test client for FasterAPI applications.
Wraps ASGI app with httpx.ASGITransport for HTTP testing. Provides websocket_connect() for WebSocket testing.
Source code in FasterAPI/testclient.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 | |
delete(url, **kwargs)
¶
get(url, **kwargs)
¶
head(url, **kwargs)
¶
options(url, **kwargs)
¶
patch(url, **kwargs)
¶
post(url, **kwargs)
¶
put(url, **kwargs)
¶
websocket_connect(path, headers=None, query_string='')
¶
Context manager for testing WebSocket endpoints.
Source code in FasterAPI/testclient.py
TrustedHostMiddleware
¶
Bases: BaseHTTPMiddleware
Middleware that validates the Host header against a list of allowed hosts.
Source code in FasterAPI/middleware.py
UploadFile
¶
Represents an uploaded file from a multipart/form-data request.
Uses SpooledTemporaryFile: data stays in memory up to 1 MB, then spills to disk.
Source code in FasterAPI/datastructures.py
WebSocket
¶
Represents a WebSocket connection.
Source code in FasterAPI/websocket.py
accept(subprotocol=None)
async
¶
Accept the WebSocket connection, optionally selecting a subprotocol.
Source code in FasterAPI/websocket.py
close(code=1000, reason='')
async
¶
Close the WebSocket connection.
receive_bytes()
async
¶
Receive a binary message from the WebSocket.
receive_json()
async
¶
receive_text()
async
¶
send_bytes(data)
async
¶
send_json(data)
async
¶
Send data as a JSON-encoded text message through the WebSocket.
WebSocketDisconnect
¶
WebSocketState
¶
async_engine_from_url_optional(url, **kwargs)
¶
Create an async engine if SQLAlchemy is installed; raise ImportError otherwise.
Source code in FasterAPI/sqlalchemy_ext.py
configure_structlog(*, json_format=False, log_level='INFO')
¶
Configure structlog for JSON or console output.
Requires pip install structlog. Safe to call once at process startup.
Bind fields per request (often request_id from middleware) via::
import structlog
structlog.contextvars.bind_contextvars(request_id=...)
Source code in FasterAPI/log_config.py
create_access_token(subject, secret, *, algorithm='HS256', expires_delta=None, expires_minutes=60, audience=None, issuer=None, extra_claims=None)
¶
Create a signed JWT string (sub claim from subject or merge subject dict).
Source code in FasterAPI/jwt_auth.py
get_header(scope, name)
¶
Case-insensitive header lookup from ASGI scope["headers"].
Source code in FasterAPI/asgi_compat.py
get_server_host(scope)
¶
Hostname for virtual hosting: Host or :authority, then server tuple.
Source code in FasterAPI/asgi_compat.py
http_version(scope)
¶
Return HTTP version string from scope (e.g. "1.1", "2").
is_http2(scope)
¶
oauth2_access_token_json(access_token, *, token_type='bearer', expires_in=None)
¶
JSON body shape for POST /token OAuth2 password / client responses (RFC 6749 §5.1).
Source code in FasterAPI/jwt_auth.py
oauth2_password_token_response(form, *, secret, authenticate, expires_minutes=60)
async
¶
Validate credentials via authenticate and return an OAuth2-style token JSON dict.
Typical handler::
@app.post("/token")
async def token(form: OAuth2PasswordRequestForm = Depends(OAuth2PasswordRequestForm)):
return await oauth2_password_token_response(form, secret=SECRET, authenticate=verify_user)
authenticate should return a subject string (e.g. user id) or None if invalid.
Source code in FasterAPI/jwt_auth.py
run_in_subinterpreter(func, *args)
async
¶
Execute func with maximum available parallelism.
Python 3.13+: Runs in a sub-interpreter with its own GIL. True parallel execution, no pickling, ~100x lighter than a process.
Python 3.11–3.12: Falls back to ProcessPoolExecutor.
Arguments must be picklable. Still achieves parallelism via
multiprocessing.
Python < 3.11: Same as 3.11 fallback with older asyncio internals.
Usage::
result = await run_in_subinterpreter(heavy_computation, n)
Source code in FasterAPI/concurrency.py
sqlalchemy_session_dependency(session_factory)
¶
Return an async dependency that yields one :class:sqlalchemy.ext.asyncio.AsyncSession.
The factory must be an :class:async_sessionmaker (or any callable returning
an object usable as async with session_factory() as session:.
Usage::
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from FasterAPI import Depends, Faster
from FasterAPI.sqlalchemy_ext import sqlalchemy_session_dependency
engine = create_async_engine("postgresql+asyncpg://...", echo=False)
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
get_session = sqlalchemy_session_dependency(SessionLocal)
app = Faster()
@app.get("/rows")
async def rows(session: AsyncSession = Depends(get_session)):
...
Install: pip install faster-api-web[ecosystem] or sqlalchemy[asyncio].