Skip to content
tezvyn:

How do you protect a FastAPI endpoint using Depends and OAuth2PasswordBearer?

Source: fastapi.tiangolo.comEasyHow cards are made

How do you protect a FastAPI endpoint using Depends and OAuth2PasswordBearer?
Summary

your grasp of FastAPI dependency injection for security.

Key points

OAuth2PasswordBearer sets the token URL, Depends injects it into the endpoint, and FastAPI validates the Bearer header.

What's really being asked

This question checks whether you know how FastAPI handles authentication through its dependency injection system rather than manual header parsing. The interviewer wants to see that you understand the separation between declaring a security scheme, injecting it into an endpoint, and letting the framework enforce validation and documentation automatically. At the senior level, they also care that you recognize why using built-in primitives reduces boilerplate and standardizes behavior across endpoints.

The full answer

First, explain that you instantiate OAuth2PasswordBearer and pass a tokenUrl parameter that tells the client where to send the username and password to receive a token. Second, describe how you use Depends to inject that security scheme instance into the path operation function, which makes the endpoint require authentication. Third, note that FastAPI automatically expects an Authorization header with a Bearer token, returns a 401 Unauthorized response when it is missing, and adds the lock icon and security requirements to the auto-generated OpenAPI documentation. Fourth, mention that the tokenUrl is relative and used by the interactive docs so the frontend knows where to authenticate.

The mistakes people make

A red flag is saying you would manually inspect the request headers inside the endpoint function or write custom middleware to check for an Authorization header. Another mistake is confusing OAuth2PasswordBearer with the actual token creation logic; it is only a declaration of the security scheme and does not verify usernames or passwords itself. Also, omitting the role of Depends suggests you do not understand FastAPI's dependency injection system. Finally, claiming that OAuth2PasswordBearer hashes passwords or issues JWTs reveals a fundamental misunderstanding of its purpose.

What usually comes next

The interviewer may ask how you would actually verify the token and load the current user, which leads to creating a dependency that decodes the token and queries a database. They might also ask about OAuth2 scopes for permission granularity, how to hash passwords with passlib, or how to make an endpoint optionally authenticated rather than strictly required. You should be ready to explain the difference between the security scheme declaration and the user retrieval dependency.

A concrete example

At the module level you create an instance of OAuth2PasswordBearer and pass tokenUrl set to the path where clients swap credentials for tokens, such as slash token. Then in your endpoint signature you declare a parameter with the Depends wrapper around that scheme instance. When a request arrives without an Authorization header containing a Bearer token, FastAPI automatically returns a 401 Unauthorized response and includes the appropriate WWW-Authenticate header. When the header is present, the token string is injected into your function parameter and you can proceed to validate it. The interactive Swagger UI will also show a lock icon on that endpoint and use the tokenUrl to let users log in and test protected routes.

Interview question

What does FastAPI automatically do when you inject an OAuth2PasswordBearer instance into an endpoint using Depends?

  • a.Require manual inspection of request.headers inside the endpoint to find the Bearer token
  • b.Hash incoming passwords and generate JWTs using the configured tokenUrl
  • c.Expect a Bearer token in the Authorization header, return 401 if absent, and add security metadata to OpenAPI docsCorrect
  • d.Verify the token against a database and inject the current user into the endpoint function
Why?

Injecting OAuth2PasswordBearer via Depends tells FastAPI to require an Authorization: Bearer header, automatically return 401 if it is missing, and document the requirement in OpenAPI. Option D is tempting but wrong because the scheme itself does not query a database or return a user object; that requires a separate custom dependency.

Just read this? Test yourself on what you have been reading.

Read the original → fastapi.tiangolo.com

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on fastapi — each one lists the topics its interview covers.

See open roles