0
0
FastAPIframework~5 mins

Configuration management in FastAPI

Choose your learning style9 modes available
Introduction

Configuration management helps your FastAPI app use settings like database info or secret keys safely and easily.

You want to keep secret keys or passwords out of your code.
You need to change settings without changing your app code.
You want to use different settings for development and production.
You want to load settings from environment variables or files.
You want to avoid hardcoding values in your FastAPI app.
Syntax
FastAPI
from pydantic import BaseSettings

class Settings(BaseSettings):
    app_name: str
    admin_email: str
    items_per_user: int = 50

    class Config:
        env_file = ".env"

settings = Settings()

Use BaseSettings from Pydantic to define config variables.

Set env_file in Config to load variables from a file.

Examples
Defines settings with a default and a required variable.
FastAPI
from pydantic import BaseSettings

class Settings(BaseSettings):
    debug: bool = False
    database_url: str

settings = Settings()
Loads secret_key from a .env file automatically.
FastAPI
from pydantic import BaseSettings

class Settings(BaseSettings):
    secret_key: str

    class Config:
        env_file = ".env"

settings = Settings()
Load settings from a specific environment file.
FastAPI
settings = Settings(_env_file='.env.production')
Sample Program

This FastAPI app uses configuration management to load settings from a .env file or environment variables. The endpoint returns these settings as JSON.

FastAPI
from fastapi import FastAPI
from pydantic import BaseSettings

class Settings(BaseSettings):
    app_name: str = "My FastAPI App"
    admin_email: str
    items_per_user: int = 10

    class Config:
        env_file = ".env"

settings = Settings()

app = FastAPI()

@app.get("/")
async def read_root():
    return {
        "app_name": settings.app_name,
        "admin_email": settings.admin_email,
        "items_per_user": settings.items_per_user
    }
OutputSuccess
Important Notes

Always keep your .env file out of version control to protect secrets.

You can override settings by setting environment variables directly.

Use type hints in BaseSettings to validate config values automatically.

Summary

Use pydantic.BaseSettings to manage FastAPI app configuration.

Load settings from environment variables or .env files for flexibility and security.

Access settings anywhere in your app by creating a settings instance.