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}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
fastapiandpydanticmust 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.