In FastAPI, using configuration files is a common practice to manage application settings, database credentials, and other environment-specific variables. Pydantic, a powerful data validation library, can be used to create and validate configuration files in a structured and type-safe manner.
Creating a Configuration Model
Import Pydantic:
Python
from pydantic import BaseModel
Define the Configuration Model:
Python
class Settings(BaseModel):
debug: bool = True
database_url: str = "postgresql://user:password@host:port/database"
secret_key: str
This Settings
model defines three configuration options: debug
, database_url
, and secret_key
. The debug
option is set to True
by default, while the database_url
and secret_key
options are left as required fields.
Loading the Configuration
Create a Function to Load the Configuration:
from dotenv import load_dotenv
from pathlib import Path
def get_settings():
load_dotenv()
return Settings()
This function loads environment variables from a .env
file using the dotenv
library and creates a Settings
instance using the loaded values.
Using the Configuration in FastAPI
Create a Dependency:
from fastapi import Depends
def get_settings(settings: Settings = Depends(get_settings)):
return settings
Inject the Configuration into Endpoints:
from fastapi import APIRouter, Depends
router = APIRouter()
@router.get(“/”)
def read_root(settings: Settings = Depends(get_settings)):
return {“debug”: settings.debug, “database_url”: settings.database_url}
Additional Considerations
- Environment Variables: You can set configuration values as environment variables and load them using the
dotenv
library. This allows you to manage different configurations for different environments (e.g., development, testing, production). - Secret Management: For sensitive information like API keys or database passwords, consider using a secret management service or storing them in environment variables that are not checked into your source code.
- Validation: Pydantic provides built-in validation to ensure that configuration values adhere to the specified types and constraints.
- Configuration Files: While using environment variables is a common approach, you can also store configuration values in dedicated configuration files (e.g.,
settings.py
) and load them using Python’s built-in configuration modules.