Skip to main content

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, @patch decorators directly on class methods
  • __init__ dependencies resolved per-request via FastAPI's Depends — shared across all routes in the controller
  • Full APIRouter compatibility: prefix, tags, dependencies, responses
  • Route inheritance — child controllers inherit routes from parent classes
  • as_router() and attach_to() for flexible integration
  • Sync and async endpoints 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

fastapi_class_router-0.1.2.tar.gz (6.1 kB view details)

Uploaded Source

Built Distribution

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

fastapi_class_router-0.1.2-py3-none-any.whl (6.9 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_class_router-0.1.2.tar.gz.

File metadata

  • Download URL: fastapi_class_router-0.1.2.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

Hashes for fastapi_class_router-0.1.2.tar.gz
Algorithm Hash digest
SHA256 684a2013983e59b87e2bd091f4b59afc67ad039b67d6e0867fe7c2d0d4429cad
MD5 abdbf2448436bb3edf67fa5e6d00ebe9
BLAKE2b-256 28ae4ec08bada41bb443634a5c5766a5d4b0773de6ca8cf7f3ecbcc9c417cd8b

See more details on using hashes here.

File details

Details for the file fastapi_class_router-0.1.2-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_class_router-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 c4a588d525df92a6ee4c584cd16eacb66106b5ca28069e64ecdc61f7eb89a4a3
MD5 a1ab7211bc79b9013dcc5a6a023cb0cd
BLAKE2b-256 b71f6252b6dc33f082e210665ada1032d737e39f32f45f22b59d68c9261a2896

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page