Browse Source

🐛 Fix double JSON parsing from request body

Remove the 'await request.json()' call which was inadvertently left in the routing path. This ensures that the body bytes are passed directly to Pydantic's validate_json via FastAPIOptimizedJsonBytes, bypassing unnecessary Python dict allocations entirely.
pull/15584/head
valbort 1 month ago
parent
commit
886cd92b5e
  1. 9
      fastapi/routing.py

9
fastapi/routing.py

@ -412,19 +412,20 @@ def get_request_handler(
else: else:
body_bytes = await request.body() body_bytes = await request.body()
if body_bytes: if body_bytes:
json_body: Any = Undefined is_json_content = False
content_type_value = request.headers.get("content-type") content_type_value = request.headers.get("content-type")
if not content_type_value: if not content_type_value:
if not actual_strict_content_type: if not actual_strict_content_type:
json_body = await request.json() is_json_content = True
else: else:
message = email.message.Message() message = email.message.Message()
message["content-type"] = content_type_value message["content-type"] = content_type_value
if message.get_content_maintype() == "application": if message.get_content_maintype() == "application":
subtype = message.get_content_subtype() subtype = message.get_content_subtype()
if subtype == "json" or subtype.endswith("+json"): if subtype == "json" or subtype.endswith("+json"):
json_body = await request.json() is_json_content = True
if json_body != Undefined:
if is_json_content:
body = FastAPIOptimizedJsonBytes(body_bytes) body = FastAPIOptimizedJsonBytes(body_bytes)
else: else:
body = body_bytes body = body_bytes

Loading…
Cancel
Save