Rewrite Create Expense
Exit

Rewrite Create Expense

Replace the dict and counter logic with session.add, session.commit, and session.refresh

💻

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

What the new endpoint does

The old create_expense endpoint assigned an ID manually using a counter, stored the expense in a dict, and saved everything to a file. The new version does none of that:

def create_expense(expense: Expense, session: SessionDep):
    session.add(expense)
    session.commit()
    session.refresh(expense)
    return expense

  • session.add(expense) — registers the expense with the session. The record is not written to the database yet.
  • session.commit() — writes the pending changes to the database. SQLite assigns the id at this point.
  • session.refresh(expense) — the expense object in memory still has id=None. This call reads the current state from the database — including the assigned id — back into the object.
  • return expense — the object now has a real id and is ready to serialize as the response.

The expense parameter already contains the validated input from the request body. You pass it directly to the session — no manual model_dump() or dict construction needed.

Instructions

Rewrite the create_expense endpoint to use the database session.

  1. Add session: SessionDep as a second parameter to create_expense, after expense: Expense.
  2. Replace the pass with session.add(expense) — this registers the expense with the session.
  3. Call session.commit() — this writes the expense to the database and lets SQLite assign the id.
  4. Call session.refresh(expense) — this updates the in-memory object with the id the database just assigned.
  5. Return expense.