Skip to content
Myr

advanced.md

This file

Path

docs/advanced.md

869 lines · 29.2 KiB · Markdown

Last changed by

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

History of this file

Take it

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

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 1–5why, one step back
1# Advanced Usage
23## Client Instances45!!! hint

Revamp docs on Client instances (#836)Florimond Mancabefore adoption7256366

line 6why, one step back
6 If you are coming from Requests, `httpx.Client()` is what you can use instead of `requests.Session()`.

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

line 7why, one step back
7

Revamp docs on Client instances (#836)Florimond Mancabefore adoption7256366

line 8why, one step back
8### Why use a Client?

Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84

line 9why, one step back
9

Revamp docs on Client instances (#836)Florimond Mancabefore adoption7256366

lines 10–11why, one step back
10!!! note "TL;DR"
11 If you do anything more than experimentation, one-off scripts, or prototypes, then you should use a `Client` instance.

Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84

line 12why, one step back
12

Revamp docs on Client instances (#836)Florimond Mancabefore adoption7256366

lines 13–35why, one step back
13#### More efficient usage of network resources
1415When you make requests using the top-level API as documented in the [Quickstart](/quickstart) guide, HTTPX has to establish a new connection _for every single request_ (connections are not reused). As the number of requests to a host increases, this quickly becomes inefficient.1617On the other hand, a `Client` instance uses [HTTP connection pooling](https://en.wikipedia.org/wiki/HTTP_persistent_connection). This means that when you make several requests to the same host, the `Client` will reuse the underlying TCP connection, instead of recreating one for every single request.1819This can bring **significant performance improvements** compared to using the top-level API, including:2021- Reduced latency across requests (no handshaking).22- Reduced CPU usage and round-trips.23- Reduced network congestion.2425#### Extra features2627`Client` instances also support features that aren't available at the top-level API, such as:2829- Cookie persistance across requests.30- Applying configuration across all outgoing requests.31- Sending requests through HTTP proxies.32- Using [HTTP/2](/http2).3334The other sections on this page go into further detail about what you can do with a `Client` instance.35

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 36–40why, one step back
36### Usage
3738The recommended way to use a `Client` is as a context manager. This will ensure that connections are properly cleaned up when leaving the `with` block:3940```python

Revamp docs on Client instances (#836)Florimond Mancabefore adoption7256366

lines 41–42why, one step back
41with httpx.Client() as client:
42 ...

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 43–44why, one step back
43```
44

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 45why, one step back
45Alternatively, you can explicitly close the connection pool without block-usage using `.close()`:

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 46–47why, one step back
46
47```python

Revamp docs on Client instances (#836)Florimond Mancabefore adoption7256366

lines 48–60why, one step back
48client = httpx.Client()
49try:50 ...51finally:52 client.close()53```5455### Making requests5657Once you have a `Client`, you can send requests using `.get()`, `.post()`, etc. For example:5859```python60>>> with httpx.Client() as client:

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 61why, one step back
61... r = client.get('https://example.com')

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 62–66why, one step back
62...
63>>> r64<Response [200 OK]>65```66

Revamp docs on Client instances (#836)Florimond Mancabefore adoption7256366

line 67why, one step back
67These methods accept the same arguments as `httpx.get()`, `httpx.post()`, etc. This means that all features documented in the [Quickstart](/quickstart) guide are also available at the client level.

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

line 68why, one step back
68

Revamp docs on Client instances (#836)Florimond Mancabefore adoption7256366

line 69why, one step back
69For example, to send a request with custom headers:

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

line 70why, one step back
70

Revamp docs on Client instances (#836)Florimond Mancabefore adoption7256366

lines 71–81why, one step back
71```python
72>>> with httpx.Client() as client:73... headers = {'X-Custom': 'value'}74... r = client.get('https://example.com', headers=headers)75...76>>> r.request.headers['X-Custom']77'value'78```7980### Sharing configuration across requests81

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 82–83why, one step back
82Clients allow you to apply configuration to all outgoing requests by passing parameters to the `Client` constructor.
83

Revamp docs on Client instances (#836)Florimond Mancabefore adoption7256366

line 84why, one step back
84For example, to apply a set of custom headers _on every request_:

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 85–88why, one step back
85
86```python87>>> url = 'http://httpbin.org/headers'88>>> headers = {'user-agent': 'my-app/0.0.1'}

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 89–90why, one step back
89>>> with httpx.Client(headers=headers) as client:
90... r = client.get(url)

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 91–95why, one step back
91...
92>>> r.json()['headers']['User-Agent']93'my-app/0.0.1'94```95

Revamp docs on Client instances (#836)Florimond Mancabefore adoption7256366

line 96why, one step back
96### Merging of configuration

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

line 97why, one step back
97

Revamp docs on Client instances (#836)Florimond Mancabefore adoption7256366

line 98why, one step back
98When a configuration option is provided at both the client-level and request-level, one of two things can happen:

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

line 99why, one step back
99

Revamp docs on Client instances (#836)Florimond Mancabefore adoption7256366

line 100why, one step back
100- For headers, query parameters and cookies, the values are combined together. For example:

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

line 101why, one step back
101

Revamp docs on Client instances (#836)Florimond Mancabefore adoption7256366

lines 102–116why, one step back
102```python
103>>> headers = {'X-Auth': 'from-client'}104>>> params = {'client_id': 'client1'}105>>> with httpx.Client(headers=headers, params=params) as client:106... headers = {'X-Custom': 'from-request'}107... params = {'request_id': 'request1'}108... r = client.get('https://example.com', headers=headers, params=params)109...110>>> r.request.url111URL('https://example.com?client_id=client1&request_id=request1')112>>> r.request.headers['X-Auth']113'from-client'114>>> r.request.headers['X-Custom']115'from-request'116```

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

line 117why, one step back
117

Revamp docs on Client instances (#836)Florimond Mancabefore adoption7256366

lines 118–119why, one step back
118- For all other parameters, the request-level value takes priority. For example:
119

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

line 120why, one step back
120```python

Revamp docs on Client instances (#836)Florimond Mancabefore adoption7256366

lines 121–138why, one step back
121>>> with httpx.Client(auth=('tom', 'mot123')) as client:
122... r = client.get('https://example.com', auth=('alice', 'ecila123'))123...124>>> _, _, auth = r.request.headers['Authorization'].partition(' ')125>>> import base64126>>> base64.b64decode(auth)127b'alice:ecila123'128```129130If you need finer-grained control on the merging of client-level and request-level parameters, see [Request instances](#request-instances).131132### Other Client-only configuration options133134Additionally, `Client` accepts some configuration options that aren't available at the request level.135136For example, `base_url` allows you to prepend an URL to all outgoing requests:137138```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 139–140why, one step back
139>>> with httpx.Client(base_url='http://httpbin.org') as client:
140... r = client.get('/headers')

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 141–145why, one step back
141...
142>>> r.request.url143URL('http://httpbin.org/headers')144```145

Revamp docs on Client instances (#836)Florimond Mancabefore adoption7256366

line 146why, one step back
146For a list of all available client parameters, see the [`Client`](/api/#client) API reference.

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 147–149why, one step back
147
148## Calling into Python Web Apps149

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 150why, one step back
150You can configure an `httpx` client to call directly into a Python web application using the WSGI protocol.

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 151–156why, one step back
151
152This is particularly useful for two main use-cases:153154* Using `httpx` as a client inside test cases.155* Mocking out external services during tests or in dev/staging environments.156

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 157why, one step back
157Here's an example of integrating against a Flask application:

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 158–159why, one step back
158
159```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 160–161why, one step back
160from flask import Flask
161import httpx

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 162–163why, one step back
162
163

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 164why, one step back
164app = Flask(__name__)

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

line 165why, one step back
165

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 166–168why, one step back
166@app.route("/")
167def hello():168 return "Hello World!"

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

line 169why, one step back
169

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 170–171why, one step back
170with httpx.Client(app=app, base_url="http://testserver") as client:
171 r = client.get("/")

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 172–173why, one step back
172 assert r.status_code == 200
173 assert r.text == "Hello World!"

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 174–175why, one step back
174```
175

Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9

line 176why, one step back
176For some more complex cases you might need to customize the WSGI transport. This allows you to:

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 177–178why, one step back
177
178* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 179–180why, one step back
179* Mount the WSGI application at a subpath by setting `script_name` (WSGI).
180* Use a given client address for requests by setting `remote_addr` (WSGI).

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 181–184why, one step back
181
182For example:183184```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 185why, one step back
185# Instantiate a client that makes WSGI requests with a client IP of "1.2.3.4".

Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9

lines 186–187why, one step back
186transport = httpx.WSGITransport(app=app, remote_addr="1.2.3.4")
187with httpx.Client(transport=transport, base_url="http://testserver") as client:

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 188–190why, one step back
188 ...
189```190

Revamp docs on Client instances (#836)Florimond Mancabefore adoption7256366

line 191why, one step back
191## Request instances

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

line 192why, one step back
192

Revamp docs on Client instances (#836)Florimond Mancabefore adoption7256366

line 193why, one step back
193For maximum control on what gets sent over the wire, HTTPX supports building explicit [`Request`](/api#request) instances:

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 194–195why, one step back
194
195```python

Revamp docs on Client instances (#836)Florimond Mancabefore adoption7256366

lines 196–221why, one step back
196request = httpx.Request("GET", "https://example.com")
197```198199To dispatch a `Request` instance across to the network, create a [`Client` instance](#client-instances) and use `.send()`:200201```python202with httpx.Client() as client:203 response = client.send(request)204 ...205```206207If you need to mix client-level and request-level options in a way that is not supported by the default [Merging of parameters](#merging-of-parameters), you can use `.build_request()` and then make arbitrary modifications to the `Request` instance. For example:208209```python210headers = {"X-Api-Key": "...", "X-Client-ID": "ABC123"}211212with httpx.Client(headers=headers) as client:213 request = client.build_request("GET", "https://api.example.com")214215 print(request.headers["X-Client-ID"]) # "ABC123"216217 # Don't send the API key for this particular request.218 del request.headers["X-Api-Key"]219220 response = client.send(request)221 ...

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 222–235why, one step back
222```
223224## .netrc Support225226HTTPX supports .netrc file. In `trust_env=True` cases, if auth parameter is227not defined, HTTPX tries to add auth into request's header from .netrc file.228229!!! note230 The NETRC file is cached across requests made by a client.231 If you need to refresh the cache (e.g. because the NETRC file has changed),232 you should create a new client or restart the interpreter.233234As default `trust_env` is true. To set false:235```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 236why, one step back
236>>> httpx.get('https://example.org/', trust_env=False)

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 237–259why, one step back
237```
238239If `NETRC` environment is empty, HTTPX tries to use default files.240(`~/.netrc`, `~/_netrc`)241242To change `NETRC` environment:243```python244>>> import os245>>> os.environ["NETRC"] = "my_default_folder/.my_netrc"246```247248.netrc file content example:249```250machine netrcexample.org251login example-username252password example-password253254...255```256257When using `Client` instances, `trust_env` should be set on the client itself, rather that on the request methods:258259```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 260why, one step back
260client = httpx.Client(trust_env=False)

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 261–264why, one step back
261```
262263## HTTP Proxying264

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

line 265why, one step back
265HTTPX supports setting up [HTTP proxies](https://en.wikipedia.org/wiki/Proxy_server#Web_proxy_servers) via the `proxies` parameter to be passed on client initialization.

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

line 266why, one step back
266

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

lines 267–277why, one step back
267_Note: SOCKS proxies are not supported yet._
268269<div align="center">270 <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/27/Open_proxy_h2g2bob.svg/480px-Open_proxy_h2g2bob.svg.png"/>271 <figcaption><em>Diagram of how a proxy works (source: Wikipedia). The left hand side "Internet" blob may be your HTTPX client requesting <code>example.com</code> through a proxy.</em></figcaption>272</div>273274### Example275276To route all traffic (HTTP and HTTPS) to a proxy located at `http://localhost:8030`, pass the proxy URL to the client...277

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

line 278why, one step back
278```python

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

lines 279–280why, one step back
279with httpx.Client(proxies="http://localhost:8030") as client:
280 ...

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 281–282why, one step back
281```
282

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

line 283why, one step back
283To route HTTP and HTTPS requests to 2 different proxies, respectively located at `http://localhost:8030`, and `http://localhost:8031`, pass a `dict` of proxy URLs:

Detect credentials in proxy URLs and create Proxy-authorization header (#780)Yeray Diaz Diazbefore adoptionb234203

line 284why, one step back
284

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

lines 285–289why, one step back
285```python
286proxies = {287 "http": "http://localhost:8030",288 "https": "http://localhost:8031",289}

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

line 290why, one step back
290

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

lines 291–307why, one step back
291with httpx.Client(proxies=proxies) as client:
292 ...293```294295For detailed information about proxy routing, see the [Routing](#routing) section.296297!!! tip "Gotcha"298 In most cases, the proxy URL for the `https` key _should_ use the `http://` scheme (that's not a typo!).299300 This is because HTTP proxying requires initiating a connection with the proxy server. While it's possible that your proxy supports doing it via HTTPS, most proxies only support doing it via HTTP.301302 For more information, see [FORWARD vs TUNNEL](#forward-vs-tunnel).303304### Authentication305306Proxy credentials can be passed as the `userinfo` section of the proxy URL. For example:307

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

line 308why, one step back
308```python

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

lines 309–312why, one step back
309proxies = {
310 "http": "http://username:password@localhost:8030",311 # ...312}

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 313–314why, one step back
313```
314

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

line 315why, one step back
315### Routing

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

line 316why, one step back
316

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

line 317why, one step back
317HTTPX supports configuring which requests go through a given proxy and which don't based on the requested **scheme**, **domain**, **port**, or a combination of these.

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

line 318why, one step back
318

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

line 319why, one step back
319#### Wildcard routing

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

line 320why, one step back
320

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

lines 321–322why, one step back
321Route everything through a proxy...
322

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

line 323why, one step back
323```python

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

lines 324–326why, one step back
324proxies = {
325 "all": "http://localhost:8030",326}

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 327–328why, one step back
327```
328

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

lines 329–445why, one step back
329(This is equivalent to `Client(..., proxies="http://localhost:8030")`.)
330331#### Scheme routing332333Route HTTP requests through one proxy, and HTTPS requests through another...334335```python336proxies = {337 "http": "http://localhost:8030",338 "https": "http://localhost:8031",339}340```341342#### Domain routing343344Proxy all requests on domain "example.com", let other requests pass through...345346```python347proxies = {348 "all://example.com": "http://localhost:8030",349}350```351352Proxy HTTP requests on domain "example.com", let HTTPS and other requests pass through...353354```python355proxies = {356 "http://example.com": "http://localhost:8030",357}358```359360Proxy all requests to "example.com" and its subdomains, let other requests pass through...361362```python363proxies = {364 "all://*example.com": "http://localhost:8030",365}366```367368Proxy all requests to strict subdomains of "example.com", let "example.com" and other requests pass through...369370```python371proxies = {372 "all://*.example.com": "http://localhost:8030",373}374```375376#### Port routing377378Proxy HTTPS requests on port 1234 to "example.com"...379380```python381proxies = {382 "https://example.com:1234": "http://localhost:8030",383}384```385386Proxy all requests on port 1234...387388```python389proxies = {390 "all://*:1234": "http://localhost:8030",391}392```393394#### No-proxy support395396It is also possible to define requests that _shouldn't_ be routed through proxies.397398To do so, pass `None` as the proxy URL. For example...399400```python401proxies = {402 # Route requests through a proxy by default...403 "all": "http://localhost:8031",404 # Except those for "example.com".405 "all://example.com": None,406}407```408409#### Complex configuration example410411You can combine the routing features outlined above to build complex proxy routing configurations. For example...412413```python414proxies = {415 # Route all traffic through a proxy by default...416 "all": "http://localhost:8030",417 # But don't use proxies for HTTPS requests to "domain.io"...418 "https://domain.io": None,419 # And use another proxy for requests to "example.com" and its subdomains...420 "all://*example.com": "http://localhost:8031",421 # And yet another proxy if HTTP is used,422 # and the "internal" subdomain on port 5550 is requested...423 "http://internal.example.com:5550": "http://localhost:8032",424}425```426427#### Environment variables428429HTTP proxying can also be configured through environment variables, although with less fine-grained control.430431See documentation on [`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`](/environment_variables/#http_proxy-https_proxy-all_proxy) for more information.432433#### Routing algorithm overview434435For reference, the proxy routing algorithm used by HTTPX is roughly as follows...4364371. Sort proxy keys in decreasing order of specificity. (For example, a proxy on `all://example.com` comes before a proxy on `all`.) _This is done on client instanciation._4381. When making a request, go through sorted proxies, looking for a matching key...439 1. If a key matches...440 1. ...But the value is `None`, no proxy is used.441 1. Otherwise, the associated proxy is used.442 1. If no key matched, no proxy is used.443444### Proxy mechanisms445

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

line 446why, one step back
446!!! note

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

line 447why, one step back
447 This section describes **advanced** proxy concepts and functionality.

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

line 448why, one step back
448

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

line 449why, one step back
449#### FORWARD vs TUNNEL

Detect credentials in proxy URLs and create Proxy-authorization header (#780)Yeray Diaz Diazbefore adoptionb234203

line 450why, one step back
450

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

lines 451–486why, one step back
451In general, the flow for making an HTTP request through a proxy is as follows:
4524531. The client connects to the proxy (initial connection request).4541. The proxy somehow transfers data to the server on your behalf.455456How exactly step 2/ is performed depends on which of two proxying mechanisms is used:457458* **Forwarding**: the proxy makes the request for you, and sends back the response it obtained from the server.459* **Tunneling**: the proxy establishes a TCP connection to the server on your behalf, and the client reuses this connection to send the request and receive the response. This is known as an [HTTP Tunnel](https://en.wikipedia.org/wiki/HTTP_tunnel). This mechanism is how you can access websites that use HTTPS from an HTTP proxy (the client "upgrades" the connection to HTTPS by performing the TLS handshake with the server over the TCP connection provided by the proxy).460461#### Default behavior462463Given the technical definitions above, by default (and regardless of whether you're using an HTTP or HTTPS proxy), HTTPX will:464465* Use forwarding for HTTP requests.466* Use tunneling for HTTPS requests.467468This ensures that you can make HTTP and HTTPS requests in all cases (i.e. regardless of which type of proxy you're using).469470#### Forcing the proxy mechanism471472In most cases, the default behavior should work just fine as well as provide enough security.473474But if you know what you're doing and you want to force which mechanism to use, you can do so by passing an `httpx.Proxy()` instance, setting the `mode` to either `FORWARD_ONLY` or `TUNNEL_ONLY`. For example...475476```python477# Route all requests through an HTTPS proxy, using tunneling only.478proxies = httpx.Proxy(479 url="https://localhost:8030",480 mode="TUNNEL_ONLY",481)482483with httpx.Client(proxies=proxies) as client:484 # This HTTP request will be tunneled instead of forwarded.485 r = client.get("http://example.com")486```

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 487–500why, one step back
487
488## Timeout Configuration489490HTTPX is careful to enforce timeouts everywhere by default.491492The default behavior is to raise a `TimeoutException` after 5 seconds of493network inactivity.494495### Setting and disabling timeouts496497You can set timeouts for an individual request:498499```python500# Using the top-level API:

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 501why, one step back
501httpx.get('http://example.com/api/v1/example', timeout=10.0)

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 502–503why, one step back
502
503# Using a client instance:

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 504–505why, one step back
504with httpx.Client() as client:
505 client.get("http://example.com/api/v1/example", timeout=10.0)

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 506–511why, one step back
506```
507508Or disable timeouts for an individual request:509510```python511# Using the top-level API:

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 512why, one step back
512httpx.get('http://example.com/api/v1/example', timeout=None)

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 513–514why, one step back
513
514# Using a client instance:

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 515–516why, one step back
515with httpx.Client() as client:
516 client.get("http://example.com/api/v1/example", timeout=None)

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 517–524why, one step back
517```
518519### Setting a default timeout on a client520521You can set a timeout on a client instance, which results in the given522`timeout` being used as the default for requests made with this client:523524```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 525–527why, one step back
525client = httpx.Client() # Use a default 5s timeout everywhere.
526client = httpx.Client(timeout=10.0) # Use a default 10s timeout everywhere.527client = httpx.Client(timeout=None) # Disable all timeouts by default.

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 528–536why, one step back
528```
529530### Fine tuning the configuration531532HTTPX also allows you to specify the timeout behavior in more fine grained detail.533534There are four different types of timeouts that may occur. These are **connect**,535**read**, **write**, and **pool** timeouts.536

Switch to more concise Timeout parameters (#1111)Florimond Mancabefore adoption26cd4f5

line 537why, one step back
537* The **connect** timeout specifies the maximum amount of time to wait until

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 538–539why, one step back
538a connection to the requested host is established. If HTTPX is unable to connect
539within this time frame, a `ConnectTimeout` exception is raised.

Switch to more concise Timeout parameters (#1111)Florimond Mancabefore adoption26cd4f5

line 540why, one step back
540* The **read** timeout specifies the maximum duration to wait for a chunk of

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 541–542why, one step back
541data to be received (for example, a chunk of the response body). If HTTPX is
542unable to receive data within this time frame, a `ReadTimeout` exception is raised.

Switch to more concise Timeout parameters (#1111)Florimond Mancabefore adoption26cd4f5

line 543why, one step back
543* The **write** timeout specifies the maximum duration to wait for a chunk of

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 544–545why, one step back
544data to be sent (for example, a chunk of the request body). If HTTPX is unable
545to send data within this time frame, a `WriteTimeout` exception is raised.

Switch to more concise Timeout parameters (#1111)Florimond Mancabefore adoption26cd4f5

line 546why, one step back
546* The **pool** timeout specifies the maximum duration to wait for acquiring

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 547–555why, one step back
547a connection from the connection pool. If HTTPX is unable to acquire a connection
548within this time frame, a `PoolTimeout` exception is raised. A related549configuration here is the maximum number of allowable connections in the550connection pool, which is configured by the `pool_limits`.551552You can configure the timeout behavior for any of these values...553554```python555# A client with a 60s timeout for connecting, and a 10s timeout elsewhere.

Switch to more concise Timeout parameters (#1111)Florimond Mancabefore adoption26cd4f5

line 556why, one step back
556timeout = httpx.Timeout(10.0, connect=60.0)

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 557why, one step back
557client = httpx.Client(timeout=timeout)

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

line 558why, one step back
558

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 559why, one step back
559response = client.get('http://example.com/')

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 560–561why, one step back
560```
561

Document pool_limits and SSL context on verify (#942)Yeray Diaz Diazbefore adoption790a3ea

lines 562–563why, one step back
562## Pool limit configuration
563

Rename PoolLimits to Limits (#1113)Florimond Mancabefore adoptionf67e925

lines 564–565why, one step back
564You can control the connection pool size using the `limits` keyword
565argument on the client. It takes instances of `httpx.Limits` which define:

Document pool_limits and SSL context on verify (#942)Yeray Diaz Diazbefore adoption790a3ea

line 566why, one step back
566

Rename pool limit options (#968)Tom Christiebefore adoption991915a

line 567why, one step back
567- `max_keepalive`, number of allowable keep-alive connections, or `None` to always

Document pool_limits and SSL context on verify (#942)Yeray Diaz Diazbefore adoption790a3ea

line 568why, one step back
568allow. (Defaults 10)

Rename pool limit options (#968)Tom Christiebefore adoption991915a

line 569why, one step back
569- `max_connections`, maximum number of allowable connections, or` None` for no limits.

Document pool_limits and SSL context on verify (#942)Yeray Diaz Diazbefore adoption790a3ea

lines 570–573why, one step back
570(Default 100)
571572573```python

Rename PoolLimits to Limits (#1113)Florimond Mancabefore adoptionf67e925

lines 574–575why, one step back
574limits = httpx.Limits(max_keepalive=5, max_connections=10)
575client = httpx.Client(limits=limits)

Document pool_limits and SSL context on verify (#942)Yeray Diaz Diazbefore adoption790a3ea

lines 576–577why, one step back
576```
577

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 578–585why, one step back
578## Multipart file encoding
579580As mentioned in the [quickstart](/quickstart#sending-multipart-file-uploads)581multipart file encoding is available by passing a dictionary with the582name of the payloads as keys and either tuple of elements or a file-like object or a string as values.583584```python585>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 586why, one step back
586>>> r = httpx.post("https://httpbin.org/post", files=files)

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 587–610why, one step back
587>>> print(r.text)
588{589 ...590 "files": {591 "upload-file": "<... binary content ...>"592 },593 ...594}595```596597More specifically, if a tuple is used as a value, it must have between 2 and 3 elements:598599- The first element is an optional file name which can be set to `None`.600- The second element may be a file-like object or a string which will be automatically601encoded in UTF-8.602- An optional third element can be used to specify the603[MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_Types)604of the file being uploaded. If not specified HTTPX will attempt to guess the MIME type based605on the file name, with unknown file extensions defaulting to "application/octet-stream".606If the file name is explicitly set to `None` then HTTPX will not include a content-type607MIME header field.608609```python610>>> files = {'upload-file': (None, 'text content', 'text/plain')}

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 611why, one step back
611>>> r = httpx.post("https://httpbin.org/post", files=files)

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 612–622why, one step back
612>>> print(r.text)
613{614 ...615 "files": {},616 "form": {617 "upload-file": "text-content"618 },619 ...620}621```622

Add note on streaming uploads (#973)Florimond Mancabefore adoptiona58be59

lines 623–625why, one step back
623!!! tip
624 It is safe to upload large files this way. File uploads are streaming by default, meaning that only one chunk will be loaded into memory at a time.625

Add note on data fields in multipart form encoding (#1022)Florimond Mancabefore adoption0f7d644

line 626why, one step back
626 Non-file data fields can be included in the multipart form using by passing them to `data=...`.

Add support for multiple files per POST field (#1032)euri10before adoption4d28795

lines 627–636why, one step back
627
628You can also send multiple files in one go with a multiple file field form.629To do that, pass a list of `(field, <file>)` items instead of a dictionary, allowing you to pass multiple items with the same `field`.630For instance this request sends 2 files, `foo.png` and `bar.png` in one request on the `images` form field: 631632```python633>>> files = [('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),634 ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]635>>> r = httpx.post("https://httpbin.org/post", files=files)636```

Add note on data fields in multipart form encoding (#1022)Florimond Mancabefore adoption0f7d644

line 637why, one step back
637

Public Auth API (#732)Tom Christiebefore adoption12dd157

lines 638–700why, one step back
638## Customizing authentication
639640When issuing requests or instantiating a client, the `auth` argument can be used to pass an authentication scheme to use. The `auth` argument may be one of the following...641642* A two-tuple of `username`/`password`, to be used with basic authentication.643* An instance of `httpx.BasicAuth()` or `httpx.DigestAuth()`.644* A callable, accepting a request and returning an authenticated request instance.645* A subclass of `httpx.Auth`.646647The most involved of these is the last, which allows you to create authentication flows involving one or more requests. A subclass of `httpx.Auth` should implement `def auth_flow(request)`, and yield any requests that need to be made...648649```python650class MyCustomAuth(httpx.Auth):651 def __init__(self, token):652 self.token = token653654 def auth_flow(self, request):655 # Send the request, with a custom `X-Authentication` header.656 request.headers['X-Authentication'] = self.token657 yield request658```659660If the auth flow requires more that one request, you can issue multiple yields, and obtain the response in each case...661662```python663class MyCustomAuth(httpx.Auth):664 def __init__(self, token):665 self.token = token666667 def auth_flow(self, request):668 response = yield request669 if response.status_code == 401:670 # If the server issues a 401 response then resend the request,671 # with a custom `X-Authentication` header.672 request.headers['X-Authentication'] = self.token673 yield request674```675676Custom authentication classes are designed to not perform any I/O, so that they may be used with both sync and async client instances. If you are implementing an authentication scheme that requires the request body, then you need to indicate this on the class using a `requires_request_body` property.677678You will then be able to access `request.content` inside the `.auth_flow()` method.679680```python681class MyCustomAuth(httpx.Auth):682 requires_request_body = True683684 def __init__(self, token):685 self.token = token686687 def auth_flow(self, request):688 response = yield request689 if response.status_code == 401:690 # If the server issues a 401 response then resend the request,691 # with a custom `X-Authentication` header.692 request.headers['X-Authentication'] = self.sign_request(...)693 yield request694695 def sign_request(self, request):696 # Create a request signature, based on `request.method`, `request.url`,697 # `request.headers`, and `request.content`.698 ...699```700

Add Auth.requires_response_body attribute (#803)George Kettleboroughbefore adoptionb3db9ff

lines 701–735why, one step back
701Similarly, if you are implementing a scheme that requires access to the response body, then use the `requires_response_body` property. You will then be able to access response body properties and methods such as `response.content`, `response.text`, `response.json()`, etc.
702703```python704class MyCustomAuth(httpx.Auth):705 requires_response_body = True706707 def __init__(self, access_token, refresh_token, refresh_url):708 self.access_token = access_token709 self.refresh_token = refresh_token710 self.refresh_url = refresh_url711712 def auth_flow(self, request):713 request.headers["X-Authentication"] = self.access_token714 response = yield request715716 if response.status_code == 401:717 # If the server issues a 401 response, then issue a request to718 # refresh tokens, and resend the request.719 refresh_response = yield self.build_refresh_request()720 self.update_tokens(refresh_response)721722 request.headers["X-Authentication"] = self.access_token723 yield request724725 def build_refresh_request(self):726 # Return an `httpx.Request` for refreshing tokens.727 ...728729 def update_tokens(self, response):730 # Update the `.access_token` and `.refresh_token` tokens731 # based on a refresh response.732 data = response.json()733 ...734```735

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 736–748why, one step back
736## SSL certificates
737738When making a request over HTTPS, HTTPX needs to verify the identity of the requested host. To do this, it uses a bundle of SSL certificates (a.k.a. CA bundle) delivered by a trusted certificate authority (CA).739740### Changing the verification defaults741742By default, HTTPX uses the CA bundle provided by [Certifi](https://pypi.org/project/certifi/). This is what you want in most cases, even though some advanced situations may require you to use a different set of certificates.743744If you'd like to use a custom CA bundle, you can use the `verify` parameter.745746```python747import httpx748

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 749why, one step back
749r = httpx.get("https://example.org", verify="path/to/client.pem")

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 750–751why, one step back
750```
751

Document pool_limits and SSL context on verify (#942)Yeray Diaz Diazbefore adoption790a3ea

lines 752–762why, one step back
752Alternatively, you can pass a standard library `ssl.SSLContext`.
753754```python755>>> import ssl756>>> import httpx757>>> context = ssl.create_default_context()758>>> context.load_verify_locations(cafile="/tmp/client.pem")759>>> httpx.get('https://example.org', verify=context)760<Response [200 OK]>761```762

Included create_ssl_context function to create the same context with SSLConfig and serve as API (#996)Can Sarıgölbefore adoption926a55a

lines 763–779why, one step back
763We also include a helper function for creating properly configured `SSLContext` instances.
764765```python766>>> context = httpx.create_ssl_context()767```768769The `create_ssl_context` function accepts the same set of SSL configuration arguments 770(`trust_env`, `verify`, `cert` and `http2` arguments) 771as `httpx.Client` or `httpx.AsyncClient`772773```python774>>> import httpx775>>> context = httpx.create_ssl_context(verify="/tmp/client.pem")776>>> httpx.get('https://example.org', verify=context)777<Response [200 OK]>778```779

Document pool_limits and SSL context on verify (#942)Yeray Diaz Diazbefore adoption790a3ea

line 780why, one step back
780Or you can also disable the SSL verification entirely, which is _not_ recommended.

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 781–784why, one step back
781
782```python783import httpx784

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 785why, one step back
785r = httpx.get("https://example.org", verify=False)

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 786–792why, one step back
786```
787788### SSL configuration on client instances789790If you're using a `Client()` instance, then you should pass any SSL settings when instantiating the client.791792```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 793why, one step back
793client = httpx.Client(verify=False)

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 794–809why, one step back
794```
795796The `client.get(...)` method and other request methods *do not* support changing the SSL settings on a per-request basis. If you need different SSL settings in different cases you should use more that one client instance, with different settings on each. Each client will then be using an isolated connection pool with a specific fixed SSL configuration on all connections within that pool.797798### Making HTTPS requests to a local server799800When making requests to local servers, such as a development server running on `localhost`, you will typically be using unencrypted HTTP connections.801802If you do need to make HTTPS connections to a local server, for example to test an HTTPS-only service, you will need to create and use your own certificates. Here's one way to do it:8038041. Use [trustme-cli](https://github.com/sethmlarson/trustme-cli/) to generate a pair of server key/cert files, and a client cert file.8051. Pass the server key/cert files when starting your local server. (This depends on the particular web server you're using. For example, [Uvicorn](https://www.uvicorn.org) provides the `--ssl-keyfile` and `--ssl-certfile` options.)8061. Tell HTTPX to use the certificates stored in `client.pem`:807808```python809>>> import httpx

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 810why, one step back
810>>> r = httpx.get("https://localhost:8000", verify="/tmp/client.pem")

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

lines 811–812why, one step back
811>>> r
812Response <200 OK>

Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9

lines 813–827why, one step back
813```
814815## Custom Transports816817HTTPX's `Client` also accepts a `transport` argument. This argument allows you818to provide a custom Transport object that will be used to perform the actual819sending of the requests.820821A transport instance must implement the Transport API defined by822[`httpcore`](https://www.encode.io/httpcore/api/). You823should either subclass `httpcore.AsyncHTTPTransport` to implement a transport to824use with `AsyncClient`, or subclass `httpcore.SyncHTTPTransport` to implement a825transport to use with `Client`.826827For example, HTTPX ships with a transport that uses the excellent

Update dependencies in docs (#969)Tom Christiebefore adoption99a5c78

lines 828–829why, one step back
828[`urllib3` library](https://urllib3.readthedocs.io/en/latest/), which can be
829used with the sync `Client`...

Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9

lines 830–837why, one step back
830
831```python832>>> import httpx833>>> client = httpx.Client(transport=httpx.URLLib3Transport())834>>> client.get("https://example.org")835<Response [200 OK]>836```837

Update dependencies in docs (#969)Tom Christiebefore adoption99a5c78

lines 838–840why, one step back
838Note that you'll need to install the `urllib3` package to use `URLLib3Transport`.
839840A complete example of a custom transport implementation would be:

Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9

lines 841–868why, one step back
841
842```python843import json844845import httpcore846import httpx847848849class JSONEchoTransport(httpcore.SyncHTTPTransport):850 """851 A mock transport that returns a JSON response containing the request body.852 """853854 def request(self, method, url, headers=None, stream=None, timeout=None):855 body = b"".join(stream).decode("utf-8")856 content = json.dumps({"body": body}).encode("utf-8")857 stream = httpcore.SyncByteStream([content])858 headers = [(b"content-type", b"application/json")]859 return b"HTTP/1.1", 200, b"OK", headers, stream860```861862Which we can use in the same way:863864```python865>>> client = httpx.Client(transport=JSONEchoTransport())866>>> response = client.post("https://httpbin.org/post", data="Hello, world!")867>>> response.json()868{'body': 'Hello, world!'}

asyncio: Don't wait for the stream to close (#640)Florimond Mancabefore adoptionc337938

line 869why, one step back
869```