How to use .env file in FastAPI

26 set 2023 2 min di lettura
How to use .env file in FastAPI
Indice dei contenuti

Introduction

FastAPI is a modern web framework for building APIs with Python 3.7+ based on standard Python type suggestions. Like many other frameworks, FastAPI has provisions for working with environment variables to manage configuration. Storing configurations in an.env file is a common practice that helps separate configuration from application code, making it easier to manage and more secure.

In this article we will explore how to integrate and use.env files in a FastAPI application.

Why use a.env file?

  • Separation of aspects: Keep configurations separate from application code.
  • Security: Avoid hardcoding sensitive information into source code.
  • Portability: Easily switch between different configurations based on your environment (development, testing, production, etc.).

Getting started with.env in FastAPI

Similar to other Python frameworks, FastAPI also uses the python-dotenv package to load `.env` files into the system environment. Then use them in the application.

Install the required packages:

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

pip install fastapi[all] python-dotenv uvicorn

Create a.env file:

Create a `.env` file in the root of your project. For example:

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

Read.env in FastAPI:

You can load the `.env` file at the beginning of the application. See the Python script below which uses the `load_dotenv` function from the dotenv package to load variables from the `.env` file into the system 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.

from fastapi import FastAPI
 import os
 from dotenv import load_dotenv

 app = FastAPI()

 # Load.env file
 load_dotenv()

 DB_URL = os.getenv("DB_URL")
 SECRET_KEY = os.getenv("SECRET_KEY")
 DEBUG = os.getenv("DEBUG") == "True"

Use the loaded environment variables:

Now that the variables are loaded, you can use them in your application.

@app.get("/")
 def read_root():
 return {"DB_URL": DB_URL, "Debug Mode": DEBUG}

Advanced usage

Using environments with FastAPI Config:

To further organize and type control our configurations, we can use a package like pydantic:

pip install pydantic

Next, define a configuration template:

from pydantic import BaseSettings

 class Settings(BaseSettings):
 DB_URL: str
 SECRET_KEY: str
 DEBUG: bool = False

 class Config:
 env_file = ".env"

Load configurations:

settings = Settings()

 @app.get("/config/")
 def read_config():
 return {"DB_URL": settings.DB_URL, "Debug Mode": settings.DEBUG}

With pydantic, environment variables are automatically converted to the correct types, which makes configuration management more secure.

Override configurations for testing

When writing tests, you may 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 to test:

# For testing, load a different.env file
 load_dotenv(".env.test")

Conclusion

Using an .env file in a FastAPI application simplifies configuration management, improving security and separation of concerns. With additional tools like pydantic, you can impose type checking on configurations to catch potential problems early. Whether you're developing locally, deploying to production, or running tests, leveraging.env files makes it easy to manage environment-specific settings.

Buy me a coffeeBuy me a coffee

Supportaci se ti piacciono i nostri contenuti. Grazie.

Successivamente, completa il checkout per l'accesso completo a Noviello.it.
Bentornato! Accesso eseguito correttamente.
Ti sei abbonato con successo a Noviello.it.
Successo! Il tuo account è completamente attivato, ora hai accesso a tutti i contenuti.
Operazione riuscita. Le tue informazioni di fatturazione sono state aggiornate.
La tua fatturazione non è stata aggiornata.