One Small Change, Big Impact
Exit

One Small Change, Big Impact

Learn how FastAPI dependencies act as gatekeepers for your endpoints

The problem: every endpoint is wide open

Your API has registration and login, but the expense endpoints ignore authentication completely. Anyone can create, read, update, or delete any expense without a token. The auth module you built in Lesson 1 is not connected to the expense endpoints yet.

Dependencies as gatekeepers

FastAPI runs dependency functions before your endpoint code executes. You already use one dependency: SessionDep gives every endpoint a database session. Adding get_current_user as a dependency works the same way. FastAPI calls get_current_user first, and if it raises a 401 error, your endpoint code never runs. One parameter addition locks down an entire endpoint.

Two changes to make

Protecting the endpoints requires two things:

  • Link expenses to users: add a user_id field to the Expense model so every expense records who created it
  • Add the current user to every endpoint: pass get_current_user as a dependency parameter so FastAPI enforces authentication and you can filter data by user

The next chapter adds user_id to the model. Then you will protect each endpoint one by one, starting with create_expense.

Next Chapter →