Skip to content

Commit

Permalink
json parameter now accepts a bytes instance for pre-serialized json.
Browse files Browse the repository at this point in the history
  • Loading branch information
Aviram Hassan committed Jul 1, 2021
1 parent ab64f7c commit 23f5234
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 2 deletions.
6 changes: 6 additions & 0 deletions docs/quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,12 @@ For more complicated data structures you'll often want to use JSON encoding inst
...
}
```
In case you wish to encode the JSON on your own, you can give a `bytes` object as a parameter for `json=`.

>>> r = httpx.post("https://httpbin.org/post", json=b'"i_am_a_valid_json"')
>>> print(r.headers['content-type'])
application/json
```
## Sending Binary Request Data
Expand Down
2 changes: 1 addition & 1 deletion httpx/_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def request(
* **files** - *(optional)* A dictionary of upload files to include in the
body of the request.
* **json** - *(optional)* A JSON serializable object to include in the body
of the request.
of the request. if a bytes object given, treats it as a serialized json.
* **headers** - *(optional)* Dictionary of HTTP headers to include in the
request.
* **cookies** - *(optional)* Dictionary of Cookie items to include in the
Expand Down
5 changes: 4 additions & 1 deletion httpx/_content.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,10 @@ def encode_html(html: str) -> Tuple[Dict[str, str], ByteStream]:


def encode_json(json: Any) -> Tuple[Dict[str, str], ByteStream]:
body = json_dumps(json).encode("utf-8")
if isinstance(json, bytes):
body = json
else:
body = json_dumps(json).encode("utf-8")
content_length = str(len(body))
content_type = "application/json"
headers = {"Content-Length": content_length, "Content-Type": content_type}
Expand Down
17 changes: 17 additions & 0 deletions tests/test_content.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,23 @@ async def test_json_content():
assert async_content == b'{"Hello": "world!"}'


@pytest.mark.asyncio
async def test_json_preserialized_content():
headers, stream = encode_request(json=b'"iamajson"')
assert isinstance(stream, typing.Iterable)
assert isinstance(stream, typing.AsyncIterable)

sync_content = b"".join([part for part in stream])
async_content = b"".join([part async for part in stream])

assert headers == {
"Content-Length": "10",
"Content-Type": "application/json",
}
assert sync_content == b'"iamajson"'
assert async_content == b'"iamajson"'


@pytest.mark.asyncio
async def test_urlencoded_content():
headers, stream = encode_request(data={"Hello": "world!"})
Expand Down

0 comments on commit 23f5234

Please sign in to comment.