Skip to content

Commit

Permalink
Change default api client request body serialization
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
nikhilym committed Feb 27, 2019
1 parent e64c35e commit 6c0afbc
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
7 changes: 6 additions & 1 deletion ask-sdk-core/ask_sdk_core/api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,12 @@ def invoke(self, request):
"Requests against non-HTTPS endpoints are not allowed.")

if request.body:
raw_data = json.dumps(request.body)
body_content_type = http_headers.get("Content-type", None)
if (body_content_type is not None and
"json" in body_content_type):
raw_data = json.dumps(request.body)
else:
raw_data = request.body
else:
raw_data = None

Expand Down
23 changes: 21 additions & 2 deletions ask-sdk-core/tests/unit/test_api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,16 +184,35 @@ def test_api_client_invoke_with_no_url_schema_throw_error(self):

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

def test_api_client_send_request_with_raw_data(self):
def test_api_client_send_request_with_raw_data_serialized_for_json_content(
self):
test_data = "test\nstring"
self.valid_request.body = "test\nstring"
self.valid_request.method = "POST"
headers = [("Content-type", "application/json")]
self.valid_request.headers = headers

with mock.patch(
"requests.post",
side_effect=lambda *args, **kwargs: self.valid_mock_response
) as mock_put:
actual_response = self.test_api_client.invoke(self.valid_request)
mock_put.assert_called_once_with(
data=json.dumps(test_data), headers={},
data=json.dumps(test_data),
headers={'Content-type': 'application/json'},
url=self.valid_request.url)

def test_api_client_send_request_with_raw_data_unchanged_for_non_json_content(
self):
test_data = "test\nstring"
self.valid_request.body = "test\nstring"
self.valid_request.method = "POST"

with mock.patch(
"requests.post",
side_effect=lambda *args, **kwargs: self.valid_mock_response
) as mock_put:
actual_response = self.test_api_client.invoke(self.valid_request)
mock_put.assert_called_once_with(
data=test_data, headers={},
url=self.valid_request.url)

0 comments on commit 6c0afbc

Please sign in to comment.