Why Environment Variables Deserve More Respect
Every FastAPI developer eventually hits the same wall: your app works perfectly on your machine, but the moment you deploy it — or hand it off to a teammate — something breaks. A database connection fails. An API key is missing. A Celery worker can't find the broker URL. Nine times out of ten, the culprit is poorly managed environment variables.
In modern full-stack development, especially when you're wiring together FastAPI, Celery, Amazon S3, and Keycloak for authentication, the number of secrets and settings your application depends on grows fast. Database URLs, JWT secret keys, S3 bucket credentials, Redis connection strings, Keycloak realm configurations — each one needs to be handled differently depending on whether you're running locally, testing in staging, or serving real users in production.
This guide will show you how to build a clean, secure, and scalable environment configuration system for your FastAPI applications — the same approach used throughout the Full Stack Python Architect: FastAPI + React + Vibe Coding course, where students build production-ready applications from the ground up.
What Are Environment Variables, Really?
Environment variables are key-value pairs that live outside your codebase and are injected into your application at runtime. Instead of hardcoding sensitive values like database passwords or API keys directly into your Python files, you reference them dynamically. This separation between configuration and code is one of the core principles behind the widely respected 12-Factor App methodology.
The benefits are immediate and significant:
- Security — secrets never get committed to version control
- Flexibility — the same codebase can run in dev, staging, and production with different configurations
- Portability — new team members can spin up the project without hunting through code for hidden config values
- Compliance — sensitive data stays out of logs, commit histories, and code reviews
Setting Up python-dotenv in FastAPI
The most common tool for managing local environment variables in Python is python-dotenv. It reads key-value pairs from a .env file and loads them into your process environment, making them accessible via os.environ or, more elegantly, through Pydantic's settings management.
Step 1: Install the Dependencies
Since FastAPI already ships with Pydantic, you'll want to install pydantic-settings alongside python-dotenv:
pip install python-dotenv pydantic-settingsStep 2: Create Your .env File
At the root of your project, create a .env file. This file should never be committed to Git — more on that shortly.
# App Settings
APP_ENV=development
SECRET_KEY=your-super-secret-key
# Database
DATABASE_URL=postgresql://user:password@localhost:5432/mydb
# Celery + Redis
CELERY_BROKER_URL=redis://localhost:6379/0
CELERY_RESULT_BACKEND=redis://localhost:6379/1
# AWS S3
AWS_ACCESS_KEY_ID=your-access-key
AWS_SECRET_ACCESS_KEY=your-secret-key
AWS_S3_BUCKET_NAME=my-app-bucket
AWS_REGION=us-east-1
# Keycloak
KEYCLOAK_SERVER_URL=https://auth.example.com
KEYCLOAK_REALM=my-app-realm
KEYCLOAK_CLIENT_ID=fastapi-client
KEYCLOAK_CLIENT_SECRET=your-client-secretStep 3: Create a Centralized Settings Class
Instead of scattering os.getenv() calls across your codebase, centralize everything into a single Pydantic Settings class. This gives you type validation, IDE autocompletion, and a single source of truth.
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
app_env: str = \"development\"
secret_key: str
database_url: str
celery_broker_url: str
celery_result_backend: str
aws_access_key_id: str
aws_secret_access_key: str
aws_s3_bucket_name: str
aws_region: str = \"us-east-1\"
keycloak_server_url: str
keycloak_realm: str
keycloak_client_id: str
keycloak_client_secret: str
model_config = SettingsConfigDict(env_file=\".env\", extra=\"ignore\")
settings = Settings()Now, anywhere in your application, you can simply import settings and access strongly-typed configuration values:
from app.config import settings
engine = create_engine(settings.database_url)This pattern is one of the first things covered when students set up their FastAPI application from scratch — establishing a clean, predictable project foundation makes everything that follows, from routing to authentication, far easier to reason about.
Handling Environment Variables for Celery
Celery introduces its own configuration complexity because it runs as a separate process from your FastAPI app, yet it needs access to the same broker credentials, database connections, and often the same secret keys used for task signing.
The cleanest approach is to have your Celery app import from the same centralized settings object rather than maintaining a parallel .env parsing setup:
from celery import Celery
from app.config import settings
celery_app = Celery(
\"worker\",
broker=settings.celery_broker_url,
backend=settings.celery_result_backend,
)This ensures that whether you're running fastapi dev or starting a Celery worker with celery -A app.worker worker --loglevel=info, both processes read from an identical, validated configuration source — eliminating a whole class of \"it works in the API but not in the worker\" bugs.
Securing S3 Credentials
Amazon S3 credentials are among the most sensitive values in any application, since a leaked access key can result in unauthorized access to stored files, or worse, unexpected billing charges. A few best practices:
- Never hardcode AWS keys in your codebase, even temporarily for testing
- Use IAM roles instead of static credentials whenever you're deploying to AWS infrastructure like ECS or EC2 — this eliminates the need for access keys entirely
- When static keys are unavoidable (e.g., local development), scope the IAM user's permissions to only the specific bucket and actions needed
- Rotate credentials periodically and immediately revoke any key that may have been exposed
Your S3 client setup should always pull from your settings object:
import boto3
from app.config import settings
s3_client = boto3.client(
\"s3\",
aws_access_key_id=settings.aws_access_key_id,
aws_secret_access_key=settings.aws_secret_access_key,
region_name=settings.aws_region,
)Configuring Keycloak for Authentication
Keycloak adds another layer of environment-driven configuration since your FastAPI backend needs to know the realm, client ID, client secret, and server URL to validate tokens correctly. Because these values often differ between environments — a staging realm versus a production realm, for example — keeping them in your .env file (rather than hardcoded) is essential.
A typical token validation dependency will reference these settings directly:
from app.config import settings
KEYCLOAK_PUBLIC_KEY_URL = (
f\"{settings.keycloak_server_url}/realms/\"
f\"{settings.keycloak_realm}/protocol/openid-connect/certs\"
)This mirrors the kind of token handling and authentication flow work covered when building login systems that connect a React frontend to a FastAPI backend — the frontend stores the token, and the backend validates it against your identity provider's configuration, all driven by environment variables.
Managing Multiple Environments
Most production applications need at least three environment configurations: development, staging, and production. Rather than maintaining one bloated .env file, consider this structure:
.env.development— local development values, safe defaults.env.staging— staging server credentials.env.production— production secrets, ideally injected by your deployment platform rather than stored in a file at all
You can then load the correct file based on an APP_ENV variable set at the system level:
import os
from pydantic_settings import BaseSettings
env_file = f\".env.{os.getenv('APP_ENV', 'development')}\"
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=env_file)Best Practices for Secrets Management
Beyond basic .env usage, here are the practices that separate hobby projects from production-grade applications:
- Add .env to .gitignore immediately — before your first commit, not after a leak
- Provide a .env.example file with placeholder values so teammates know which variables are required without exposing real secrets
- Use a secrets manager in production — AWS Secrets Manager, HashiCorp Vault, or your cloud provider's native solution rather than flat files on disk
- Validate on startup — Pydantic's
BaseSettingswill raise an error immediately if a required variable is missing, catching misconfigurations before they cause runtime failures - Never log environment variables, even in debug mode
- Limit access to production environment variables to only the people and systems that absolutely need them
Featured Video
[Video embed placeholder: Watch the full walkthrough of setting up environment variables, project structure, and configuration best practices for a FastAPI + React application.]
Bringing It All Together
Environment configuration might seem like a small detail compared to designing APIs or building React components, but it's one of the areas where sloppy habits cause the most real-world pain — leaked credentials, broken deployments, and hours lost debugging \"works on my machine\" issues. A well-structured .env setup, backed by a centralized Pydantic settings class, gives your entire stack — FastAPI, Celery, S3, and Keycloak — a single, validated, secure source of configuration truth.
This kind of architectural discipline is exactly what's emphasized throughout the Full Stack Python Architect: FastAPI + React + Vibe Coding course, where clean project structure and configuration management are treated as first-class citizens from the very first lecture, not an afterthought bolted on before deployment.
Key Takeaways
- Separate configuration from code using
.envfiles and never commit secrets to version control - Centralize environment variables into a single, validated Pydantic
Settingsclass - Share configuration consistently between FastAPI and Celery to avoid mismatched settings
- Protect S3 and Keycloak credentials with scoped permissions and environment-specific values
- Use dedicated secrets managers in production rather than relying solely on flat files
If you're ready to go deeper — building out full authentication flows, background task processing with Celery, file storage with S3, and a polished React frontend all connected to a properly configured FastAPI backend — the full course walks through every one of these integrations step by step, with real, portfolio-ready projects along the way.