FastApi_Class_Router is a lightweight yet powerful library for implementing class-based routing in FastAPI. It allows you to organise your API’s logic into classes, which significantly improves code structure, promotes component reusability and facilitates the implementation of dependency injection.
Project description
fastapi-class-router
CBV-style (class-based views) controller wrapper for FastAPI that preserves 100% of APIRouter functionality.
Features
@get,@post,@put,@delete,@patchdecorators directly on class methods__init__dependencies resolved per-request via FastAPI'sDepends— shared across all routes in the controller- Full
APIRoutercompatibility:prefix,tags,dependencies,responses - Route inheritance — child controllers inherit routes from parent classes
as_router()andattach_to()for flexible integration- Sync and
asyncendpoints both supported - OpenAPI schema passthrough:
summary,description,deprecated,operation_id,include_in_schema
Installation
pip install fastapi-class-router
Requires Python ≥ 3.10 and FastAPI ≥ 0.100.
Quick Start
from fastapi import FastAPI, Depends
from fastapi_class_router import ClassRouter, get, post, put, delete
app = FastAPI()
# ── Dependencies ──────────────────────────────────────────────────────────────
def get_db():
return {"connected": True} # replace with a real session
# ── Schema ────────────────────────────────────────────────────────────────────
from pydantic import BaseModel
class ItemOut(BaseModel):
id: int
name: str
class ItemCreate(BaseModel):
name: str
# ── Controller ────────────────────────────────────────────────────────────────
class ItemController(ClassRouter, prefix="/items", tags=["Items"]):
"""
All dependencies declared in __init__ are injected per-request by FastAPI.
No manual Depends() wiring needed on individual methods.
"""
def __init__(self, db=Depends(get_db)):
self.db = db
@get("/", response_model=list[ItemOut])
async def list_items(self):
return []
@post("/", response_model=ItemOut, status_code=201)
async def create_item(self, body: ItemCreate):
return {"id": 1, "name": body.name}
# ── Register ──────────────────────────────────────────────────────────────────
app.include_router(ItemController.as_router())
Class kwargs
| kwarg | Type | Description |
|---|---|---|
prefix |
str |
URL prefix applied to all routes |
tags |
list[str] |
OpenAPI tags for all routes |
dependencies |
list |
Depends(...) applied to every route in the class |
responses |
dict |
Shared response definitions |
class SecureController(
ClassRouter,
prefix="/admin",
tags=["Admin"],
dependencies=[Depends(require_admin)],
responses={403: {"description": "Forbidden"}},
):
...
Route decorators
All decorators accept the same kwargs as APIRouter.add_api_route:
@get(
"/",
response_model=list[ItemOut],
status_code=200,
summary="List all items",
description="Returns a paginated list of items.",
deprecated=False,
operation_id="list_items",
include_in_schema=True,
dependencies=[Depends(log_request)],
responses={429: {"description": "Rate limited"}},
)
async def list_items(self):
...
Dependency Injection
Controller-level (shared across all routes)
class ReportController(ClassRouter, prefix="/reports"):
def __init__(
self,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
self.db = db
self.current_user = current_user
@get("/")
async def list_reports(self):
# self.db and self.current_user are available here
...
Route-level (specific to one endpoint)
@get("/export")
async def export(self, fmt: str = Depends(parse_format)):
...
Both levels can be combined freely.
Registration options
Option 1 — directly on the app
app.include_router(ItemController.as_router())
Option 2 — attach to an existing router (versioning)
from fastapi import APIRouter
v1 = APIRouter(prefix="/api/v1")
ItemController.attach_to(v1)
UserController.attach_to(v1)
app.include_router(v1)
Inheritance
Child controllers automatically inherit routes from their parents. Overriding a route is as simple as redefining the method:
class BaseController(ClassRouter, prefix="/base"):
def __init__(self): pass
@get("/hello")
async def hello(self):
return {"msg": "from base"}
class ChildController(BaseController, prefix="/child"):
@get("/hello") # overrides the parent route
async def hello(self):
return {"msg": "from child"}
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file fastapi_class_router-0.1.1.tar.gz.
File metadata
- Download URL: fastapi_class_router-0.1.1.tar.gz
- Upload date:
- Size: 6.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: Hatch/1.16.5 cpython/3.13.6 HTTPX/0.28.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a519dbf390aa2158b23f03efb98a9645c4d3839ae65610ed7289b863a352ff1f
|
|
| MD5 |
cdb6c520808a9799c04f1faa7dfc9e99
|
|
| BLAKE2b-256 |
58c3c70b5e7eeceefa475da4660d49582847dec7108c6884b7ab0206cc4f4287
|
File details
Details for the file fastapi_class_router-0.1.1-py3-none-any.whl.
File metadata
- Download URL: fastapi_class_router-0.1.1-py3-none-any.whl
- Upload date:
- Size: 6.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: Hatch/1.16.5 cpython/3.13.6 HTTPX/0.28.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4bb41a9aac1e751b98c181f6327ee27fed6f3d90b67a5cebc4f14011711e3ae7
|
|
| MD5 |
4f962c00b44777e855feb8946e7113c9
|
|
| BLAKE2b-256 |
0ca020174bfdf451b249aa181097c8a294a6894f86b619c2fe31f696dc6c7338
|