Bird
Raised Fist0
FastAPIframework~20 mins

Environment variable management in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Environment Variable Mastery in FastAPI
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
How does FastAPI load environment variables with Pydantic BaseSettings?
Given this FastAPI settings class using Pydantic's BaseSettings, what will be the value of settings.api_key if the environment variable API_KEY is set to secret123?
FastAPI
from pydantic import BaseSettings

class Settings(BaseSettings):
    api_key: str

settings = Settings()
A"api_key"
B"secret123"
CRaises a ValidationError because no default is set
D"" (empty string)
Attempts:
2 left
💡 Hint
Pydantic BaseSettings automatically reads environment variables matching attribute names in uppercase.
📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this FastAPI environment variable loading code
Which option contains the correct way to define a Pydantic BaseSettings class to load an environment variable DATABASE_URL?
FastAPI
from pydantic import BaseSettings

class Settings(BaseSettings):
    database_url: str

settings = Settings()
A
class Settings(BaseSettings):
    database_url: str

settings = Settings()
B
class Settings(BaseSettings):
    database_url = str

settings = Settings()
C
class Settings(BaseSettings):
    database_url: str = None

settings = Settings()
D
class Settings(BaseSettings):
    database_url: str

settings = Settings
Attempts:
2 left
💡 Hint
Check how type annotations and instantiation are done.
❓ state_output
advanced
2:00remaining
What is the output when environment variable is missing and no default is set?
Consider this FastAPI settings class. What happens when you run settings = Settings() but the environment variable SECRET_KEY is not set?
FastAPI
from pydantic import BaseSettings

class Settings(BaseSettings):
    secret_key: str

settings = Settings()
Asettings.secret_key is set to 'secret_key'
Bsettings.secret_key is set to an empty string
Csettings.secret_key is set to None
DRaises pydantic.ValidationError because secret_key is required but missing
Attempts:
2 left
💡 Hint
Required fields without defaults must be provided by environment or raise error.
🔧 Debug
advanced
2:00remaining
Why does this FastAPI app fail to read environment variables correctly?
This FastAPI app uses Pydantic BaseSettings but always returns default values instead of environment variables. What is the likely cause?
FastAPI
from fastapi import FastAPI
from pydantic import BaseSettings

class Settings(BaseSettings):
    app_name: str = "MyApp"

settings = Settings()

app = FastAPI()

@app.get("/")
def read_root():
    return {"app_name": settings.app_name}
AThe app_name field must be Optional[str] to read environment variables
BBaseSettings does not support environment variables by default
CEnvironment variables are not loaded because the .env file is missing or not in the working directory
DFastAPI requires special middleware to read environment variables
Attempts:
2 left
💡 Hint
Check if environment variables are actually available to the app process.
🧠 Conceptual
expert
3:00remaining
How does Pydantic BaseSettings prioritize environment variables and defaults?
Given a Pydantic BaseSettings class with a field timeout: int = 30, and an environment variable TIMEOUT=60 set, what will be the value of settings.timeout after instantiation?
FastAPI
from pydantic import BaseSettings

class Settings(BaseSettings):
    timeout: int = 30

settings = Settings()
A60, because environment variables override default values
B30, because default values always take precedence over environment variables
CNone, because the environment variable is ignored
DRaises ValidationError because environment variables cannot override defaults
Attempts:
2 left
💡 Hint
Think about how BaseSettings merges environment variables with defaults.

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

  1. 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.
  2. Step 2: Identify the correct reason in FastAPI context

    FastAPI uses environment variables to avoid hardcoding secrets, which helps keep them safe and flexible.
  3. Final Answer:

    To keep sensitive information like API keys out of the code -> Option A
  4. 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

  1. Step 1: Recall correct os module function

    The correct function to get environment variables is os.getenv('VAR_NAME').
  2. 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.
  3. Final Answer:

    api_key = os.getenv('API_KEY') -> Option B
  4. 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

  1. Step 1: Understand BaseSettings behavior

    Pydantic BaseSettings reads environment variables matching attribute names in uppercase by default.
  2. 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.
  3. Final Answer:

    "MyApp" and False -> Option D
  4. 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

  1. 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.
  2. Step 2: Understand what happens calling upper() on None

    Calling None.upper() raises an AttributeError because NoneType has no method upper().
  3. Final Answer:

    It will raise an AttributeError because API_KEY is None -> Option A
  4. 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

  1. Step 1: Define default value in BaseSettings attribute

    Setting port: int = 8000 provides a default if the environment variable PORT is missing.
  2. 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.
  3. Final Answer:

    class Settings(BaseSettings): port: int = 8000 settings = Settings() -> Option C
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard