Get Expense by ID

Add an endpoint that retrieves a single expense using a path parameter

💻

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

Why you need a single-expense endpoint

The GET /expenses endpoint returns every expense in the tracker. That works for displaying a full list, but a client often needs just one record. For example, a details screen needs to fetch a specific expense, or a confirmation dialog needs to show what the user is about to delete.

The path parameter {expense_id} captures the identifier from the URL. FastAPI converts it to the declared type (int) automatically. If the identifier does not match any stored expense, you raise an HTTPException with status code 404.

Note: the import line changes in this chapter. HTTPException is added to the fastapi import.

Instructions

  1. Add the @app.get("/expenses/{expense_id}") decorator.
  2. Define a function named get_expense with an expense_id parameter of type int.
  3. If expense_id is not in expenses, raise HTTPException(status_code=404, detail="Expense not found").
  4. Return expenses[expense_id].