openapi-ts icon indicating copy to clipboard operation
openapi-ts copied to clipboard

Handling Error Responses in API with OpenAPI Specification

Open sagardwivedi opened this issue 1 year ago • 14 comments

Description

I wrote a login API, and when I enter the wrong password, it sends back a status code 400 along with a message. However, I know that the OpenAPI specification doesn't directly include the raise HTTPException feature. Is there a workaround for this?

Problem Details

  • Current Behavior: When a user enters the wrong password, the API responds with a status code 400 and a corresponding error message.
  • Issue: The OpenAPI specification does not inherently support the raise HTTPException used in FastAPI for error handling. This means that the error handling as implemented does not directly translate to OpenAPI documentation.

Example Code

Here is a simplified example of the current implementation:

from fastapi import FastAPI, HTTPException

app = FastAPI()

@router.post("/login/access-token")
def login_access_token(
    session: SessionDep,
    form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
) -> Token:
    """
    Get an access token for authentication.

    This endpoint authenticates a user's credentials and returns an access token
    if the credentials are valid.

    - `session`: SQLModel database session dependency.
    - `form_data`: OAuth2PasswordRequestForm object containing username and password.

    ## Returns:
    - `Token`: A Token object containing the access token and token type.

    ## Raises:
    - `HTTPException`: If the provided username or password is incorrect.
    """
    user = authenticate(
        session=session, username=form_data.username, password=form_data.password
    )
    if not user:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Incorrect email or password",
        )
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(user.user_id, access_token_expires)
    return Token(access_token=access_token, token_type="Bearer")

Desired Outcome

To have the OpenAPI documentation accurately reflect the API's behavior, including the handling of incorrect passwords and the resulting status code 400 response.

Question

Is there a workaround to properly document this behavior in the OpenAPI specification?

Reproducible example or configuration

No response

OpenAPI specification (optional)

"responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Token"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }

System information (optional)

No response

sagardwivedi avatar Jul 24 '24 16:07 sagardwivedi