diff --git a/sanic/request.py b/sanic/request.py index bca0cf27..ac1b78d6 100644 --- a/sanic/request.py +++ b/sanic/request.py @@ -69,6 +69,8 @@ class Request(dict): try: self.parsed_json = json_loads(self.body) except Exception: + if not self.body: + return None raise InvalidUsage("Failed when parsing body as json") return self.parsed_json diff --git a/tests/test_requests.py b/tests/test_requests.py index 2bd742d6..38954038 100644 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -85,20 +85,28 @@ def test_json(): request, response = app.test_client.get('/') - try: - results = json_loads(response.text) - except: - raise ValueError("Expected JSON response but got '{}'".format(response)) + results = json_loads(response.text) assert results.get('test') == True +def test_empty_json(): + app = Sanic('test_json') + + @app.route('/') + async def handler(request): + assert request.json == None + return json(request.json) + + request, response = app.test_client.get('/') + assert response.status == 200 + assert response.text == 'null' def test_invalid_json(): app = Sanic('test_json') @app.route('/') async def handler(request): - return json(request.json()) + return json(request.json) data = "I am not json" request, response = app.test_client.get('/', data=data)