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.0.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.0.2-py3-none-any.whl (6.9 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: fastapi_class_router-0.0.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.0.2.tar.gz
Algorithm Hash digest
SHA256 469ae23329d17a8c3f84790fdc24b6d3be5ef999561c094d5a8fe4ed0015c200
MD5 b7e9e47b4d5b98d9421320dbb0c1c00c
BLAKE2b-256 3d8552cc5926b6de99553a088311ebd36fda7f39492347cce511194365946cd5

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for fastapi_class_router-0.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 0f0132a55d6a5fb6e770a95be954bc4b5667ac829cbc5ab1dcfb56efbcfbe2e4
MD5 7a67cbbac69362e5c67d22dc2dad57a5
BLAKE2b-256 9d40b33a4a00cff6d20ada886e22514c2c2d0823c77ef55b53e02f8759354bb8

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