Setting Up Environment Variables in FastAPI
FastAPI is a modern, fast (high-performance) web framework for building APIs with Python based on standard Python type hints. When developing applications with FastAPI, it’s crucial to manage sensitive information, configuration settings, and other parameters effectively. This is where environment variables come into play. Environment variables allow you to store and access configuration data outside of your codebase, making your application more secure, flexible, and easier to deploy across different environments. In this blog post, we’ll explore the fundamental concepts of setting up environment variables in FastAPI, discuss usage methods, common practices, and best practices.
Table of Contents
- Fundamental Concepts of Environment Variables
- Usage Methods in FastAPI
- Common Practices
- Best Practices
- Conclusion
- References
Fundamental Concepts of Environment Variables
Environment variables are dynamic values that can affect the way running processes will behave on a computer. They are part of the environment in which a process runs. In the context of a FastAPI application, environment variables can be used to store various types of information, such as:
- API Keys: For third - party services like databases, email providers, or cloud storage.
- Database Connection Strings: To connect to different databases in development, testing, and production environments.
- Debug Mode Flags: To enable or disable debug mode in different environments.
The advantage of using environment variables is that you can change the configuration of your application without modifying the source code. This is especially useful when deploying your application to different environments, such as development, staging, and production.
Usage Methods in FastAPI
Using the os Module
The simplest way to access environment variables in Python (and thus in FastAPI) is by using the os module. Here is a basic example:
import os
from fastapi import FastAPI
app = FastAPI()
# Get an environment variable
database_url = os.getenv('DATABASE_URL', 'sqlite:///./test.db')
@app.get("/")
def read_root():
return {"Database URL": database_url}
In this example, we first import the os module. Then we use the os.getenv function to retrieve the DATABASE_URL environment variable. If the variable is not set, we provide a default value of sqlite:///./test.db.
Using pydantic’s BaseSettings
FastAPI often works well with pydantic for data validation. pydantic provides a BaseSettings class that can be used to manage environment variables in a more structured way.
from fastapi import FastAPI
from pydantic import BaseSettings
class Settings(BaseSettings):
database_url: str = 'sqlite:///./test.db'
api_key: str
class Config:
env_file = ".env"
settings = Settings()
app = FastAPI()
@app.get("/")
def read_root():
return {"Database URL": settings.database_url, "API Key": settings.api_key}
In this example, we define a Settings class that inherits from BaseSettings. We define the environment variables as class attributes with their types. The Config subclass specifies the name of the .env file where the environment variables are stored.
Common Practices
Storing Environment Variables in a .env File
During development, it’s common to store environment variables in a .env file. This file is not committed to version control (usually added to .gitignore) to keep sensitive information secure.
Here is an example of a .env file:
DATABASE_URL=postgresql://user:password@localhost/mydb
API_KEY=1234567890
Using Different .env Files for Different Environments
You can create different .env files for development, testing, and production. For example, you might have .env.development, .env.testing, and .env.production. Then, you can set the appropriate file to be loaded based on the environment.
Best Practices
Security
- Never Hardcode Sensitive Information: Sensitive information like API keys, database passwords, etc., should always be stored as environment variables.
- Protect
.envFiles: As mentioned earlier,.envfiles should not be committed to version control. You can use tools like.gitignoreto ensure this.
Error Handling
- Provide Default Values: When retrieving environment variables, always provide default values if possible. This ensures that your application can still run even if a variable is not set.
Documentation
- Document Environment Variables: Clearly document what each environment variable is used for in your application. This will make it easier for other developers to understand and maintain the code.
Conclusion
Setting up environment variables in FastAPI is an essential part of building secure, flexible, and maintainable applications. By using environment variables, you can separate configuration from code, making it easier to deploy your application across different environments. Whether you choose to use the os module or pydantic’s BaseSettings, the key is to follow best practices to ensure the security and reliability of your application.