Closed
Description
Expected Behaviour
When:
- using APIGatewayResolver, with
enable_validation=True
and, - a route's function fails to validate its return value against its return type
Expected:
- HTTP response with a server error status code (>499)
Current Behaviour
- HTTP response has a status code of 422
- despite the client payload being valid
Code snippet
from typing import Literal
from http import HTTPStatus
from aws_lambda_powertools.event_handler.api_gateway import APIGatewayRestResolver
from pydantic import BaseModel
import pytest
app = APIGatewayRestResolver(enable_validation=True)
class Todo(BaseModel):
title: str
status: Literal["Pending", "Done"]
@app.get("/non_empty_string")
def return_non_empty_string() -> Todo:
return "hello"
@app.get("/non_conforming_dict")
def return_non_conforming_dict() -> Todo:
return {"title": "fix_response_validation"}
def lambda_handler(event, context):
return app.resolve(event, context)
# --- Tests below ---
@pytest.fixture()
def event_factory():
def _factory(path: str):
return {
"httpMethod": "GET",
"path": path,
}
yield _factory
@pytest.mark.parametrize(
"path",
[
("/non_empty_string"),
("/non_conforming_dict"),
],
ids=["non_empty_string", "non_conforming_dict"],
)
def test_correct_serialization_failure(path, event_factory):
"""Tests to demonstrate cases when response serialization fails, as expected."""
event = event_factory(path)
response = lambda_handler(event, None)
assert response["statusCode"] == HTTPStatus.UNPROCESSABLE_ENTITY
if __name__ == "__main__":
pytest.main(["-v", __file__])
Possible Solution
_call_exception_handler
method of APIGatewayResolver
class returns a 422 response if RequestValidationError
is raised. Change response from 422 to a more appropriate response—possibly a 500.
Steps to Reproduce
- save snippet above to a file
- install the following dependencies
- "aws-lambda-powertools==3.4.1"
- "pydantic==2.10.5"
- "pytest==8.3.4"
- run the file
Powertools for AWS Lambda (Python) version
latest, 3.4.1
AWS Lambda function runtime
3.12
Packaging format used
PyPi
Debugging logs
Metadata
Metadata
Assignees
Labels
Type
Projects
Status
Shipped