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.3.tar.gz (6.5 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.3-py3-none-any.whl (7.1 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: fastapi_class_router-0.1.3.tar.gz
  • Upload date:
  • Size: 6.5 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.3.tar.gz
Algorithm Hash digest
SHA256 f36939c08afebb63e09ffedcd2c1f8e144b953b2f8484e61c3cf65602973ee84
MD5 5aca2ca8ff96b8f253e6dbdfbe4d8895
BLAKE2b-256 4bb24d588edb12a09e94de49a36e4c2dac75b844ecaefdc04f9d30c828b8318f

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for fastapi_class_router-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 7cc04d5614e482bceebef55b0db147288f3fe94552823f705d8ac4bfd1d27d5a
MD5 3de084ae2227fb4ffa39c28afb2f7b44
BLAKE2b-256 3eff05bd9b9cca08c4c2d667e830bd78b9780df1e94ee3d770940f2d767557bf

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