From: Sebastián Ramírez Date: Sat, 3 Jul 2021 16:25:12 +0000 (+0200) Subject: ♻ Assume request bodies contain JSON when no Content-Type header is provided (#3456) X-Git-Tag: 0.65.3~4 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=edf6b2d61ff2645d8fcde30e60421ee9d8f2a4be;p=thirdparty%2Ffastapi%2Ffastapi.git ♻ Assume request bodies contain JSON when no Content-Type header is provided (#3456) --- diff --git a/fastapi/routing.py b/fastapi/routing.py index 9b51f03cac..3cf35f5095 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -184,7 +184,9 @@ def get_request_handler( if body_bytes: json_body: Any = Undefined content_type_value = request.headers.get("content-type") - if content_type_value: + if not content_type_value: + json_body = await request.json() + else: message = email.message.Message() message["content-type"] = content_type_value if message.get_content_maintype() == "application": diff --git a/tests/test_tutorial/test_body/test_tutorial001.py b/tests/test_tutorial/test_body/test_tutorial001.py index c90240ae4c..7bf62c907d 100644 --- a/tests/test_tutorial/test_body/test_tutorial001.py +++ b/tests/test_tutorial/test_body/test_tutorial001.py @@ -229,6 +229,20 @@ def test_geo_json(): assert response.status_code == 200, response.text +def test_no_content_type_is_json(): + response = client.post( + "/items/", + data='{"name": "Foo", "price": 50.5}', + ) + assert response.status_code == 200, response.text + assert response.json() == { + "name": "Foo", + "description": None, + "price": 50.5, + "tax": None, + } + + def test_wrong_headers(): data = '{"name": "Foo", "price": 50.5}' invalid_dict = {