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:
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.
os
ModuleThe 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
.
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.
.env
FileDuring 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
.env
Files for Different EnvironmentsYou 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.
.env
Files: As mentioned earlier, .env
files should not be committed to version control. You can use tools like .gitignore
to ensure this.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.