FastAPI is a modern tool built with Python that helps you create backend APIs. To use the latest version of FastAPI, your computer needs to have at least version 3.8 of Python installed. Like many other frameworks, FastAPI can work with environment variables, which are a great way to manage settings separately from your code. This makes your application easier to manage and more secure.
In this article, we’ll look at how to use .env files in your FastAPI application. These files are where you can store configuration settings, keeping them separate from your main application code.
Why use a .env file?
- Keep the configurations separate from the application code.
- Avoid hardcoding sensitive information in the source code.
- 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 your 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:
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.
4. Use the loaded environment variables:
Now that the variables are loaded, you can use them in your application.
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:
Load the configurations:
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:
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.