Delete Expense by ID
Exit

Delete Expense by ID

Add an endpoint that removes an expense from the tracker

💻

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 delete endpoint

Users make mistakes. Someone logs an expense twice or enters the wrong amount. Without a delete endpoint, bad data stays in the tracker permanently.

The HTTP DELETE method signals that the client wants to remove a resource. You use the same {expense_id} path parameter to identify which expense to remove. Python's dict.pop() method removes a key from the dictionary and returns its value in one step. This lets you return the deleted expense so the client can confirm what was removed.

The error handling follows the same pattern as the get endpoint. If the identifier does not match any stored expense, you raise an HTTPException with status code 404.

Instructions

  1. Add the @app.delete("/expenses/{expense_id}") decorator.
  2. Define a function named delete_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.pop(expense_id).