Skip to main content

fastapi-views

Tests Build License Mypy Ruff) Pydantic v2 security: bandit Python Format PyPi

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 viewsView, APIView, APIViewSet, and GenericViewSet at three levels of abstraction; mix-in only the actions you need
  • Full CRUD in one classlist, create, retrieve, update, partial_update, destroy with correct HTTP semantics out of the box (201 Created, 204 No Content, Location header, etc.)
  • Generic views with the repository pattern — plug in any data source (SQLAlchemy, Motor, plain dicts) via a simple protocol; no ORM dependency
  • Bulk actionsAsyncBulkAPIViewSet adds bulk create, per-item bulk update, filtered update, and filtered delete on a single /bulk route
  • JSON Patch — RFC 6902 PATCH support with application/json-patch+json request bodies (optional extra)
  • DRF-style filtersModelFilter, OrderingFilter, SearchFilter, PaginationFilter, OffsetLimitFilter, CursorPaginationFilter, FieldsFilter, and a combined Filter class; 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 serializationTypeAdapter cached per schema type avoids the double validation/model instantiation that FastAPI does by default, reducing per-request overhead
  • Response cachingCachedAPIView, the @cache decorator, and CacheMiddleware, with in-memory and Redis backends (optional extra)
  • Conditional requestsConditionalMixin emits ETag / Last-Modified validators and answers 304 Not Modified from a cheap version column, without serialising a body
  • Documented response headers — declare a ResponseHeaders model on a view, action, or router and the headers show up in the OpenAPI spec
  • Server-Sent EventsServerSentEventsAPIView and @sse_route handle framing, content-type, and Pydantic validation automatically
  • WebSocketsWebSocketAPIView handles 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 Security system: JWTAuth (JWKS import, claims validation, token minting), hierarchical OAuth2 scope enforcement via requires(*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, and Translated[str] model fields; built-in error messages are translatable out of the box (optional extra)
  • Async and sync support — every class ships an Async and a synchronous variant; sync endpoints run in a thread pool
  • One-call setupconfigure_app(app) registers error handlers, Prometheus middleware, OpenTelemetry instrumentation, locale detection, optional request logging, and a concurrency limit
  • Prometheus metrics/metrics endpoint with request count, latency histogram, and in-flight requests (optional extra)
  • OpenTelemetry tracingcorrelation_id injected into every error response for easy trace correlation (optional extra)
  • Structured request logging — opt-in RequestLoggingMiddleware backed by structlog, enabled with configure_app(enable_request_logging_middleware=True) (optional extra)
  • Readable OpenAPI operation IDslist_item, create_item, retrieve_item instead of FastAPI's long path-derived defaults
  • CLI — export a static openapi.json / openapi.yaml without 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

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_views-2.0.1.tar.gz (62.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_views-2.0.1-py3-none-any.whl (87.8 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_views-2.0.1.tar.gz.

File metadata

  • Download URL: fastapi_views-2.0.1.tar.gz
  • Upload date:
  • Size: 62.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.8.13

File hashes

Hashes for fastapi_views-2.0.1.tar.gz
Algorithm Hash digest
SHA256 3a879fd917d4b9647194deab78b7d0fb310c2f7617076f845830f2f229bf33de
MD5 cb63c98b8114fe285fdd1b62b57bd07f
BLAKE2b-256 43a544cf6646744567c7b39147855a9ebebad4d48bdf17dfa130ae4b070dcfbd

See more details on using hashes here.

File details

Details for the file fastapi_views-2.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_views-2.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 d2db21d8151ee721aa52ae04aaed160f7ffd9f46c816a5e603cb83d77caa06f9
MD5 3faf106c7c759d05f39baa3275ae0303
BLAKE2b-256 8d045dc553cb44d67cc8592110d20346ecb3a417ab24532350788c3c1ecd45e1

See more details on using hashes here.

Release history Release notifications | RSS feed

2.0.2

2 files

This release

2.0.1 This release

2 files

2.0.0

2 files

1.8.3

2 files

1.8.2

2 files

1.8.1

2 files

1.8.0

2 files

1.7.0

2 files

1.6.4

2 files

1.6.3

2 files

1.6.2

2 files

1.6.1

2 files

1.6.0

2 files

1.5.1

2 files

1.5.0

2 files

1.4.0

2 files

1.3.1

2 files

1.3.0

2 files

1.2.2

2 files

1.2.1

2 files

1.2.0

2 files

1.1.0

2 files

1.0.6

2 files

1.0.5

2 files

0.3.2

2 files

0.3.1

2 files

0.3.0

2 files

0.2.0

2 files

0.1.2

2 files

0.1.1

2 files

0.1.0

2 files

0.0.7

2 files

0.0.6

2 files

0.0.5

2 files

0.0.4

2 files

0.0.2

2 files

0.0.1

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page