diff --git a/aws_lambda_powertools/event_handler/api_gateway.py b/aws_lambda_powertools/event_handler/api_gateway.py index 2231bc1b400..0007540453d 100644 --- a/aws_lambda_powertools/event_handler/api_gateway.py +++ b/aws_lambda_powertools/event_handler/api_gateway.py @@ -789,6 +789,12 @@ def _route(self, event: ResponseEventT, cors: Optional[CORSConfig]): def build(self, event: ResponseEventT, cors: Optional[CORSConfig] = None) -> Dict[str, Any]: """Build the full response dict to be returned by the lambda""" + + # We only apply the serializer when the content type is JSON and the + # body is not a str, to avoid double encoding + if self.response.is_json() and not isinstance(self.response.body, str): + self.response.body = self.serializer(self.response.body) + self._route(event, cors) if isinstance(self.response.body, bytes): @@ -796,11 +802,6 @@ def build(self, event: ResponseEventT, cors: Optional[CORSConfig] = None) -> Dic self.response.base64_encoded = True self.response.body = base64.b64encode(self.response.body).decode() - # We only apply the serializer when the content type is JSON and the - # body is not a str, to avoid double encoding - elif self.response.is_json() and not isinstance(self.response.body, str): - self.response.body = self.serializer(self.response.body) - return { "statusCode": self.response.status_code, "body": self.response.body,