Skip to content

fix(event_handler): make decoded_body field optional in ApiGateway resolver #3937

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 2 commits into from
Mar 13, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
13 changes: 8 additions & 5 deletions aws_lambda_powertools/utilities/data_classes/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,13 +150,16 @@ def body(self) -> Optional[str]:
@cached_property
def json_body(self) -> Any:
"""Parses the submitted body as json"""
return self._json_deserializer(self.decoded_body)
if self.decoded_body:
return self._json_deserializer(self.decoded_body)

return None

@cached_property
def decoded_body(self) -> str:
"""Dynamically base64 decode body as a str"""
body: str = self["body"]
if self.is_base64_encoded:
def decoded_body(self) -> Optional[str]:
"""Decode the body from base64 if encoded, otherwise return it as is."""
body: Optional[str] = self.body
if self.is_base64_encoded and body:
return base64.b64decode(body.encode()).decode()
return body

Expand Down
14 changes: 0 additions & 14 deletions tests/unit/test_data_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,27 +324,13 @@ def test_base_proxy_event_get_header_value_case_insensitive():
assert value is None


def test_base_proxy_event_json_body_key_error():
event = BaseProxyEvent({})
with pytest.raises(KeyError) as ke:
assert not event.json_body
assert str(ke.value) == "'body'"


def test_base_proxy_event_json_body():
data = {"message": "Foo"}
event = BaseProxyEvent({"body": json.dumps(data)})
assert event.json_body == data
assert event.json_body["message"] == "Foo"


def test_base_proxy_event_decode_body_key_error():
event = BaseProxyEvent({})
with pytest.raises(KeyError) as ke:
assert not event.decoded_body
assert str(ke.value) == "'body'"


def test_base_proxy_event_decode_body_encoded_false():
data = "Foo"
event = BaseProxyEvent({"body": data, "isBase64Encoded": False})
Expand Down