0
0
FastAPIframework~30 mins

Environment variable management in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Environment variable management
📖 Scenario: You are building a FastAPI application that needs to securely manage configuration settings like API keys and database URLs. Instead of hardcoding these values, you will use environment variables to keep your app flexible and safe.
🎯 Goal: Create a FastAPI app that reads environment variables for configuration using pydantic.BaseSettings. You will set up the environment variables, configure the settings class, use the settings in your app, and complete the app with a route that returns the config values.
📋 What You'll Learn
Create environment variables for API_KEY and DATABASE_URL
Create a Settings class inheriting from pydantic.BaseSettings to load environment variables
Instantiate the Settings class and use it in the FastAPI app
Add a GET route /config that returns the loaded environment variables
💡 Why This Matters
🌍 Real World
Managing environment variables is essential for configuring web apps securely and flexibly without hardcoding secrets or URLs.
💼 Career
Backend developers and DevOps engineers often use environment variables and configuration management to deploy and maintain applications safely.
Progress0 / 4 steps
1
Set environment variables
Create environment variables API_KEY with value mysecretkey123 and DATABASE_URL with value sqlite:///./test.db. In Python, create a FastAPI app instance called app.
FastAPI
Need a hint?

Use os.environ['VARIABLE_NAME'] = 'value' to set environment variables in Python. Then create app = FastAPI().

2
Create Settings class to load environment variables
Import BaseSettings from pydantic. Create a class called Settings that inherits from BaseSettings. Add two fields: API_KEY and DATABASE_URL both as strings.
FastAPI
Need a hint?

Define a class Settings inheriting from BaseSettings. Add two string fields named exactly API_KEY and DATABASE_URL.

3
Instantiate Settings and use in FastAPI app
Create an instance of Settings called settings. Use this instance to access environment variables in your app.
FastAPI
Need a hint?

Create a variable settings and assign it to Settings() to load environment variables.

4
Add GET route to return config values
Add a GET route /config to the app that returns a dictionary with keys api_key and database_url and their values from settings.API_KEY and settings.DATABASE_URL.
FastAPI
Need a hint?

Use @app.get('/config') decorator and define a function get_config() that returns a dictionary with keys api_key and database_url from settings.