0
0
FastAPIframework~5 mins

Environment-based settings in FastAPI

Choose your learning style9 modes available
Introduction

Environment-based settings help your app use different values depending on where it runs, like your computer or a server. This keeps your app flexible and safe.

When you want to use different database addresses for development and production.
When you need to keep secret keys safe and not share them in your code.
When you want to change app behavior without changing code, like turning debug mode on or off.
When deploying the same app to multiple environments with different settings.
When you want to avoid hardcoding values that might change later.
Syntax
FastAPI
from pydantic import BaseSettings

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

    class Config:
        env_file = ".env"

settings = Settings()

Use BaseSettings from Pydantic to define environment-based settings easily.

The env_file option tells Pydantic to load variables from a file named .env.

Examples
Defines default app name and debug mode, but requires database_url from environment.
FastAPI
class Settings(BaseSettings):
    app_name: str = "My FastAPI App"
    debug: bool = True
    database_url: str

    class Config:
        env_file = ".env"
Creates settings instance and prints values loaded from environment or defaults.
FastAPI
settings = Settings()
print(settings.app_name)
print(settings.debug)
print(settings.database_url)
Example .env file that sets environment variables for the app.
FastAPI
# .env file content
APP_NAME=AwesomeAPI
DEBUG=False
DATABASE_URL=postgresql://user:pass@localhost/dbname
Sample Program

This FastAPI app reads settings from environment or .env file and shows them at the root URL.

FastAPI
from fastapi import FastAPI
from pydantic import BaseSettings

class Settings(BaseSettings):
    app_name: str = "FastAPI Example"
    debug: bool = False
    database_url: str

    class Config:
        env_file = ".env"

settings = Settings()

app = FastAPI()

@app.get("/")
def read_root():
    return {
        "app_name": settings.app_name,
        "debug_mode": settings.debug,
        "database_url": settings.database_url
    }
OutputSuccess
Important Notes

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

You can override environment variables by setting them directly in your system or deployment platform.

Use boolean fields carefully; environment variables are strings, so Pydantic converts them automatically.

Summary

Environment-based settings let your app change behavior without code changes.

Use Pydantic's BaseSettings and a .env file for easy setup.

Keep secrets safe and make your app flexible for different environments.