How To Use .env File in FastAPI

FastAPI is a modern web framework for building APIs with Python 3.7+ based on standard Python type hints.

In this article, we’ll learn how to integrate and use .env files in a FastAPI application.

Why should you use .env file?

  • It makes it easy to switch between different configurations based on the environment (development, testing, production, etc.).
  • it lets you avoid hard coding sensitive information in the source code.

We are going to discuss two ways of implementing .env file in FastAPI.

First method

Just as other Python frameworks, FastAPI also uses the python-dotenv package to load `.env` files into the system environment.

1. Install required packages

To use `.env` files, we’ll use the python-dotenv library. Install it with pip:

pip install fastapi python-dotenv "uvicorn[standard]"

2. Create a .env file:

Create a “.env” file in your root folder. Example

DB_URL=postgresql://username:password@localhost:5432/mydatabase
SECRET_KEY=mysecretkey

3. Read .env in FastAPI:

You can load the `.env` file at the start of your application or where ever you want to load these variables to. 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. It is also best to always add second value so that If the environment variable is not set, it returns the default value, which in this case is None

from fastapi import FastAPI
import os
from dotenv import load_dotenv

app = FastAPI()

# Load .env file
load_dotenv()

DB_URL = os.getenv("DB_URL",None)
SECRET_KEY = os.getenv("SECRET_KEY",None)

Now these loaded variables can be used anywhere in your code.

Second method:

After you are done with the step two on the previous method. We will be installing a package called pydantic which is a data validation and parsing library that simplifies the handling of request and response data by providing a declarative way to define data models with automatic validation and serialization.

pip install pydantic

Then, you can create a different file or use your “main.py” file. Define your model:

from pydantic import BaseSettings #helps you create configuration settings models for your application


class SettingsEnv(BaseSettings):
    DB_URL: str
    SECRET_KEY: str

    class Config:
        env_file = ".env" # This line tells it to look for a file called ".env" in the root directory to pull out the variables there

when you are done with this. you can then call these anywhere in your code to access either the db_url or the secret_key and any other variable you add to the .env file.

# add your import if you created a different file for this

#create and instance of your class
settings = SettingsEnv()

# You can now call it any where in the file you created
print(settings.DB_URL)

Conclusion

Using a .env file in a FastAPI application improves security and separation of concerns. So you can use any of these methods you are cool with.

White mode attracts bug

I also think so

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top