FastAPI Dependency Injection for Settings

Provide shared settings through a FastAPI dependency so handlers receive a configured object and tests can override it cleanly.

PythonConfig Management

Code

pythonsnippet
23 lines
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}

Inside the snippet

FastAPI Dependency Injection for Settings comes down to the class Settings and the functions get_settings and health.

The import line is the dependency contract: lru_cache, Annotated, Depends, FastAPI, BaseModel come from fastapi and nothing else.

Environment variables SERVICE_NAME drive configuration, so one artifact serves every environment.

A fresh value is allocated for the result; the arguments stay untouched.

Points of care

  • fastapi and pydantic must be installed first — the snippet imports them directly.

Putting it to use

The primary signature is def get_settings() -> Settings

Treat get_settings as the API: import it, and ignore the supporting code.

Core lines

return {"status": "ok", "service": settings.service_name}
def get_settings() -> Settings:
    return Settings(service_name=os.environ.get("SERVICE_NAME", "api"))

Interactive Tools for This Topic

FAQ

Does `get_settings` modify its input?
No — a new value is constructed for the result and the arguments are never written to.
Do I need to install anything before running this?
Yes: `fastapi` and `pydantic` must be present in the project or the import fails at load time.