Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

♻ Assume request bodies contain JSON when no Content-Type header is provided #3456

Merged
merged 2 commits into from Jul 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion fastapi/routing.py
Expand Up @@ -184,7 +184,9 @@ async def app(request: Request) -> Response:
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":
Expand Down
14 changes: 14 additions & 0 deletions tests/test_tutorial/test_body/test_tutorial001.py
Expand Up @@ -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 = {
Expand Down