How to Use Config Class in FastAPI for Settings Management
In FastAPI, you can use a
config class by creating a Pydantic model to hold your settings and then loading it once for your app. This class centralizes configuration like database URLs or API keys, making your code cleaner and easier to manage.Syntax
Define a config class by subclassing pydantic.BaseSettings. Each attribute represents a setting with an optional default value. FastAPI can then use this class to load environment variables automatically.
Example parts:
class Config(BaseSettings):- declares the config class.- Attributes like
database_url: str- define settings. - Optional
Configinner class to customize behavior.
python
from pydantic import BaseSettings class Config(BaseSettings): database_url: str api_key: str = "default_key" class Config: env_file = ".env" # Optional: load from .env file
Example
This example shows how to create a config class, load settings from environment variables or a .env file, and use it in a FastAPI app.
python
from fastapi import FastAPI from pydantic import BaseSettings class Config(BaseSettings): database_url: str api_key: str = "default_key" class Config: env_file = ".env" app = FastAPI() settings = Config() @app.get("/settings") def read_settings(): return {"database_url": settings.database_url, "api_key": settings.api_key}
Output
{"database_url": "postgresql://user:pass@localhost/db", "api_key": "default_key"}
Common Pitfalls
Common mistakes when using config classes in FastAPI include:
- Not subclassing
BaseSettings, so environment variables won't load automatically. - Forgetting to create a single instance of the config class and instead recreating it multiple times.
- Not specifying
env_fileif you rely on a .env file for local development. - Using mutable default values in the config class attributes.
python
from pydantic import BaseSettings # Wrong: Not subclassing BaseSettings class WrongConfig: database_url = "sqlite:///test.db" # Right: Subclass BaseSettings and use env_file class RightConfig(BaseSettings): database_url: str class Config: env_file = ".env"
Quick Reference
- Define config: subclass
BaseSettings. - Load env vars: use
env_filein innerConfigclass. - Use single instance: create one config object and reuse it.
- Access settings: use attributes like
settings.database_url.
Key Takeaways
Use a Pydantic class subclassing BaseSettings to manage FastAPI config cleanly.
Load environment variables automatically by specifying an env_file in the config class.
Create one config instance and reuse it throughout your FastAPI app.
Avoid mutable defaults and always subclass BaseSettings for automatic env loading.
Access config values via attributes on the config instance for clarity and safety.