Rewrite Get Expense
Exit

Rewrite Get Expense

Replace the dict lookup with session.get and handle the not-found case

💻

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

Looking up a single record

The old get_expense checked whether the ID existed in the expenses dict. With a database, you use session.get():

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

session.get(Expense, expense_id) looks up a row by its primary key. It returns the matching Expense object if the row exists, or None if it does not. The if not expense: check handles the not-found case the same way as before — with a 404 response.

This is cleaner than a dict lookup: no if expense_id not in expenses: check, no expenses[expense_id] access. One call, one result.

Instructions

Rewrite the get_expense endpoint.

  1. Inside get_expense, replace pass with expense = session.get(Expense, expense_id). This looks up the expense by its unique identifier in the database.
  2. Add an if not expense: block. Inside it, raise HTTPException(status_code=404, detail="Expense not found").
  3. Return expense.