Repository: allisson/python-simple-rest-client

Issue:
json.decoder.JSONDecodeError when processing empty server responses
@zmbbb report:

Hey, really like your lib and the elegant interface.

I encountered an exception (see below) when I received an empty response from the server, in this case a "204 NO CONTENT". The lib forwarded the empty response to JSON for decoding which raised the exception. As a quick fix, I added a check whether client_response.text is True. This works for me, for empty and non-empty responses.

The exception:
[...]
File "/usr/local/lib/python3.5/dist-packages/simple_rest_client/resource.py", line 107, in action_method
return make_request(self.session, request)
File "/usr/local/lib/python3.5/dist-packages/simple_rest_client/decorators.py", line 39, in wrapper
response = f(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/simple_rest_client/request.py", line 30, in make_request
body = json.loads(client_response.text)
File "/usr/local/lib/python3.5/dist-packages/json_encoder/json/init.py", line 229, in loads
**kw
File "/usr/lib/python3.5/json/init.py", line 332, in loads
return cls(**kw).decode(s)
File "/usr/lib/python3.5/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.5/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)


Discussion:
codecov-io: # [Codecov](https://codecov.io/gh/allisson/python-simple-rest-client/pull/9?src=pr&el=h1) Report
> Merging [#9](https://codecov.io/gh/allisson/python-simple-rest-client/pull/9?src=pr&el=desc) into [master](https://codecov.io/gh/allisson/python-simple-rest-client/commit/2b7a0b84f9ba93ab0223da50b28365f61433e73c?src=pr&el=desc) will **not change** coverage.
> The diff coverage is `100%`.

[![Impacted file tree graph](https://codecov.io/gh/allisson/python-simple-rest-client/pull/9/graphs/tree.svg?src=pr&token=YsspZn4Uwl&width=650&height=150)](https://codecov.io/gh/allisson/python-simple-rest-client/pull/9?src=pr&el=tree)

```diff
@@          Coverage Diff          @@
##           master     #9   +/-   ##
=====================================
  Coverage     100%   100%           
=====================================
  Files           6      6           
  Lines         184    188    +4     
=====================================
+ Hits          184    188    +4
```


| [Impacted Files](https://codecov.io/gh/allisson/python-simple-rest-client/pull/9?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [simple\_rest\_client/request.py](https://codecov.io/gh/allisson/python-simple-rest-client/pull/9/diff?src=pr&el=tree#diff-c2ltcGxlX3Jlc3RfY2xpZW50L3JlcXVlc3QucHk=) | `100% <100%> (ø)` | :arrow_up: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/allisson/python-simple-rest-client/pull/9?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/allisson/python-simple-rest-client/pull/9?src=pr&el=footer). Last update [2b7a0b8...c862d35](https://codecov.io/gh/allisson/python-simple-rest-client/pull/9?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).


Patch:
diff --git a/.gitignore b/.gitignore
index 95ea3fd..ed03ab1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -39,7 +39,7 @@ htmlcov/
 .tox/
 .coverage
 .coverage.*
-.cache
+.pytest_cache
 nosetests.xml
 coverage.xml
 *,cover
diff --git a/CHANGES.rst b/CHANGES.rst
index 13d44c2..229f54b 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -1,6 +1,11 @@
 Changelog
 ---------
 
+0.5.2
+~~~~~
+
+* Fix JSONDecodeError when processing empty server responses (thanks @zmbbb).
+
 0.5.1
 ~~~~~
 
diff --git a/simple_rest_client/request.py b/simple_rest_client/request.py
index b412489..05713a9 100644
--- a/simple_rest_client/request.py
+++ b/simple_rest_client/request.py
@@ -3,7 +3,7 @@ import logging
 import async_timeout
 from json_encoder import json
 
-from .decorators import handle_request_error, handle_async_request_error
+from .decorators import handle_async_request_error, handle_request_error
 from .models import Response
 
 logger = logging.getLogger(__name__)
@@ -26,7 +26,9 @@ def make_request(session, request):
     if 'text' in content_type:
         body = client_response.text
     elif 'json' in content_type:
-        body = json.loads(client_response.text)
+        body = client_response.text
+        if body:
+            body = json.loads(body)
     else:
         body = client_response.content
 
@@ -58,7 +60,9 @@ async def make_async_request(session, request):
             if 'text' in content_type:
                 body = await client_response.text()
             elif 'json' in content_type:
-                body = json.loads(await client_response.text())
+                body = await client_response.text()
+                if body:
+                    body = json.loads(body)
             else:
                 body = await client_response.read()
 


Test patch:
diff --git a/tests/test_resource.py b/tests/test_resource.py
index 5f8fc0b..f3a70bd 100644
--- a/tests/test_resource.py
+++ b/tests/test_resource.py
@@ -83,24 +83,25 @@ def test_resource_actions(url, method, status, action, args, kwargs, reqres_reso
     assert response.body == {'success': True}
 
 
-@pytest.mark.parametrize('content_type,response_body', [
-    ('application/json', {'success': True}),
-    ('text/plain', '{"success": true}'),
-    ('application/octet-stream', b'{"success": true}'),
+@pytest.mark.parametrize('content_type,response_body,expected_response_body', [
+    ('application/json', '{"success": true}', {'success': True}),
+    ('application/json', '', ''),
+    ('text/plain', '{"success": true}', '{"success": true}'),
+    ('application/octet-stream', '{"success": true}', b'{"success": true}'),
 ])
 @responses.activate
-def test_resource_response_body(content_type, response_body, reqres_resource):
+def test_resource_response_body(content_type, response_body, expected_response_body, reqres_resource):
     url = 'https://reqres.in/api/users'
     responses.add(
         responses.GET,
         url,
-        body=b'{"success": true}',
+        body=response_body,
         status=200,
         content_type=content_type
     )
 
     response = reqres_resource.list()
-    assert response.body == response_body
+    assert response.body == expected_response_body
 
 
 @pytest.mark.asyncio
@@ -124,14 +125,15 @@ async def test_async_resource_actions(url, method, status, action, args, kwargs,
 
 
 @pytest.mark.asyncio
-@pytest.mark.parametrize('content_type,response_body', [
-    ('application/json', {'success': True}),
-    ('text/plain', '{"success": true}'),
-    ('application/octet-stream', b'{"success": true}'),
+@pytest.mark.parametrize('content_type,response_body,expected_response_body', [
+    ('application/json', '{"success": true}', {'success': True}),
+    ('application/json', '', ''),
+    ('text/plain', '{"success": true}', '{"success": true}'),
+    ('application/octet-stream', '{"success": true}', b'{"success": true}'),
 ])
-async def test_asyncresource_response_body(content_type, response_body, reqres_async_resource):
+async def test_asyncresource_response_body(content_type, response_body, expected_response_body, reqres_async_resource):
     url = 'https://reqres.in/api/users'
     with aioresponses() as mock_response:
-        mock_response.get(url, status=200, body=b'{"success": true}', headers={'Content-Type': content_type})
+        mock_response.get(url, status=200, body=response_body, headers={'Content-Type': content_type})
         response = await reqres_async_resource.list()
-    assert response.body == response_body
+    assert response.body == expected_response_body