FastAPI Utils

0.8.0 · active · verified Sun Apr 12

FastAPI Utils is a Python library providing reusable utilities for FastAPI applications, including class-based views, repeated tasks, timing middleware, and SQLAlchemy session management. It is currently at version 0.8.0 and releases seem to be quarterly or bi-annually based on recent GitHub activity.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the use of Class-Based Views (CBV) to group related endpoints and share dependencies, a core feature of fastapi-utils. Methods within the `@cbv` decorated class become endpoints on the included router, and class-level `Depends` declarations are injected as instance attributes.

from fastapi import FastAPI, Depends, APIRouter
from fastapi_utils.cbv import cbv
from fastapi_utils.inferring_router import InferringRouter # Still commonly seen, but prefer APIRouter

app = FastAPI()
router = InferringRouter() # Or APIRouter() for newer FastAPI versions

def common_dependency():
    return "Shared Data"

@cbv(router)
class ClassBasedView:
    # Dependencies shared by all methods in this class
    shared_data: str = Depends(common_dependency)

    @router.get("/items/")
    def read_items(self):
        return {"message": f"Hello from CBV, shared data: {self.shared_data}"}

    @router.post("/items/")
    def create_item(self, item_name: str):
        return {"message": f"Item '{item_name}' created with shared data: {self.shared_data}"}

app.include_router(router)

# To run: uvicorn main:app --reload (assuming this code is in main.py)

view raw JSON →