DEV Community

HidetoshiYanagisawa
HidetoshiYanagisawa

Posted on

Efficiently Using Environment Variables in FastAPI!

FastAPI offers a flexible and efficient way to build web applications. One of its strengths is the ease with which it integrates with external tools and libraries. In this article, we'll delve into how you can effectively use environment variables within your FastAPI applications. This is crucial for safely managing configurations, secrets, and other sensitive data. Dive in to learn the steps and grab some sample code!

Table of Contents

  1. Installing Necessary Libraries
  2. Setting Up Environment Variables
  3. Using Environment Variables in FastAPI

1. Installing Necessary Libraries

First and foremost, we'll need to install the python-dotenv library to effortlessly handle environment variables.

pip install python-dotenv
Enter fullscreen mode Exit fullscreen mode

2. Setting Up Environment Variables

Next, create a .env file in the root directory of your project. Set your environment variables within this file. For example:

DATABASE_URL=postgresql://user:password@localhost:5432/mydatabase
SECRET_KEY=mysecretkey
Enter fullscreen mode Exit fullscreen mode

Before launching your FastAPI application, add the following code to ensure the .env file's environment variables are loaded:

import os
from dotenv import load_dotenv

load_dotenv()  # Loads environment variables from .env file
Enter fullscreen mode Exit fullscreen mode

3. Using Environment Variables in FastAPI

Once the environment variables are loaded, they can be accessed and used within the FastAPI application. Use os.environ.get() to retrieve the values of these variables:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    secret_key = os.environ.get("SECRET_KEY")
    return {"Hello": "World", "Key": secret_key}
Enter fullscreen mode Exit fullscreen mode

By following these steps, you can seamlessly and securely use environment variables in your FastAPI applications.


That's it! By using environment variables in FastAPI, you ensure the security of configurations, secrets, and other sensitive data. Give it a try in your next project!

If you have questions or feedback, don't hesitate to drop a comment or give a thumbs up! 🚀🌟

Top comments (1)

Collapse
 
shravan20 profile image
Shravan Kumar B

@yanagisawahidetoshi : Good read. How would you go about handling envs for multiple environments?