Spending Summary
Exit

Spending Summary

Build a capstone endpoint that calculates total spending per category

💻

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

The need for server-side aggregation

A client that wants to display total spending per category has two options: download every expense and sum the amounts locally, or ask the server to do the math. The first option wastes bandwidth and pushes work onto the client. The second option is a single request that returns a small dictionary.

Server-side aggregation is a common pattern in APIs. The server already has all the data in memory, so the calculation is fast. The client gets a compact result without transferring records it does not need.

How the summary works

The endpoint loops through every expense and groups the amounts by category. The result is a dictionary where each key is a category name and each value is the total amount:

{"food": 42.50, "transport": 15.00, "entertainment": 8.99}

Python's dict.get() method handles categories that appear for the first time. summary.get("food", 0) returns the current total for food, or 0 if food has not appeared yet.

Choosing the route path

The endpoint uses /summary rather than /expenses/summary. Placing it under /expenses would conflict with the {expense_id} path parameter. FastAPI would try to parse "summary" as an integer and return a validation error.

Instructions

Add a spending summary endpoint at the bottom of the file.

  1. Add the @app.get("/summary") decorator.
  2. Define a function named spending_summary that takes no arguments.
  3. Build the summary: create an empty dictionary named summary, then loop through expenses.values(). For each expense, read expense["category"] into a variable named cat. Set summary[cat] to summary.get(cat, 0) + expense["amount"].
  4. Return summary.