0Pricing
FastAPI Backend Development Bootcamp · Lesson

Managing Environment Variables and Secrets

Learn to configure FastAPI for different environments safely using environment variables and secret management.

Managing Environment Variables and Secrets is a free FastAPI Backend Development Bootcamp lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the FastAPI Backend Development Bootcamp learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Externalize Configuration?

Hardcoding database URLs, API keys, or debug flags into your code is dangerous and inflexible.

The 12-factor app approach stores configuration in the environment, so the same image runs in dev, staging, and production with different settings.

Reading Environment Variables

Python reads variables via os.environ or os.getenv with a default.

import os

DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./dev.db")
DEBUG = os.getenv("DEBUG", "false").lower() == "true"

Pydantic Settings

FastAPI projects commonly use pydantic-settings to load and validate config into a typed object.

from pydantic_settings import BaseSettings

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

Loading from a .env File

Configure the settings class to read a local .env file during development.

class Settings(BaseSettings):
    database_url: str
    secret_key: str

    class Config:
        env_file = ".env"

Caching the Settings Object

Use lru_cache so settings are parsed once and reused as a dependency.

from functools import lru_cache

@lru_cache
def get_settings() -> Settings:
    return Settings()

Injecting Settings into Routes

Treat settings as a FastAPI dependency for clean access and easy testing.

from fastapi import Depends

@app.get("/info")
def info(settings: Settings = Depends(get_settings)):
    return {"debug": settings.debug}

Never Commit Secrets

Add .env to .gitignore. Committed secrets are extremely hard to fully remove from git history and may leak credentials.

# .gitignore
.env
*.pem
secrets/

Production Secret Stores

In production, prefer a managed secret store over plain files:

  • AWS Secrets Manager or Parameter Store
  • HashiCorp Vault
  • Docker or Kubernetes secrets

These inject secrets at runtime without writing them to disk in plain text.

Different Configs per Environment

Use a single variable like ENV to branch behavior, keeping all values in the environment.

ENV = os.getenv("ENV", "development")
if ENV == "production":
    LOG_LEVEL = "warning"
else:
    LOG_LEVEL = "debug"

Validating Required Variables

Pydantic settings raise a clear error at startup if a required variable is missing, failing fast instead of crashing later.

try:
    settings = Settings()
except Exception as e:
    print("Config error:", e)
    raise

Typed Lists and Nested Config

Settings can parse complex values too, like comma-separated origins into a list, keeping parsing logic out of your routes.

class Settings(BaseSettings):
    cors_origins: list[str] = []

# CORS_ORIGINS=https://a.com,https://b.com

Quick Check

Test your configuration knowledge.

Recap

You learned to manage configuration safely:

  • Read config from the environment, not source code
  • Use pydantic-settings for typed, validated config
  • Never commit .env; use a secret store in production

Solid config management keeps deployments portable and secure.

Frequently asked questions

Is the “Managing Environment Variables and Secrets” lesson free?

Yes — the full text of “Managing Environment Variables and Secrets” is free to read here on the web, and the FastAPI Backend Development Bootcamp course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the FastAPI Backend Development Bootcamp course, upgrade to CoddyKit PRO.

What will I learn in “Managing Environment Variables and Secrets”?

Learn to configure FastAPI for different environments safely using environment variables and secret management. You practise FastAPI Backend Development Bootcamp with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start FastAPI Backend Development Bootcamp?

No prior experience is required. FastAPI Backend Development Bootcamp on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Managing Environment Variables and Secrets” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this FastAPI Backend Development Bootcamp lesson?

Yes. Every FastAPI Backend Development Bootcamp lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Dockerizing FastAPI Applications
  2. Deploying with Gunicorn & Uvicorn
  3. Cloud Deployment Strategies
  4. Managing Environment Variables and Secrets
← Back to FastAPI Backend Development Bootcamp