Why Persistence Matters
Exit

Why Persistence Matters

Understand why in-memory data disappears and how file-based storage fixes it

The problem with in-memory storage

Right now, your expense tracker stores everything in a Python dictionary. That dictionary lives in the server's memory. Stop the server and start it again — every expense is gone.

Try it yourself: create a few expenses, then press Ctrl+C to stop the server. Run uvicorn main:app --reload again and send GET /expenses. You get an empty list. The dictionary was wiped clean when the process ended.

For a useful expense tracker, data must survive restarts.

The approach: JSON file storage

The simplest fix is to write expenses to a file after every change. When the server starts, read that file back into memory.

JSON is a good format for this because your expense data is already dictionary-shaped. Python's built-in json module converts between dictionaries and JSON strings with one function call.

The plan:

  • Save function: After every create, delete, or update, write the full expenses dictionary to a JSON file.
  • Load function: When the server starts, read the JSON file and restore the dictionary.

A note on scope

File-based storage works well for a single-user learning project. A production API serving many users at the same time would use a database like PostgreSQL or SQLite. But the concept is the same: persist data outside of memory so it outlasts the process.

In the next three chapters, you will build the save function, the load function, and wire them into your existing endpoints.

Next Chapter →