Rewrite Delete Expense
Exit

Rewrite Delete Expense

Replace dict.pop with session.delete and session.commit

💻

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

Deleting a record

Deleting from a database follows the same lookup-then-act pattern as get:

expense = session.get(Expense, expense_id)
if not expense:
    raise HTTPException(status_code=404, detail="Expense not found")
session.delete(expense)
session.commit()
return expense

Notice that you return expense after deleting it. You loaded the object before the delete, so you still have it in memory and can include it in the response. The old code did the same thing — expenses.pop(expense_id) removed the item from the dict and returned its value in one step. Here you do it in two steps, but the result is the same.

session.commit() is required after session.delete(). Without it, the delete is pending but never written to the database.

Instructions

Rewrite the delete_expense endpoint.

  1. Inside delete_expense, replace pass with expense = session.get(Expense, expense_id).
  2. Add an if not expense: block. Inside it, raise HTTPException(status_code=404, detail="Expense not found").
  3. Call session.delete(expense).
  4. Call session.commit().
  5. Return expense.