Skip to content
Myr

compatibility.md

This file

Path

docs/compatibility.md

222 lines · 9.0 KiB · Markdown

Last changed by

update requests compatibility docs on query and form params (#2461)Ben Falkbefore adoption8e5e3b8

History of this file

Take it

The walk stopped after 200 commits: lines older than 6b93787 point at it.

Test under Python 3.10b3 (#1707)Joebefore adoption6b93787

lines 1–2why, one step back
1# Requests Compatibility Guide
2

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 3–4why, one step back
3HTTPX aims to be broadly compatible with the `requests` API, although there are a
4few design differences in places.

Test under Python 3.10b3 (#1707)Joebefore adoption6b93787

lines 5–7why, one step back
5
6This documentation outlines places where the API differs...7

Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7

lines 8–18why, one step back
8## Redirects
910Unlike `requests`, HTTPX does **not follow redirects by default**.1112We differ in behaviour here [because auto-redirects can easily mask unnecessary network13calls being made](https://github.com/encode/httpx/discussions/1785).1415You can still enable behaviour to automatically follow redirects, but you need to16do so explicitly...1718```python

Fix typos (#1968)Kian Meng, Angbefore adoption82ba15b

line 19why, one step back
19response = client.get(url, follow_redirects=True)

Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7

lines 20–27why, one step back
20```
2122Or else instantiate a client, with redirect following enabled by default...2324```python25client = httpx.Client(follow_redirects=True)26```27

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 28–47why, one step back
28## Client instances
2930The HTTPX equivalent of `requests.Session` is `httpx.Client`.3132```python33session = requests.Session(**kwargs)34```3536is generally equivalent to3738```python39client = httpx.Client(**kwargs)40```4142## Request URLs4344Accessing `response.url` will return a `URL` instance, rather than a string.4546Use `str(response.url)` if you need a string instance.47

Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7

lines 48–69why, one step back
48## Determining the next redirect request
4950The `requests` library exposes an attribute `response.next`, which can be used to obtain the next redirect request.5152```python53session = requests.Session()54request = requests.Request("GET", ...).prepare()55while request is not None:56 response = session.send(request, allow_redirects=False)57 request = response.next58```5960In HTTPX, this attribute is instead named `response.next_request`. For example:6162```python63client = httpx.Client()64request = client.build_request("GET", ...)65while request is not None:66 response = client.send(request)67 request = response.next_request68```69

Test under Python 3.10b3 (#1707)Joebefore adoption6b93787

lines 70–91why, one step back
70## Request Content
7172For uploading raw text or binary content we prefer to use a `content` parameter,73in order to better separate this usage from the case of uploading form data.7475For example, using `content=...` to upload raw content:7677```python78# Uploading text, bytes, or a bytes iterator.79httpx.post(..., content=b"Hello, world")80```8182And using `data=...` to send form data:8384```python85# Uploading form data.86httpx.post(..., data={"message": "Hello, world"})87```8889Using the `data=<text/byte content>` will raise a deprecation warning,90and is expected to be fully removed with the HTTPX 1.0 release.91

Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7

lines 92–97why, one step back
92## Upload files
9394HTTPX strictly enforces that upload files must be opened in binary mode, in order95to avoid character encoding issues that can result from attempting to upload files96opened in text mode.97

Test under Python 3.10b3 (#1707)Joebefore adoption6b93787

lines 98–99why, one step back
98## Content encoding
99

Fix typos (#1968)Kian Meng, Angbefore adoption82ba15b

line 100why, one step back
100HTTPX uses `utf-8` for encoding `str` request bodies. For example, when using `content=<str>` the request body will be encoded to `utf-8` before being sent over the wire. This differs from Requests which uses `latin1`. If you need an explicit encoding, pass encoded bytes explicitly, e.g. `content=<str>.encode("latin1")`.

Add cli support (#1855)Tom Christiebefore adoptionee9250d

line 101why, one step back
101For response bodies, assuming the server didn't send an explicit encoding then HTTPX will do its best to figure out an appropriate encoding. HTTPX makes a guess at the encoding to use for decoding the response using `charset_normalizer`. Fallback to that or any content with less than 32 octets will be decoded using `utf-8` with the `error="replace"` decoder strategy.

Test under Python 3.10b3 (#1707)Joebefore adoption6b93787

lines 102–135why, one step back
102
103## Cookies104105If using a client instance, then cookies should always be set on the client rather than on a per-request basis.106107This usage is supported:108109```python110client = httpx.Client(cookies=...)111client.post(...)112```113114This usage is **not** supported:115116```python117client = httpx.Client()118client.post(..., cookies=...)119```120121We prefer enforcing a stricter API here because it provides clearer expectations around cookie persistence, particularly when redirects occur.122123## Status Codes124125In our documentation we prefer the uppercased versions, such as `codes.NOT_FOUND`, but also provide lower-cased versions for API compatibility with `requests`.126127Requests includes various synonyms for status codes that HTTPX does not support.128129## Streaming responses130131HTTPX provides a `.stream()` interface rather than using `stream=True`. This ensures that streaming responses are always properly closed outside of the stream block, and makes it visually clearer at which points streaming I/O APIs may be used with a response.132133For example:134135```python

Add cli support (#1855)Tom Christiebefore adoptionee9250d

line 136why, one step back
136with httpx.stream("GET", "https://www.example.com") as response:

Test under Python 3.10b3 (#1707)Joebefore adoption6b93787

lines 137–147why, one step back
137 ...
138```139140Within a `stream()` block request data is made available with:141142* `.iter_bytes()` - Instead of `response.iter_content()`143* `.iter_text()` - Instead of `response.iter_content(decode_unicode=True)`144* `.iter_lines()` - Corresponding to `response.iter_lines()`145* `.iter_raw()` - Use this instead of `response.raw`146* `.read()` - Read the entire response body, making `request.text` and `response.content` available.147

Mention default timeout differences from Requests in compatibility docs (#2433)František Nesvedabefore adoptiona2a69e4

lines 148–157why, one step back
148## Timeouts
149150HTTPX defaults to including reasonable [timeouts](quickstart.md#timeouts) for all network operations, while Requests has no timeouts by default.151152To get the same behavior as Requests, set the `timeout` parameter to `None`:153154```python155httpx.get('https://www.example.com', timeout=None)156```157

Test under Python 3.10b3 (#1707)Joebefore adoption6b93787

lines 158–177why, one step back
158## Proxy keys
159160When using `httpx.Client(proxies={...})` to map to a selection of different proxies, we use full URL schemes, such as `proxies={"http://": ..., "https://": ...}`.161162This is different to the `requests` usage of `proxies={"http": ..., "https": ...}`.163164This change is for better consistency with more complex mappings, that might also include domain names, such as `proxies={"all://": ..., "all://www.example.com": None}` which maps all requests onto a proxy, except for requests to "www.example.com" which have an explicit exclusion.165166Also note that `requests.Session.request(...)` allows a `proxies=...` parameter, whereas `httpx.Client.request(...)` does not.167168## SSL configuration169170When using a `Client` instance, the `trust_env`, `verify`, and `cert` arguments should always be passed on client instantiation, rather than passed to the request method.171172If you need more than one different SSL configuration, you should use different client instances for each SSL configuration.173174Requests supports `REQUESTS_CA_BUNDLE` which points to either a file or a directory. HTTPX supports the `SSL_CERT_FILE` (for a file) and `SSL_CERT_DIR` (for a directory) OpenSSL variables instead.175176## Request body on HTTP methods177

Add cli support (#1855)Tom Christiebefore adoptionee9250d

line 178why, one step back
178The HTTP `GET`, `DELETE`, `HEAD`, and `OPTIONS` methods are specified as not supporting a request body. To stay in line with this, the `.get`, `.delete`, `.head` and `.options` functions do not support `content`, `files`, `data`, or `json` arguments.

Test under Python 3.10b3 (#1707)Joebefore adoption6b93787

lines 179–181why, one step back
179
180If you really do need to send request data using these http methods you should use the generic `.request` function instead.181

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 182–188why, one step back
182```python
183httpx.request(184 method="DELETE",185 url="https://www.example.com/",186 content=b'A request body on a DELETE request.'187)188```

Test under Python 3.10b3 (#1707)Joebefore adoption6b93787

line 189why, one step back
189

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 190–192why, one step back
190## Checking for success and failure responses
191192We don't support `response.is_ok` since the naming is ambiguous there, and might incorrectly imply an equivalence to `response.status_code == codes.OK`. Instead we provide the `response.is_success` property, which can be used to check for a 2xx response.

Test under Python 3.10b3 (#1707)Joebefore adoption6b93787

lines 193–197why, one step back
193
194## Request instantiation195196There is no notion of [prepared requests](https://requests.readthedocs.io/en/stable/user/advanced/#prepared-requests) in HTTPX. If you need to customize request instantiation, see [Request instances](advanced.md#request-instances).197

Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7

line 198why, one step back
198Besides, `httpx.Request()` does not support the `auth`, `timeout`, `follow_redirects`, `proxies`, `verify` and `cert` parameters. However these are available in `httpx.request`, `httpx.get`, `httpx.post` etc., as well as on [`Client` instances](advanced.md#client-instances).

Test under Python 3.10b3 (#1707)Joebefore adoption6b93787

lines 199–213why, one step back
199
200## Mocking201202If you need to mock HTTPX the same way that test utilities like `responses` and `requests-mock` does for `requests`, see [RESPX](https://github.com/lundberg/respx).203204## Networking layer205206`requests` defers most of its HTTP networking code to the excellent [`urllib3` library](https://urllib3.readthedocs.io/en/latest/).207208On the other hand, HTTPX uses [HTTPCore](https://github.com/encode/httpcore) as its core HTTP networking layer, which is a different project than `urllib3`.209210## Query Parameters211212`requests` omits `params` whose values are `None` (e.g. `requests.get(..., params={"foo": None})`). This is not supported by HTTPX.213

update requests compatibility docs on query and form params (#2461)Ben Falkbefore adoption8e5e3b8

lines 214–215why, one step back
214For both query params (`params=`) and form data (`data=`), `requests` supports sending a list of tuples (e.g. `requests.get(..., params=[('key1', 'value1'), ('key1', 'value2')])`). This is not supported by HTTPX. Instead, use a dictionary with lists as values. E.g.: `httpx.get(..., params={'key1': ['value1', 'value2']})` or with form data: `httpx.post(..., data={'key1': ['value1', 'value2']})`.
215

Test under Python 3.10b3 (#1707)Joebefore adoption6b93787

lines 216–222why, one step back
216## Event Hooks
217218`requests` allows event hooks to mutate `Request` and `Response` objects. See [examples](https://requests.readthedocs.io/en/master/user/advanced/#event-hooks) given in the documentation for `requests`.219220In HTTPX, event hooks may access properties of requests and responses, but event hook callbacks cannot mutate the original request/response.221222If you are looking for more control, consider checking out [Custom Transports](advanced.md#custom-transports).