FastAPI is a modern web framework for building APIs with Python 3.7+ based on standard Python type hints. Like many other frameworks, FastAPI has provisions for working with environment variables to manage configuration. Storing configurations in a .env file is a common practice that helps separate configuration from the application code, making it easier to manage and more secure.
In this article, we’ll explore how to integrate and use .env files in a FastAPI application.
Why use a .env file?
- Separation of Concerns: Keep configurations separate from the application code.
- Security: Avoid hardcoding sensitive information in the source code.
- Portability: Easily switch between different configurations based on the environment (development, testing, production, etc.).
Getting Started with .env in FastAPI
Similar to other Python frameworks FastAPI also uses python-dotenv package to load `.env` files to systems environment. Then use them in the application.
1. Install required packages:
To work with `.env` files, we’ll use the python-dotenv library. Install it with pip:
pip install fastapi[all] python-dotenv uvicorn
2. Create a .env file:
Create a `.env` file in the root of your project. For example:
DB_URL=postgresql://username:password@localhost:5432/mydatabase
SECRET_KEY=mysecretkey
DEBUG=True
3. Read .env in FastAPI:
You can load the `.env` file at the start of your application. See the below Python script that uses `load_dotenv` function from the dotenv package to load the variables from the `.env` file into the system’s environment. After loading the .env file, the code retrieves specific environment variables such as “DB_URL”, “SECRET_KEY”, and “DEBUG” using the os.getenv function.
from fastapi import FastAPI
import os
from dotenv import load_dotenv
app = FastAPI()
# Load .env file
load_dotenv()
DB_URL = os.getenv("DB_URL")
SECRET_KEY = os.getenv("SECRET_KEY")
DEBUG = os.getenv("DEBUG") == "True"
4. Use the loaded environment variables:
Now that the variables are loaded, you can use them in your application.
@app.get("/")
def read_root():
return {"DB_URL": DB_URL, "Debug Mode": DEBUG}
Advanced Usage:
1. Using environments with FastAPI Config:
To further organize and type-check our configurations, we can use a package like pydantic:
pip install pydantic
Then, define a configuration model:
from pydantic import BaseSettings
class Settings(BaseSettings):
DB_URL: str
SECRET_KEY: str
DEBUG: bool = False
class Config:
env_file = ".env"
Load the configurations:
settings = Settings()
@app.get("/config/")
def read_config():
return {"DB_URL": settings.DB_URL, "Debug Mode": settings.DEBUG}
With pydantic, your environment variables are automatically cast to the correct types, which makes handling configurations safer.
2. Overriding configurations for testing:
When writing tests, you might want to use different configurations. The python-dotenv library allows you to specify a path to your .env file, so you can use a separate `.env.test` file for testing:
# For testing, load a different .env file
load_dotenv(".env.test")
Conclusion
Using a .env file in a FastAPI application streamlines configuration management, improving security and separation of concerns. With additional tools like pydantic, you can enforce type-checking on configurations to catch potential issues early. Whether you’re developing locally, deploying to production, or running tests, leveraging .env files makes managing environment-specific settings a breeze.