Wire Up Save and Load
Exit

Wire Up Save and Load

Call load on startup and save after every change to persist expenses

💻

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

Two connections to make

You have a save_expenses function and a load_expenses function, but neither one runs yet. You need to connect them to the rest of your code in two places:

  • Load on startup: Call load_expenses() right after the default values are set. This restores saved data when the server starts. If no file exists, the function does nothing and the defaults stay in place.
  • Save after changes: Call save_expenses() inside every endpoint that modifies data. That means create_expense, delete_expense, and update_expense. The list_expenses and get_expense endpoints only read data, so they do not need a save call.

After this chapter, you can stop the server, restart it, and see all your expenses still there.

Instructions

Wire the save and load functions into the existing code.

  1. Add load_expenses() on the line after counter = 0. This runs once when the server starts.
  2. In create_expense, add save_expenses() after the line that stores the expense in the dictionary, before the return statement.
  3. In delete_expense, add save_expenses() after the 404 check, before the return statement.
  4. In update_expense, add save_expenses() after the line that applies the updates, before the return statement.