compatibility.md
This file
Path
docs/compatibility.md
202 lines · 8.1 KiB · Markdown
Last changed by
Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
History of this fileTake it
The walk stopped after 200 commits: lines older than def9f1c point at it.
Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 1–2why, one step back1# Requests Compatibility Guide2Update compatibility.md: mention differing query parameter handling (#1262)Bartbefore adoption4bd08be
line 3why, one step back3HTTPX aims to be broadly compatible with the `requests` API.Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 4–6why, one step back45This documentation outlines places where the API differs...6Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
lines 7–20why, one step back7## Client instances89The HTTPX equivalent of `requests.Session` is `httpx.Client`.1011```python12session = requests.Session(**kwargs)13```1415is generally equivalent to1617```python18client = httpx.Client(**kwargs)19```20Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 21–23why, one step back21## Request URLs2223Accessing `response.url` will return a `URL` instance, rather than a string.Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
line 24why, one step back24Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 25–26why, one step back25Use `str(response.url)` if you need a string instance.26Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
lines 27–68why, one step back27## Redirects2829Unlike `requests`, HTTPX does **not follow redirects by default**.3031We differ in behaviour here [because auto-redirects can easily mask unnecessary network32calls being made](https://github.com/encode/httpx/discussions/1785).3334You can still enable behaviour to automatically follow redirects, but you need to35do so explicitly...3637```python38respose = client.get(url, follow_redirects=True)39```4041Or else instantiate a client, with redirect following enabled by default...4243```python44client = httpx.Client(follow_redirects=True)45```4647## Determining the next redirect request4849The `requests` library exposes an attribute `response.next`, which can be used to obtain the next redirect request.5051```python52session = requests.Session()53request = requests.Request("GET", ...).prepare()54while request is not None:55 response = session.send(request, allow_redirects=False)56 request = response.next57```5859In HTTPX, this attribute is instead named `response.next_request`. For example:6061```python62client = httpx.Client()63request = client.build_request("GET", ...)64while request is not None:65 response = client.send(request)66 request = response.next_request67```68Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
lines 69–87why, one step back69## Request Content7071For uploading raw text or binary content we prefer to use a `content` parameter,72in order to better separate this usage from the case of uploading form data.7374For example, using `content=...` to upload raw content:7576```python77# Uploading text, bytes, or a bytes iterator.78httpx.post(..., content=b"Hello, world")79```8081And using `data=...` to send form data:8283```python84# Uploading form data.85httpx.post(..., data={"message": "Hello, world"})86```87Escalate the distinction between data=... and content=... to be stricter (#1573)Tom Christiebefore adoption397aad9
lines 88–89why, one step back88Using the `data=<text/byte content>` will raise a deprecation warning,89and is expected to be fully removed with the HTTPX 1.0 release.Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 90why, one step back90Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
lines 91–96why, one step back91## Upload files9293HTTPX strictly enforces that upload files must be opened in binary mode, in order94to avoid character encoding issues that can result from attempting to upload files95opened in text mode.96Document content encoding differences with Requests (#1416)Florimond Mancabefore adoption7ea6019
lines 97–100why, one step back97## Content encoding9899HTTPX 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 explictly, e.g. `content=<str>.encode("latin1")`.100:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
line 101why, one step back101For 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. Document content encoding differences with Requests (#1416)Florimond Mancabefore adoption7ea6019
line 102why, one step back102Deprecate per-request cookies (#1574)Tom Christiebefore adoption6a99f6f
lines 103–122why, one step back103## 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.122Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 123–163why, one step back123## 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```python136with request.stream("GET", "https://www.example.com") as response: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.147148## Proxy keys149150When using `httpx.Client(proxies={...})` to map to a selection of different proxies, we use full URL schemes, such as `proxies={"http://": ..., "https://": ...}`.151152This is different to the `requests` usage of `proxies={"http": ..., "https": ...}`.153154This 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.155156Also note that `requests.Session.request(...)` allows a `proxies=...` parameter, whereas `httpx.Client.request(...)` does not.157158## SSL configuration159160When 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.161162If you need more than one different SSL configuration, you should use different client instances for each SSL configuration.163Explain REQUESTS_CA_BUNDLE migration (#1471)Quentin Pradetbefore adoption5af6ab0
lines 164–165why, one step back164Requests 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.165Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 166–177why, one step back166## Request body on HTTP methods167168The 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 `files`, `data`, or `json` arguments.169170If you really do need to send request data using these http methods you should use the generic `.request` function instead.171172## Checking for 4xx/5xx responses173174We 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_error` property. Use `if not response.is_error:` instead of `if response.is_ok:`.175176## Request instantiation177Use relative links for interlinking markdown files in docs (#1390)Tom Christiebefore adoption0af6d9a
line 178why, one step back178There 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).Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
line 179why, one step back179Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
line 180why, one step back180Besides, `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).Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c
lines 181–184why, one step back181182## Mocking183184If 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).Drop urllib3 in favor of public gist (#1182)Florimond Mancabefore adoption8fa8765
lines 185–190why, one step back185186## Networking layer187188`requests` defers most of its HTTP networking code to the excellent [`urllib3` library](https://urllib3.readthedocs.io/en/latest/).189190On the other hand, HTTPX uses [HTTPCore](https://github.com/encode/httpcore) as its core HTTP networking layer, which is a different project than `urllib3`.Update compatibility.md: mention differing query parameter handling (#1262)Bartbefore adoption4bd08be
lines 191–194why, one step back191192## Query Parameters193194`requests` omits `params` whose values are `None` (e.g. `requests.get(..., params={"foo": None})`). This is not supported by HTTPX.Updates compatibility guide to address event hooks (#1436)Colton Eakinsbefore adoptione3a7b6d
lines 195–199why, one step back195196## Event Hooks197198`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`.199Escalate the distinction between data=... and content=... to be stricter (#1573)Tom Christiebefore adoption397aad9
line 200why, one step back200In HTTPX, event hooks may access properties of requests and responses, but event hook callbacks cannot mutate the original request/response.Updates compatibility guide to address event hooks (#1436)Colton Eakinsbefore adoptione3a7b6d
lines 201–202why, one step back201202If you are looking for more control, consider checking out [Custom Transports](advanced.md#custom-transports).