Skip to content

Commit 1b8f00c

Browse files
Content-Length for empty POST, PUT, PATCH requests (#129)
1 parent 6e5bf70 commit 1b8f00c

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-0
lines changed

src/ahttpx/_request.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,17 @@ def __init__(
5353
elif content_length > 0:
5454
self.headers = self.headers.copy_set("Content-Length", str(content_length))
5555

56+
elif method in ("POST", "PUT", "PATCH"):
57+
# https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.2
58+
# RFC 7230, Section 3.3.2, Content Length.
59+
#
60+
# A user agent SHOULD send a Content-Length in a request message when no
61+
# Transfer-Encoding is sent and the request method defines a meaning for
62+
# an enclosed payload body. For example, a Content-Length header field is
63+
# normally sent in a POST request even when the value is 0.
64+
# (indicating an empty payload body).
65+
self.headers = self.headers.copy_set("Content-Length", "0")
66+
5667
@property
5768
def body(self) -> bytes:
5869
if not hasattr(self, '_body'):

src/httpx/_request.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,17 @@ def __init__(
5353
elif content_length > 0:
5454
self.headers = self.headers.copy_set("Content-Length", str(content_length))
5555

56+
elif method in ("POST", "PUT", "PATCH"):
57+
# https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.2
58+
# RFC 7230, Section 3.3.2, Content Length.
59+
#
60+
# A user agent SHOULD send a Content-Length in a request message when no
61+
# Transfer-Encoding is sent and the request method defines a meaning for
62+
# an enclosed payload body. For example, a Content-Length header field is
63+
# normally sent in a POST request even when the value is 0.
64+
# (indicating an empty payload body).
65+
self.headers = self.headers.copy_set("Content-Length", "0")
66+
5667
@property
5768
def body(self) -> bytes:
5869
if not hasattr(self, '_body'):

tests/test_request.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,3 +64,16 @@ def test_request_json():
6464
"Content-Type": "application/json",
6565
}
6666
assert r.read() == b'{"msg":"Hello, world"}'
67+
68+
69+
def test_request_empty_post():
70+
r = httpx.Request("POST", "https://example.com")
71+
72+
assert repr(r) == "<Request [POST 'https://example.com']>"
73+
assert r.method == "POST"
74+
assert r.url == "https://example.com"
75+
assert r.headers == {
76+
"Host": "example.com",
77+
"Content-Length": "0",
78+
}
79+
assert r.read() == b''

0 commit comments

Comments
 (0)