fastapi-viewsets¶
Django REST Framework-style ViewSets for FastAPI — auto-generate CRUD endpoints from SQLAlchemy, Tortoise ORM, or Peewee models in minutes.
Why fastapi-viewsets¶
-
Less boilerplate
Register
LIST,GET,POST,PUT,PATCH, andDELETEfrom one class — no repetitive route definitions. -
ORM-agnostic core
Pluggable adapters for SQLAlchemy (sync & async), Tortoise ORM, and Peewee via
ORM_TYPE/ optional extras. -
Typed & Pydantic-first
OpenAPI tags and response schemas generated from your
response_model. Full Pydantic v2 support. -
Declarative eager loading
select_related/prefetch_relatedvia an innerRelatedConfigclass on Pydantic schemas — eliminates N+1 without touching the viewset. -
Built-in pagination
limit/offseton LIST endpoints out of the box. -
OAuth2 on selected operations
Protect specific CRUD methods with
OAuth2PasswordBearerviaregister().
30-second example¶
from fastapi import FastAPI
from pydantic import BaseModel, ConfigDict
from sqlalchemy import Column, Integer, String
from typing import Optional
from fastapi_viewsets import BaseViewset
from fastapi_viewsets.db_conf import Base, engine, get_session
app = FastAPI()
class Item(Base):
__tablename__ = "items"
id = Column(Integer, primary_key=True)
name = Column(String(255), nullable=False)
class ItemSchema(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: Optional[int] = None
name: str
Base.metadata.create_all(bind=engine)
items = BaseViewset(
endpoint="/items",
model=Item,
response_model=ItemSchema,
db_session=get_session,
tags=["items"],
)
items.register(methods=["LIST", "GET", "POST", "PATCH", "DELETE"])
app.include_router(items)
Run it:
That's it — you now have GET /items, GET /items/{id}, POST /items, PATCH /items/{id}, and DELETE /items/{id} with full OpenAPI docs at /docs.
Feature matrix¶
| Feature | SQLAlchemy (sync) | SQLAlchemy (async) | Tortoise ORM | Peewee |
|---|---|---|---|---|
BaseViewset / AsyncBaseViewset CRUD |
✅ | ✅ (AsyncBaseViewset) |
✅ via adapter + async session | ✅ via adapter |
limit / offset on LIST |
✅ | ✅ | ✅ | ✅ |
| OAuth2 on selected methods | ✅ | ✅ | ✅ | ✅ |
| Declarative eager loading | ✅ | ✅ | ✅ (prefetch_related) |
✅ (select_related) |
search query on LIST |
Roadmap | Roadmap | Roadmap | Roadmap |
| Declarative ordering / advanced filters | Roadmap | Roadmap | Roadmap | Roadmap |
Next steps¶
- Getting Started — install and run your first viewset
- Async Quickstart —
AsyncBaseViewsetwith SQLAlchemy 2.x - ORM Adapters — Tortoise and Peewee configuration
- Eager Loading — eliminate N+1 queries with
RelatedConfig