aio-libs/aiohttp · error · ValueError

only one of data or body should be specified

Error message

only one of data or body should be specified

What it means

Raised by the bytes-encoding JSON response helper (`json_response_with_bytes` / the bytes-returning-encoder variant) when both `data=` and `body=` are passed. The helper expects either a value to encode via the bytes-returning `dumps` (data) or pre-encoded bytes (body), not both.

Solutions

  1. Pass exactly one: `data=obj` to have the helper encode it via `dumps`, or `body=encoded_bytes` to use pre-encoded bytes.
  2. Prefer `data=obj` and let the helper call `dumps` once.
  3. If you already have bytes, drop the `data=` argument.
  4. Keep wrapper signatures explicit about which channel to use.

Example fix

// before
return json_response_with_bytes(data=obj, body=orjson.dumps(obj))

// after
return json_response_with_bytes(data=obj)  # helper invokes orjson.dumps
Defensive patterns

Strategy: validation

Validate before calling

def safe_json_bytes(data=sentinel, body=None, **kw):
    if data is not sentinel:
        assert body is None, 'pass only one of data or body'
    return json_response_with_bytes(data=data, body=body, **kw)

Prevention

When it happens

Trigger: Calling the bytes JSON helper with `data=obj, body=orjson.dumps(obj)`. Common when migrating from `json_response` to the bytes variant and forgetting to drop one argument.

Common situations: Using orjson/mujson (which return bytes) and double-encoding by passing both the object and its serialized form; helper refactor that forwards both kwargs.

Related errors


AI-assisted analysis of aio-libs/aiohttp@d041d4d0fd (2026-08-11). Data as JSON: /api/errors/5ed465ee6275527c. Report an issue: GitHub.

Appendix: source

Thrown at aiohttp/web_response.py:782

def json_bytes_response(
    data: Any = sentinel,
    *,
    dumps: JSONBytesEncoder,
    body: bytes | None = None,
    status: int = 200,
    reason: str | None = None,
    headers: LooseHeaders | None = None,
    content_type: str = "application/json",
) -> Response:
    """Create a JSON response using a bytes-returning encoder.

    Use this when your JSON encoder (like orjson) returns bytes
    instead of str, avoiding the encode/decode overhead.
    """
    if data is not sentinel:
        if body is not None:
            raise ValueError("only one of data or body should be specified")
        else:
            body = dumps(data)
    return Response(
        body=body,
        status=status,
        reason=reason,
        headers=headers,
        content_type=content_type,
    )

View on GitHub (pinned to d041d4d0fd)