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 expensesession.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.
- Inside
get_expense, replacepasswithexpense = session.get(Expense, expense_id). This looks up the expense by its unique identifier in the database. - Add an
if not expense:block. Inside it, raiseHTTPException(status_code=404, detail="Expense not found"). - Return
expense.
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding