Hardcoded Settings Are a Problem
Understand why hardcoded values like file paths and app titles should live in configuration
What is hardcoded in your API
Your API has two values embedded directly in the source code:
DATA_FILE = Path("expenses.json")— the path to your data fileFastAPI()— the app title defaults to "FastAPI"
These work fine for development, but they create problems as your project grows:
- Different environments need different values. A test environment should use a separate data file so tests do not overwrite production data. If the file path is hardcoded, you cannot change it without editing the code.
- Secrets must stay out of source code. Right now your API does not use secrets like API keys or database passwords. But when it does, hardcoding them means anyone who reads the code can see them — including in version control history.
The twelve-factor approach
The twelve-factor app methodology is a set of best practices for building reliable applications. One of its core principles: store configuration in environment variables.
Environment variables are values set outside your code, in the shell or in a .env file. Your code reads them at startup. This separates what the code does (logic) from how it is configured (settings).
Pydantic Settings
Pydantic provides a BaseSettings class that reads configuration from environment variables automatically. You define a class with typed fields, and Pydantic loads the values from the environment — or from a .env file — with full validation. If a required variable is missing or has the wrong type, you get a clear error at startup, not a mysterious failure at runtime.