📖 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
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
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
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
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.
Practice
(1/5)
1. What is the main reason to use environment variables in a FastAPI project?
easy
A. To keep sensitive information like API keys out of the code
B. To make the code run faster
C. To store user data permanently
D. To create new API endpoints automatically
Solution
Step 1: Understand environment variables purpose
Environment variables are used to keep sensitive data like passwords or API keys separate from the code to improve security.
Step 2: Identify the correct reason in FastAPI context
FastAPI uses environment variables to avoid hardcoding secrets, which helps keep them safe and flexible.
Final Answer:
To keep sensitive information like API keys out of the code -> Option A
Quick Check:
Environment variables = keep secrets safe [OK]
Hint: Environment variables store secrets, not speed or data [OK]
Common Mistakes:
Thinking environment variables speed up code
Confusing environment variables with database storage
Assuming environment variables create API routes
2. Which of the following is the correct way to get an environment variable named API_KEY using Python's os module in FastAPI?
easy
A. api_key = os.get('API_KEY')
B. api_key = os.getenv('API_KEY')
C. api_key = os.environ.get('API_KEY')()
D. api_key = os.getenv(API_KEY)
Solution
Step 1: Recall correct os module function
The correct function to get environment variables is os.getenv('VAR_NAME').
Step 2: Check syntax correctness
api_key = os.getenv('API_KEY') uses os.getenv('API_KEY') correctly with quotes around the variable name and no extra parentheses.
Final Answer:
api_key = os.getenv('API_KEY') -> Option B
Quick Check:
Use os.getenv('VAR') to get environment variables [OK]
Hint: Use os.getenv('VAR_NAME') with quotes [OK]
Common Mistakes:
Using os.get instead of os.getenv
Calling os.environ.get with extra parentheses
Not quoting the environment variable name
3. Given this FastAPI code snippet using Pydantic's BaseSettings:
from pydantic import BaseSettings
class Settings(BaseSettings):
app_name: str
debug_mode: bool = False
settings = Settings()
If the environment variable APP_NAME is set to "MyApp" and DEBUG_MODE is not set, what will settings.app_name and settings.debug_mode be?
medium
A. None and None
B. "MyApp" and True
C. None and False
D. "MyApp" and False
Solution
Step 1: Understand BaseSettings behavior
Pydantic BaseSettings reads environment variables matching attribute names in uppercase by default.
Step 2: Check provided environment variables and defaults
APP_NAME is set to "MyApp", so settings.app_name is "MyApp". DEBUG_MODE is not set, so it uses the default False.
Final Answer:
"MyApp" and False -> Option D
Quick Check:
Env var set = value, missing uses default [OK]
Hint: Unset vars use default values in BaseSettings [OK]
Common Mistakes:
Assuming missing env vars become True
Thinking unset vars become None instead of default
Confusing attribute names with env var names
4. What is wrong with this FastAPI environment variable usage code?
import os
API_KEY = os.getenv('API_KEY')
print(f"API key is {API_KEY.upper()}")
Assuming API_KEY is not set in the environment.
medium
A. It will raise an AttributeError because API_KEY is None
B. It will print 'API key is ' with empty string
C. It will raise a SyntaxError
D. It will print the string 'None'
Solution
Step 1: Check os.getenv behavior when var missing
os.getenv returns None if the environment variable is not set and no default is given.
Step 2: Understand what happens calling upper() on None
Calling None.upper() raises an AttributeError because NoneType has no method upper().
Final Answer:
It will raise an AttributeError because API_KEY is None -> Option A
Quick Check:
None.upper() causes AttributeError [OK]
Hint: Check for None before calling string methods [OK]
Common Mistakes:
Assuming os.getenv returns empty string if missing
Expecting no error when calling upper() on None
Confusing AttributeError with SyntaxError
5. You want to manage environment variables in FastAPI using Pydantic's BaseSettings and ensure a default port of 8000 if PORT is not set. Which code snippet correctly achieves this?
hard
A. class Settings(BaseSettings):
port: int
settings = Settings(port=8000)
B. class Settings(BaseSettings):
port: int
settings = Settings() # default 8000 if missing
C. class Settings(BaseSettings):
port: int = 8000
settings = Settings()
D. class Settings(BaseSettings):
port: str = '8000'
settings = Settings()
Solution
Step 1: Define default value in BaseSettings attribute
Setting port: int = 8000 provides a default if the environment variable PORT is missing.
Step 2: Instantiate Settings without arguments
Calling Settings() reads environment variables or uses defaults if missing, so port will be 8000 if PORT is unset.
Final Answer:
class Settings(BaseSettings):
port: int = 8000
settings = Settings() -> Option C
Quick Check:
Default values in BaseSettings = default used if env var missing [OK]
Hint: Set default in class attribute for fallback [OK]
Common Mistakes:
Not providing default and expecting fallback
Passing default in constructor instead of attribute
Using string type for port instead of int
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.