diff --git a/aws_lambda_powertools/shared/headers_serializer.py b/aws_lambda_powertools/shared/headers_serializer.py index 796fd9aeae3..b4e9f7c7c5f 100644 --- a/aws_lambda_powertools/shared/headers_serializer.py +++ b/aws_lambda_powertools/shared/headers_serializer.py @@ -41,6 +41,10 @@ def serialize(self, headers: Dict[str, Union[str, List[str]]], cookies: List[Coo # Duplicate headers are combined with commas and included in the headers field. combined_headers: Dict[str, str] = {} for key, values in headers.items(): + # omit headers with explicit null values + if values is None: + continue + if isinstance(values, str): combined_headers[key] = values else: @@ -60,13 +64,15 @@ def serialize(self, headers: Dict[str, Union[str, List[str]]], cookies: List[Coo https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html#multi-value-headers-response """ payload: Dict[str, List[str]] = defaultdict(list) - for key, values in headers.items(): + # omit headers with explicit null values + if values is None: + continue + if isinstance(values, str): payload[key].append(values) else: - for value in values: - payload[key].append(value) + payload[key].extend(values) if cookies: payload.setdefault("Set-Cookie", []) @@ -98,6 +104,10 @@ def serialize(self, headers: Dict[str, Union[str, List[str]]], cookies: List[Coo payload["headers"]["Set-Cookie"] = str(cookies[-1]) for key, values in headers.items(): + # omit headers with explicit null values + if values is None: + continue + if isinstance(values, str): payload["headers"][key] = values else: diff --git a/tests/functional/test_headers_serializer.py b/tests/functional/test_headers_serializer.py index 8a27ce8baa8..204df5ad614 100644 --- a/tests/functional/test_headers_serializer.py +++ b/tests/functional/test_headers_serializer.py @@ -145,3 +145,21 @@ def test_single_value_headers_with_multiple_header_values_warning(): payload = serializer.serialize(cookies=[], headers=headers) assert payload["headers"]["Foo"] == headers["Foo"][-1] + + +def test_http_api_headers_serializer_with_null_values(): + serializer = HttpApiHeadersSerializer() + payload = serializer.serialize(headers={"Foo": None}, cookies=[]) + assert payload == {"headers": {}, "cookies": []} + + +def test_multi_value_headers_serializer_with_null_values(): + serializer = MultiValueHeadersSerializer() + payload = serializer.serialize(headers={"Foo": None}, cookies=[]) + assert payload == {"multiValueHeaders": {}} + + +def test_single_value_headers_serializer_with_null_values(): + serializer = SingleValueHeadersSerializer() + payload = serializer.serialize(headers={"Foo": None}, cookies=[]) + assert payload["headers"] == {}