In FastAPI, what does a token endpoint built on OAuth2PasswordRequestForm accept, and what must it send back?
answer
- form fields, not a JSON body
- field names fixed by the spec
- an ordinary class dependency
- two keys in the reply
- grant_type: optional, strict variant requires it
basics
~10 sOAuth2PasswordRequestForm reads form-encoded username and password fields, plus optional scope, grant_type, client_id and client_secret. The endpoint itself must return JSON with access_token and token_type set to bearer.
solid answer
~40 s`OAuth2PasswordRequestForm` is a class dependency, declared as `Annotated[OAuth2PasswordRequestForm, Depends()]`. It declares a form body, so the client posts `application/x-www-form-urlencoded` fields named exactly `username` and `password`; a JSON body gets a 422 listing both as missing. It also reads an optional `scope` string, exposed as a `scopes` list split on whitespace, an optional `grant_type` that must equal `password` when sent (`OAuth2PasswordRequestFormStrict` makes it required), and optional `client_id` and `client_secret`. Parsing forms needs FastAPI's optional form-parsing dependency, which `fastapi[standard]` installs. FastAPI does not build the reply: the path operation returns a JSON object with `access_token` and `token_type: "bearer"`, and on bad credentials raises `HTTPException` with 401 and `WWW-Authenticate: Bearer`.
code
python · 33 linesfrom typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from pydantic import BaseModel
app = FastAPI()
class Token(BaseModel):
access_token: str
token_type: str
def issue_token(username: str, password: str) -> str | None:
# Stand-in: look the user up, verify the password hash, mint a JWT.
if (username, password) == ("ana", "s3cret"):
return "signed-jwt-goes-here"
return None
@app.post("/token")
async def login(
form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
) -> Token:
access_token = issue_token(form_data.username, form_data.password)
if access_token is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
return Token(access_token=access_token, token_type="bearer")go deeper
Recall that the login request is a form post with username and password, and that the reply is JSON with access_token and token_type bearer.
Explain the optional fields, how scope becomes the scopes list, what the strict variant changes, and why a JSON body gets a 422.
Diagnose a client that cannot sign in: content type, field names, the reply keys, and whether the failure answer reveals which half of the credentials was wrong.
Treat the form contract as a public interface: every client and the docs dialog depend on its field names and reply keys, so changes to it need the same care as any API change.
## What the class is In a FastAPI app that issues its own tokens, the login endpoint (by convention `POST /token`) receives a username and a password and answers with an access token. **`OAuth2PasswordRequestForm`** is the helper FastAPI ships for the receiving half. It lives in `fastapi.security` and is an ordinary **class dependency**: its `__init__` declares `Form()` parameters, and you use it as ```python form_data: Annotated[OAuth2PasswordRequestForm, Depends()] ``` `Depends()` with no argument tells FastAPI to call the annotated class itself. The class is not a security scheme: it adds no security entry to the OpenAPI schema and no lock icon in the docs. That role belongs to `OAuth2PasswordBearer`, which protects the other endpoints. You could write the same `Form()` parameters by hand; the class exists because the OAuth2 password flow fixes the field names, so every app would write the same thing. ## The fields it reads | Form field | Required | What you get on the instance | |---|---|---| | `username` | yes | `form_data.username`, a string | | `password` | yes | `form_data.password` (documented with `format: password`) | | `scope` | no, defaults to `""` | `form_data.scopes`, the string split on whitespace | | `grant_type` | no, but must match `^password$` if sent | `form_data.grant_type`, or `None` | | `client_id` | no | `form_data.client_id`, or `None` | | `client_secret` | no | `form_data.client_secret`, or `None` | Points that trip people up: - **The names are fixed.** The field is `username` even when your users sign in with an email address; the client puts the email into `username`. Your database columns and your UI labels can say anything. - **"Permissive" means only that `grant_type` may be left out.** If a client sends `grant_type=client_credentials`, the regex still applies and FastAPI answers 422 with a `string_pattern_mismatch` error. `OAuth2PasswordRequestFormStrict` goes one step further and makes the field required, so a request without it also gets a 422. - **The instance has `scopes`, not `scope`.** The class splits the space-separated `scope` string for you; `"items:read me"` becomes `["items:read", "me"]`. - **Forms need an optional dependency.** FastAPI parses form bodies with a separate multipart package that `fastapi[standard]` installs. Without it, declaring the route raises a `RuntimeError` telling you to install that package. ## What a client must send In the worked scenario, a mobile app posts its sign-in screen to the API. The request has to be a form post: 1. Set `Content-Type: application/x-www-form-urlencoded` (a multipart form also parses). 2. Send `username=...&password=...`, optionally `scope=...`. 3. Read `access_token` from the JSON reply and send it on later calls as `Authorization: Bearer <token>`. If the app posts JSON instead, FastAPI looks for form fields, finds none, and answers **422** with two `missing` errors located at `["body", "username"]` and `["body", "password"]`. It does not fall back to reading JSON. This is the first thing to check when a front end "can't log in" against a FastAPI backend. ## What the endpoint must return FastAPI handles the request side, and the reply is yours. The password flow expects a JSON object with: - **`access_token`**: the token string, a signed JWT in the docs' full example; - **`token_type`**: `"bearer"`, telling the client how to present it. The docs declare a small `Token` model with exactly those two fields and annotate the endpoint's return type with it, so the response is filtered and documented. On a failed login, the docs' JWT version raises `HTTPException(status_code=401, detail="Incorrect username or password", headers={"WWW-Authenticate": "Bearer"})` and uses the same message whether the username or the password was wrong. (The earlier, simpler tutorial step answers 400 with the same text.) Getting the field names and these two reply keys right is what lets the **Authorize** dialog in Swagger UI work: it posts the form to the `tokenUrl` declared on `OAuth2PasswordBearer`, reads `access_token`, and sends it as a bearer header on every "Try it out" call. ## Common mistakes - Modelling the login body as a Pydantic model, which turns it into JSON and breaks every OAuth2-aware client, the docs dialog among them. - Renaming `username` to `email` in the form. - Returning only the token string, or a key such as `token`, so clients and the docs cannot find `access_token`. - Reading `form_data.scope` and getting an `AttributeError`. - Expecting the form class to check the password; it only parses fields, and checking the password is your code's job.
- Why does the Authorize dialog in FastAPI's docs work against this endpoint with no extra setup?Because `OAuth2PasswordBearer(tokenUrl="token")` declares an OAuth2 password flow in the OpenAPI schema. Swagger UI reads that flow, posts `username` and `password` as form fields to the token URL, takes `access_token` from the JSON reply and adds `Authorization: Bearer` to later calls. Rename a field, accept JSON or drop `access_token`, and the dialog stops working.
- Is OAuth2PasswordRequestForm registered as a security scheme in the generated OpenAPI schema?No. It is a plain class dependency that declares form parameters, so it only shows up as the endpoint's form body. `OAuth2PasswordBearer`, which subclasses FastAPI's security base class, is what becomes a security scheme and puts the lock icons on the operations that depend on it.
- When would you choose OAuth2PasswordRequestFormStrict over the default form class?When you want the endpoint to enforce the spec's required `grant_type=password`, for example because the same URL might later accept other grant types and you want each request to say which one it is. The strict class makes `grant_type` required, so its absence is a 422. Both classes already reject any other value with 422.
- Declaring the login body as a Pydantic model so the client posts JSON
- Renaming the username form field to email because users sign in with email
- Expecting FastAPI to build the access_token reply automatically
- Believing the non-strict form accepts any grant_type value
- Reading form_data.scope as a list instead of form_data.scopes