OAuth2PasswordRequestForm
OAuth2PasswordRequestForm
What is OAuth2PasswordRequestForm in FastAPI
In short
It’s a dependency class that parses and validates a login form sent with these fields:
usernamepassword- (optional)
scope - (optional)
grant_type - (optional)
client_id - (optional)
client_secret
Where it comes from
You import it from FastAPI’s security module:
from fastapi.security import OAuth2PasswordRequestFormIt’s typically used with FastAPI’s dependency injection in a login endpoint:
from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordRequestForm
app = FastAPI()
@app.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
# You can now access form_data.username and form_data.password
user_dict = {"username": form_data.username}
# verify username & password here...
return {"access_token": user_dict["username"], "token_type": "bearer"}Example of expected request
The client must send the data as application/x-www-form-urlencoded, not JSON:
POST /token
Content-Type: application/x-www-form-urlencoded
grant_type=password&username=johndoe&password=secretWhy it’s useful
- Automatically reads and validates form data.
- Matches the OAuth2 “Resource Owner Password Credentials” grant specification.
- Works seamlessly with FastAPI’s OAuth2 and security utilities.