Skip to content

Commit 6c0afbc

Browse files
committed
Change default api client request body serialization
This commit makes a change in the default api client - request body serialization. The earlier code has a conversion for the request body to convert to json before triggering the APIs, without checking the content type of the request. This would make incorrect API calls if the request body is not of type JSON. This commit checks if the request body content is of type json and only convert it. If not, then send in the body unconverted, leaving the initial input as is.
1 parent e64c35e commit 6c0afbc

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

ask-sdk-core/ask_sdk_core/api_client.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,12 @@ def invoke(self, request):
6767
"Requests against non-HTTPS endpoints are not allowed.")
6868

6969
if request.body:
70-
raw_data = json.dumps(request.body)
70+
body_content_type = http_headers.get("Content-type", None)
71+
if (body_content_type is not None and
72+
"json" in body_content_type):
73+
raw_data = json.dumps(request.body)
74+
else:
75+
raw_data = request.body
7176
else:
7277
raw_data = None
7378

ask-sdk-core/tests/unit/test_api_client.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -184,16 +184,35 @@ def test_api_client_invoke_with_no_url_schema_throw_error(self):
184184

185185
assert "Requests against non-HTTPS endpoints are not allowed." in str(exc.exception)
186186

187-
def test_api_client_send_request_with_raw_data(self):
187+
def test_api_client_send_request_with_raw_data_serialized_for_json_content(
188+
self):
188189
test_data = "test\nstring"
189190
self.valid_request.body = "test\nstring"
190191
self.valid_request.method = "POST"
192+
headers = [("Content-type", "application/json")]
193+
self.valid_request.headers = headers
191194

192195
with mock.patch(
193196
"requests.post",
194197
side_effect=lambda *args, **kwargs: self.valid_mock_response
195198
) as mock_put:
196199
actual_response = self.test_api_client.invoke(self.valid_request)
197200
mock_put.assert_called_once_with(
198-
data=json.dumps(test_data), headers={},
201+
data=json.dumps(test_data),
202+
headers={'Content-type': 'application/json'},
203+
url=self.valid_request.url)
204+
205+
def test_api_client_send_request_with_raw_data_unchanged_for_non_json_content(
206+
self):
207+
test_data = "test\nstring"
208+
self.valid_request.body = "test\nstring"
209+
self.valid_request.method = "POST"
210+
211+
with mock.patch(
212+
"requests.post",
213+
side_effect=lambda *args, **kwargs: self.valid_mock_response
214+
) as mock_put:
215+
actual_response = self.test_api_client.invoke(self.valid_request)
216+
mock_put.assert_called_once_with(
217+
data=test_data, headers={},
199218
url=self.valid_request.url)

0 commit comments

Comments
 (0)