FastAPI Utils
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
- deprecated The `InferringRouter` class was deprecated in `fastapi-utils` v0.4.4. Its core functionality for inferring response models is now a built-in feature of `fastapi.APIRouter` in recent FastAPI versions.
- gotcha When using `@cbv` (Class-Based Views), any dependencies defined as class attributes will be resolved and injected for *every* endpoint method within that class, even if a specific method doesn't explicitly use `self.dependency_name`. This can lead to unnecessary work if dependencies are expensive and not universally required.
- gotcha For `repeat_every` background tasks, if you're using a modern FastAPI version (0.68.0+), `app.on_event("startup")` is deprecated in favor of `asynccontextmanager` for managing application lifespan.
- breaking fastapi-utils v0.4.0 introduced a breaking change by removing support for Python versions < 3.6.2. Ensure your project runs on Python 3.8+ as per current requirements.
Install
-
pip install fastapi-utils -
pip install fastapi-utils[session]
Imports
- cbv
from fastapi_utils.cbv import cbv
- InferringRouter
from fastapi.routing import APIRouter
- repeat_every
from fastapi_utils.tasks import repeat_every
- FastAPISessionMaker
from fastapi_utils.session import FastAPISessionMaker
- APIModel
from fastapi_utils.api_model import APIModel
- APISettings
from fastapi_utils.settings import APISettings
- StrEnum
from fastapi_utils.enums import StrEnum
- CamelStrEnum
from fastapi_utils.enums import CamelStrEnum
- GUID
from fastapi_utils.guid_type import GUID
Quickstart
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)