Environment variables help keep sensitive data like passwords safe and let you change settings without changing code.
0
0
Environment variable management in FastAPI
Introduction
You want to keep API keys secret and not write them in your code.
You need to change database settings when moving from your computer to a server.
You want to set different options for development and production without changing code.
You want to avoid hardcoding passwords or tokens in your FastAPI app.
You want to easily update configuration without redeploying your app.
Syntax
FastAPI
import os value = os.getenv('VARIABLE_NAME', 'default_value')
Use
os.getenv to read environment variables safely.Provide a default value to avoid errors if the variable is missing.
Examples
Reads the
API_KEY environment variable. Returns None if not set.FastAPI
import os api_key = os.getenv('API_KEY')
Reads
PORT and converts it to an integer. Uses 8000 if PORT is not set.FastAPI
import os port = int(os.getenv('PORT', '8000'))
Uses Pydantic's
BaseSettings to automatically load environment variables into a settings object.FastAPI
from pydantic import BaseSettings class Settings(BaseSettings): database_url: str secret_key: str settings = Settings()
Sample Program
This FastAPI app reads the API_KEY environment variable when it starts. If not set, it uses 'no-key-found'. The root URL shows the API key value.
FastAPI
import os from fastapi import FastAPI app = FastAPI() API_KEY = os.getenv('API_KEY', 'no-key-found') @app.get('/') async def read_root(): return {"message": f"Your API key is: {API_KEY}"}
OutputSuccess
Important Notes
Set environment variables before running your FastAPI app, for example: export API_KEY='mysecret' on Linux/macOS or set API_KEY=mysecret on Windows.
Use python-dotenv package to load variables from a .env file during development.
Never commit secrets like API keys or passwords to your code repository.
Summary
Environment variables keep sensitive info safe and separate from code.
Use os.getenv or Pydantic BaseSettings to access them in FastAPI.
Always provide defaults or handle missing variables to avoid crashes.