Skip to content

fix(event_handler): serialize pydantic/dataclasses in exception handler #3455

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion aws_lambda_powertools/event_handler/api_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -709,7 +709,7 @@ class ResponseBuilder(Generic[ResponseEventT]):
def __init__(
self,
response: Response,
serializer: Callable[[Any], str] = json.dumps,
serializer: Callable[[Any], str] = partial(json.dumps, separators=(",", ":"), cls=Encoder),
route: Optional[Route] = None,
):
self.response = response
Expand Down
18 changes: 16 additions & 2 deletions aws_lambda_powertools/shared/json_encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,27 @@


class Encoder(json.JSONEncoder):
"""
Custom JSON encoder to allow for serialization of Decimals, similar to the serializer used by Lambda internally.
"""Custom JSON encoder to allow for serialization of Decimals, Pydantic and Dataclasses.

It's similar to the serializer used by Lambda internally.
"""

def default(self, obj):
if isinstance(obj, decimal.Decimal):
if obj.is_nan():
return math.nan
return str(obj)

# Pydantic model (v1/v2)
if hasattr(obj, "json"):
from aws_lambda_powertools.event_handler.openapi.compat import _model_dump

return _model_dump(obj)

# Standard dataclass
if hasattr(obj, "__dataclass_fields__"):
import dataclasses

return dataclasses.asdict(obj)

return super().default(obj)
30 changes: 29 additions & 1 deletion tests/functional/event_handler/test_api_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from typing import Dict

import pytest
from pydantic import BaseModel

from aws_lambda_powertools.event_handler import content_types
from aws_lambda_powertools.event_handler.api_gateway import (
Expand Down Expand Up @@ -1465,7 +1466,6 @@ def test_exception_handler_with_data_validation():

@app.exception_handler(RequestValidationError)
def handle_validation_error(ex: RequestValidationError):
print(f"request path is '{app.current_event.path}'")
return Response(
status_code=422,
content_type=content_types.TEXT_PLAIN,
Expand All @@ -1486,6 +1486,34 @@ def get_lambda(param: int):
assert result["body"] == "Invalid data. Number of errors: 1"


def test_exception_handler_with_data_validation_pydantic_response():
# GIVEN a resolver with an exception handler defined for RequestValidationError
app = ApiGatewayResolver(enable_validation=True)

class Err(BaseModel):
msg: str

@app.exception_handler(RequestValidationError)
def handle_validation_error(ex: RequestValidationError):
return Response(
status_code=422,
content_type=content_types.APPLICATION_JSON,
body=Err(msg=f"Invalid data. Number of errors: {len(ex.errors())}"),
)

@app.get("/my/path")
def get_lambda(param: int):
...

# WHEN calling the event handler
# AND a RequestValidationError is raised
result = app(LOAD_GW_EVENT, {})

# THEN exception handler's pydantic response should be serialized correctly
assert result["statusCode"] == 422
assert result["body"] == '{"msg":"Invalid data. Number of errors: 1"}'


def test_data_validation_error():
# GIVEN a resolver without an exception handler
app = ApiGatewayResolver(enable_validation=True)
Expand Down
34 changes: 34 additions & 0 deletions tests/unit/test_json_encoder.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import decimal
import json
from dataclasses import dataclass

import pytest
from pydantic import BaseModel

from aws_lambda_powertools.shared.json_encoder import Encoder

Expand All @@ -22,3 +24,35 @@ class CustomClass:

with pytest.raises(TypeError):
json.dumps({"val": CustomClass()}, cls=Encoder)


def test_json_encode_pydantic():
# GIVEN a Pydantic model
class Model(BaseModel):
data: dict

data = {"msg": "hello"}
model = Model(data=data)

# WHEN json.dumps use our custom Encoder
result = json.dumps(model, cls=Encoder)

# THEN we should serialize successfully; not raise a TypeError
assert result == json.dumps({"data": data}, cls=Encoder)


def test_json_encode_dataclasses():
# GIVEN a standard dataclass

@dataclass
class Model:
data: dict

data = {"msg": "hello"}
model = Model(data=data)

# WHEN json.dumps use our custom Encoder
result = json.dumps(model, cls=Encoder)

# THEN we should serialize successfully; not raise a TypeError
assert result == json.dumps({"data": data}, cls=Encoder)