Write the PATCH Endpoint
Exit

Write the PATCH Endpoint

Add a PATCH route that applies partial updates to a stored expense

💻

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

Merging changes into the stored expense

The PATCH endpoint follows the same pattern as GET and DELETE: extract the identifier from the URL, check that the expense exists, and raise a 404 if it does not.

The new part is applying the changes. The model_dump(exclude_unset=True) method returns a dictionary with only the fields the client sent. Python's dict.update() merges those key-value pairs into the stored expense:

# Client sends {"amount": 15.0}
changes = updates.model_dump(exclude_unset=True)  # {"amount": 15.0}
expenses[expense_id].update(changes)               # Only amount changes

Fields the client did not send remain untouched. The description, category, and date keep their original values.

Instructions

Add the PATCH endpoint at the bottom of the file.

  1. Add the decorator @app.patch("/expenses/{expense_id}").
  2. Define a function named update_expense with expense_id: int and updates: ExpenseUpdate as parameters.
  3. If expense_id is not in expenses, raise HTTPException(status_code=404, detail="Expense not found").
  4. Call expenses[expense_id].update(updates.model_dump(exclude_unset=True)) and return expenses[expense_id].