FastAPI Dependency Injection for Settings
Provide shared settings through a FastAPI dependency so handlers receive a configured object and tests can override it cleanly.
Code
import os
from functools import lru_cache
from typing import Annotated
from fastapi import Depends, FastAPI
from pydantic import BaseModel
app = FastAPI()
class Settings(BaseModel):
service_name: str
max_page_size: int = 100
@lru_cache
def get_settings() -> Settings:
return Settings(service_name=os.environ.get("SERVICE_NAME", "api"))
@app.get("/health")
def health(settings: Annotated[Settings, Depends(get_settings)]) -> dict:
return {"status": "ok", "service": settings.service_name}Report a problem with this exampleOpens a pre-filled issue on GitHub.