fastapi-views
Class-based views, CRUD utilities, and production-ready patterns for FastAPI.
FastAPI Views brings Django REST Framework-style class-based views to FastAPI — without giving up type safety or dependency injection. Define a full CRUD resource by inheriting one class; routes, status codes, and OpenAPI docs are wired up automatically.
Features
- Class-based views —
View,APIView,APIViewSet, andGenericViewSetat three levels of abstraction; mix-in only the actions you need - Full CRUD in one class —
list,create,retrieve,update,partial_update,destroywith correct HTTP semantics out of the box (201 Created,204 No Content,Locationheader, etc.) - Generic views with the repository pattern — plug in any data source (SQLAlchemy, Motor, plain dicts) via a simple protocol; no ORM dependency
- Bulk actions —
AsyncBulkAPIViewSetadds bulk create, per-item bulk update, filtered update, and filtered delete on a single/bulkroute - JSON Patch — RFC 6902
PATCHsupport withapplication/json-patch+jsonrequest bodies (optional extra) - DRF-style filters —
ModelFilter,OrderingFilter,SearchFilter,PaginationFilter,OffsetLimitFilter,CursorPaginationFilter,FieldsFilter, and a combinedFilterclass; built-in SQLAlchemy and Python object resolvers - RFC 9457 Problem Details — every error response is machine-readable; built-in classes for the most common cases; custom errors auto-register in the OpenAPI spec
- Fast Pydantic v2 serialization —
TypeAdaptercached per schema type avoids the double validation/model instantiation that FastAPI does by default, reducing per-request overhead - Response caching —
CachedAPIView, the@cachedecorator, andCacheMiddleware, with in-memory and Redis backends (optional extra) - Conditional requests —
ConditionalMixinemitsETag/Last-Modifiedvalidators and answers304 Not Modifiedfrom a cheap version column, without serialising a body - Documented response headers — declare a
ResponseHeadersmodel on a view, action, or router and the headers show up in the OpenAPI spec - Server-Sent Events —
ServerSentEventsAPIViewand@sse_routehandle framing, content-type, and Pydantic validation automatically - WebSockets —
WebSocketAPIViewhandles connection lifecycle, per-class connection tracking, broadcast helpers, and Pydantic validation of binary frames; disconnects and failed handshakes are cleaned up without masking the original error - Authentication & authorization — bearer-token auth built on FastAPI's
Securitysystem:JWTAuth(JWKS import, claims validation, token minting), hierarchical OAuth2 scope enforcement viarequires(*scopes), header API-key auth (APIKeyAuth,ConstAPIKeyAuth), and an Auth0 integration (optional extras) - Internationalization (i18n) — per-request locale detection (query param, cookie,
Accept-Language), pluggable translation managers (JSON files, in-memory, or custom),str.format/Jinja2 formatters, andTranslated[str]model fields; built-in error messages are translatable out of the box (optional extra) - Async and sync support — every class ships an
Asyncand a synchronous variant; sync endpoints run in a thread pool - One-call setup —
configure_app(app)registers error handlers, Prometheus middleware, OpenTelemetry instrumentation, locale detection, optional request logging, and a concurrency limit - Prometheus metrics —
/metricsendpoint with request count, latency histogram, and in-flight requests (optional extra) - OpenTelemetry tracing —
correlation_idinjected into every error response for easy trace correlation (optional extra) - Structured request logging — opt-in
RequestLoggingMiddlewarebacked bystructlog, enabled withconfigure_app(enable_request_logging_middleware=True)(optional extra) - Readable OpenAPI operation IDs —
list_item,create_item,retrieve_iteminstead of FastAPI's long path-derived defaults - CLI — export a static
openapi.json/openapi.yamlwithout starting a server
Documentation: https://asynq-io.github.io/fastapi-views/
Repository: https://github.com/asynq-io/fastapi-views
Installation
pip install fastapi-views
Optional dependencies
Available extensions: uvloop, uvicorn, prometheus, opentelemetry, cli, structlog, websockets, jose (JWT auth), auth0 (Auth0 auth), i18n, cache (Redis), jsonpatch, sqlargon (SQLAlchemy repositories), and standard (a curated bundle).
pip install 'fastapi-views[all]'
Quick start
from typing import ClassVar, Optional
from uuid import UUID
from fastapi import FastAPI
from pydantic import BaseModel
from fastapi_views import ViewRouter, configure_app
from fastapi_views.views.viewsets import AsyncAPIViewSet
class ItemSchema(BaseModel):
id: UUID
name: str
price: int
class ItemViewSet(AsyncAPIViewSet):
api_component_name = "Item"
response_schema = ItemSchema
# In-memory store — swap for a real repository in production
items: ClassVar[dict[UUID, ItemSchema]] = {}
async def list(self) -> list[ItemSchema]:
return list(self.items.values())
async def create(self, item: ItemSchema) -> ItemSchema:
self.items[item.id] = item
return item
async def retrieve(self, id: UUID) -> Optional[ItemSchema]:
return self.items.get(id)
async def update(self, id: UUID, item: ItemSchema) -> ItemSchema:
self.items[id] = item
return item
async def destroy(self, id: UUID) -> None:
self.items.pop(id, None)
router = ViewRouter(prefix="/items")
router.register_view(ItemViewSet)
app = FastAPI(title="My API")
app.include_router(router)
configure_app(app)
This registers the following routes automatically:
| Method | Path | Action | Status code |
|---|---|---|---|
GET |
/items |
list |
200 |
POST |
/items |
create |
201 |
GET |
/items/{id} |
retrieve |
200 |
PUT |
/items/{id} |
update |
200 |
DELETE |
/items/{id} |
destroy |
204 |
Release files for fastapi-views 2.0.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| fastapi_views-2.0.2.tar.gz | 62.9 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| fastapi_views-2.0.2-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 150.7 kB
Release files / fastapi_views-2.0.2.tar.gz
| Download URL | fastapi_views-2.0.2.tar.gz |
|---|---|
| Size | 62.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
e068b39a89a27952d79f3b3adf770a650693475a03a61079ead89fb73851fe00
|
|
BLAKE2b-256 checksum How to use checksums |
daef4d0415eb32ecb7bb4f9ba827be7a6f467cdcc02f1afddccc292ee461025f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.8.13
|
Release files / fastapi_views-2.0.2-py3-none-any.whl
| Download URL | fastapi_views-2.0.2-py3-none-any.whl |
|---|---|
| Size | 87.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
29a8749b55b9bf53148b40e4179b04aa946d40848ffa36e542c26cd384fa9634
|
|
BLAKE2b-256 checksum How to use checksums |
80e4120124c9d5023e53ccda4b283d266225b9a022c47b1bcd0c515103119cba
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.8.13
|