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 expensesession.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 theidat this point.session.refresh(expense)— theexpenseobject in memory still hasid=None. This call reads the current state from the database — including the assignedid— back into the object.return expense— the object now has a realidand 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.
- Add
session: SessionDepas a second parameter tocreate_expense, afterexpense: Expense. - Replace the
passwithsession.add(expense)— this registers the expense with the session. - Call
session.commit()— this writes the expense to the database and lets SQLite assign theid. - Call
session.refresh(expense)— this updates the in-memory object with theidthe database just assigned. - Return
expense.
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding