Use Settings in Your App
Exit

Use Settings in Your App

Replace hardcoded values with settings from your configuration class

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

From hardcoded to configurable

You created a Settings class with data_file and app_title fields. Now you need to use those values instead of the hardcoded ones. Two lines in your code need to change:

  • DATA_FILE = Path("expenses.json") should read from settings.data_file
  • app = FastAPI() should use settings.app_title as the title

After this change, you can control both values through environment variables or a .env file without touching the code.

The app title in Swagger

The title parameter in FastAPI() sets the heading that appears at the top of the Swagger documentation page at /docs. Right now it shows the default "FastAPI". Setting it to a descriptive name like "Expense Tracker API" makes the documentation easier to identify.

Instructions

Replace the hardcoded values with your settings.

  1. Change DATA_FILE = Path("expenses.json") to DATA_FILE = Path(settings.data_file).
  2. Change app = FastAPI() to app = FastAPI(title=settings.app_title).