How to Use Environment Variables in FastAPI for Configuration
In FastAPI, you can use environment variables by reading them with Python's
os.getenv() or by using the pydantic.BaseSettings class for structured settings. This allows you to keep sensitive data like API keys outside your code and configure your app easily.Syntax
There are two common ways to use environment variables in FastAPI:
- Using
os.getenv(): Directly fetch environment variables as strings. - Using
pydantic.BaseSettings: Define a settings class that automatically reads environment variables and validates types.
This helps keep configuration clean and secure.
python
import os from pydantic import BaseSettings # Using os.getenv() api_key = os.getenv('API_KEY', 'default_key') # Using pydantic BaseSettings class Settings(BaseSettings): api_key: str debug: bool = False class Config: env_file = '.env' settings = Settings()
Example
This example shows how to create a FastAPI app that reads an API key from environment variables using pydantic.BaseSettings. It also demonstrates how to use a .env file for local development.
python
from fastapi import FastAPI, HTTPException from pydantic import BaseSettings class Settings(BaseSettings): api_key: str debug: bool = False class Config: env_file = '.env' settings = Settings() app = FastAPI() @app.get('/secure-data') async def secure_data(key: str): if key != settings.api_key: raise HTTPException(status_code=401, detail='Unauthorized') return {'message': 'Access granted', 'debug_mode': settings.debug} # To run: # 1. Create a .env file with API_KEY=your_secret_key # 2. Run uvicorn main:app --reload
Output
When you call /secure-data?key=your_secret_key, it returns {"message": "Access granted", "debug_mode": false} if the key matches the environment variable.
Common Pitfalls
Common mistakes when using environment variables in FastAPI include:
- Not setting environment variables before running the app, causing
Noneor default values. - Forgetting to load a
.envfile in development. - Using
os.environ['VAR']without a fallback, which raises errors if the variable is missing. - Not validating types, leading to unexpected bugs.
Always provide defaults or validate with pydantic.BaseSettings.
python
import os # Wrong way: raises KeyError if API_KEY is missing # api_key = os.environ['API_KEY'] # Right way: returns None or default if missing api_key = os.getenv('API_KEY', 'default_key') # Better: use pydantic BaseSettings for validation and defaults from pydantic import BaseSettings class Settings(BaseSettings): api_key: str # required debug: bool = False settings = Settings()
Quick Reference
Tips for using environment variables in FastAPI:
- Use
pydantic.BaseSettingsfor structured, validated config. - Store secrets in environment variables or
.envfiles, never in code. - Use
env_fileinConfigto load.envautomatically. - Always provide defaults or mark fields as required.
- Use
uvicornto run your app with environment variables set.
Key Takeaways
Use pydantic.BaseSettings to read and validate environment variables in FastAPI.
Never hardcode secrets; keep them in environment variables or .env files.
Always provide defaults or mark variables as required to avoid runtime errors.
Use .env files with env_file config for easy local development.
Use os.getenv() with a default if you need quick access without validation.