RequestValidationError thrown in OAuth2PasswordRequestForm can't be parsed by Swagger UI #12166
-
First Check
Commit to Help
Example Codefrom fastapi import FasAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
app = FastAPI()
correct_user = "placeholder"
correct_pwd = "placeholder"
@app.post("/token")
async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):
if not form_data.username != correct_user or not form_data.password != correct_pwd:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username or password", headers={"WWW-Authenticate": "Bearer"})
return {"message": "whatever"}DescriptionWhen using The problem is that Swagger UI cannot consume this, resulting in the following:
One could argue this is a Swagger UI issue, but should an empty username or password really raise a RequestValidationError? This is an auth issue and should be handled in the auth layer of the app. So it's not really a validation issue. Besides, nothing in the example above is custom behavior. Fastapi works like this out of the box, and it feels weird that the default, out-of-the-box behavior of the fastapi+swagger integration doesn't work quite well. What do you think? Operating SystemLinux, Windows Operating System DetailsNo response FastAPI Version0.112.2 Pydantic Version2.8.2 Python Version3.12.5 Additional ContextHere's the SO question for more details: https://stackoverflow.com/questions/78960147/objects-in-error-response-cant-be-parsed-by-swagger-ui |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I disagree here. Authorization issue is when you are trying to access protected endpoint without providing appropriate token. Then you should (and will) have 401 or 403 response. I think everything works correctly here. The only thing that might be improved here is that Swagger could show clearer error message instead of |
Beta Was this translation helpful? Give feedback.

I disagree here. Authorization issue is when you are trying to access protected endpoint without providing appropriate token. Then you should (and will) have 401 or 403 response.
But not providing login or password to
loginendpoint should cause request validation error.I think everything works correctly here. The only thing that might be improved here is that Swagger could show clearer error message instead of
Error: Unprocessable Entity(i'm talking a…