Skip to content
Myr

advanced.md

This file

Path

docs/advanced.md

674 lines · 22.8 KiB · Markdown

Last changed by

Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9

History of this file

Take it

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

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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()`.

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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 ...

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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()`:

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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')

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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.

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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:

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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_:

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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)

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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:

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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:

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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```

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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')

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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.

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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.

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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:

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 162–163why, one step back
162
163

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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!"

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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!"

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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:

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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).

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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:

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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

Link to ASGI docs (#577)Tom Christiebefore adoption7d45db0

line 190why, one step back
190

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

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

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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:

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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 ...

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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)

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 237–256why, 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```256

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 257–259why, one step back
257When 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)

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 261–262why, one step back
261```
262

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 263–264why, one step back
263## HTTP Proxying
264

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

line 265why, one step back
265HTTPX supports setting up HTTP proxies the same way that Requests does via the `proxies` parameter.

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 266–273why, one step back
266For example to forward all HTTP traffic to `http://127.0.0.1:3080` and all HTTPS traffic
267to `http://127.0.0.1:3081` your `proxies` config would look like this:268269```python270>>> proxies = {271... "http": "http://127.0.0.1:3080",272... "https": "http://127.0.0.1:3081"273... }

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 274why, one step back
274>>> with httpx.Client(proxies=proxies) as client:

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 275–277why, one step back
275... ...
276```277

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

lines 278–280why, one step back
278Credentials may be passed in as part of the URL in the standard way, i.e.
279`http://username:password@127.0.0.1:3080`.280

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 281–291why, one step back
281Proxies can be configured for a specific scheme and host, all schemes of a host,
282all hosts for a scheme, or for all requests. When determining which proxy configuration283to use for a given request this same order is used.284285```python286>>> proxies = {287... "http://example.com": "...", # Host+Scheme288... "all://example.com": "...", # Host289... "http": "...", # Scheme290... "all": "...", # All291... }

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 292why, one step back
292>>> with httpx.Client(proxies=proxies) as client:

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 293–295why, one step back
293... ...
294...295>>> proxy = "..." # Shortcut for {'all': '...'}

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 296why, one step back
296>>> with httpx.Client(proxies=proxy) as client:

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 297–304why, one step back
297... ...
298```299300!!! warning301 To make sure that proxies cannot read your traffic,302 and even if the proxy_url uses HTTPS, it is recommended to303 use HTTPS and tunnel requests if possible.304

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 305why, one step back
305By default `httpx.Proxy` will operate as a forwarding proxy for `http://...` requests

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

line 306why, one step back
306and will establish a `CONNECT` TCP tunnel for `https://` requests. This doesn't change

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 307why, one step back
307regardless of the proxy `url` being `http` or `https`.

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 308–311why, one step back
308
309Proxies can be configured to have different behavior such as forwarding or tunneling all requests:310311```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 312–314why, one step back
312proxy = httpx.Proxy(
313 url="https://127.0.0.1",314 mode="TUNNEL_ONLY" # May be "TUNNEL_ONLY" or "FORWARD_ONLY". Defaults to "DEFAULT".

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

line 315why, one step back
315)

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 316why, one step back
316with httpx.Client(proxies=proxy) as client:

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

line 317why, one step back
317 # This request will be tunneled instead of forwarded.

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 318why, one step back
318 r = client.get("http://example.com")

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 319–322why, one step back
319```
320321!!! note322

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 323–324why, one step back
323 To use proxies you must pass the proxy information at `Client` initialization,
324 rather than on the `.get(...)` call or other request methods.

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

lines 325–326why, one step back
325
326SOCKS proxies are *not* supported yet.

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

line 327why, one step back
327

Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20

line 328why, one step back
328## Timeout Configuration

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

line 329why, one step back
329

Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20

line 330why, one step back
330HTTPX is careful to enforce timeouts everywhere by default.

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

line 331why, one step back
331

Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20

lines 332–333why, one step back
332The default behavior is to raise a `TimeoutException` after 5 seconds of
333network inactivity.

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

line 334why, one step back
334

Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20

line 335why, one step back
335### Setting and disabling timeouts

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

line 336why, one step back
336

Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20

line 337why, one step back
337You can set timeouts for an individual request:

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 338–339why, one step back
338
339```python

Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20

line 340why, one step back
340# Using the top-level API:

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

line 342why, one step back
342

Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20

line 343why, one step back
343# Using a client instance:

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 346–347why, one step back
346```
347

Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20

line 348why, one step back
348Or disable timeouts for an individual request:

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 349–350why, one step back
349
350```python

Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20

line 351why, one step back
351# Using the top-level API:

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20

lines 353–354why, one step back
353
354# Using a client instance:

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 357–358why, one step back
357```
358

Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20

line 359why, one step back
359### Setting a default timeout on a client

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

line 360why, one step back
360

Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20

lines 361–362why, one step back
361You can set a timeout on a client instance, which results in the given
362`timeout` being used as the default for requests made with this client:

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 363–364why, one step back
363
364```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 368–369why, one step back
368```
369

Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20

line 370why, one step back
370### Fine tuning the configuration

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

line 371why, one step back
371

Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20

line 372why, one step back
372HTTPX also allows you to specify the timeout behavior in more fine grained detail.

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

line 373why, one step back
373

Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20

lines 374–375why, one step back
374There are four different types of timeouts that may occur. These are **connect**,
375**read**, **write**, and **pool** timeouts.

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

line 376why, one step back
376

Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20

lines 377–390why, one step back
377* The **connect timeout** specifies the maximum amount of time to wait until
378a connection to the requested host is established. If HTTPX is unable to connect379within this time frame, a `ConnectTimeout` exception is raised.380* The **read timeout** specifies the maximum duration to wait for a chunk of381data to be received (for example, a chunk of the response body). If HTTPX is382unable to receive data within this time frame, a `ReadTimeout` exception is raised.383* The **write timeout** specifies the maximum duration to wait for a chunk of384data to be sent (for example, a chunk of the request body). If HTTPX is unable385to send data within this time frame, a `WriteTimeout` exception is raised.386* The **pool timeout** specifies the maximum duration to wait for acquiring387a connection from the connection pool. If HTTPX is unable to acquire a connection388within this time frame, a `PoolTimeout` exception is raised. A related389configuration here is the maximum number of allowable connections in the390connection pool, which is configured by the `pool_limits`.

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

line 391why, one step back
391

Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20

lines 392–393why, one step back
392You can configure the timeout behavior for any of these values...
393

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

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

Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20

lines 395–396why, one step back
395# A client with a 60s timeout for connecting, and a 10s timeout elsewhere.
396timeout = httpx.Timeout(10.0, connect_timeout=60.0)

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

line 398why, one step back
398

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 400–401why, one step back
400```
401

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

lines 402–417why, one step back
402## Pool limit configuration
403404You can control the connection pool size using the `pool_limits` keyword405argument on the client. It takes instances of `httpx.PoolLimits` which define:406407- `soft_limit`, number of allowable keep-alive connections, or `None` to always408allow. (Defaults 10)409- `hard_limit`, maximum number of allowable connections, or` None` for no limits.410(Default 100)411412413```python414limits = httpx.PoolLimits(soft_limit=5, hard_limit=10)415client = httpx.Client(pool_limits=limits)416```417

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 418–421why, one step back
418## Multipart file encoding
419420As mentioned in the [quickstart](/quickstart#sending-multipart-file-uploads)421multipart file encoding is available by passing a dictionary with the

Clarify multipart documentation (#580)Mattwmaster58before adoption33cb397

line 422why, one step back
422name of the payloads as keys and either tuple of elements or a file-like object or a string as values.

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 423–425why, one step back
423
424```python425>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 427–436why, one step back
427>>> print(r.text)
428{429 ...430 "files": {431 "upload-file": "<... binary content ...>"432 },433 ...434}435```436

Clarify multipart documentation (#580)Mattwmaster58before adoption33cb397

line 437why, one step back
437More specifically, if a tuple is used as a value, it must have between 2 and 3 elements:

Update advanced.mdTom Christiebefore adoption871b0b5

line 438why, one step back
438

Clarify multipart documentation (#580)Mattwmaster58before adoption33cb397

lines 439–440why, one step back
439- The first element is an optional file name which can be set to `None`.
440- The second element may be a file-like object or a string which will be automatically

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

line 441why, one step back
441encoded in UTF-8.

Better HTTP/2 defaults. (#584)Tom Christiebefore adoption30229f1

line 442why, one step back
442- An optional third element can be used to specify the

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

line 443why, one step back
443[MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_Types)

Clarify multipart documentation (#580)Mattwmaster58before adoption33cb397

lines 444–447why, one step back
444of the file being uploaded. If not specified HTTPX will attempt to guess the MIME type based
445on the file name, with unknown file extensions defaulting to "application/octet-stream".446If the file name is explicitly set to `None` then HTTPX will not include a content-type447MIME header field.

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 448–450why, one step back
448
449```python450>>> files = {'upload-file': (None, 'text content', 'text/plain')}

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 452–462why, one step back
452>>> print(r.text)
453{454 ...455 "files": {},456 "form": {457 "upload-file": "text-content"458 },459 ...460}461```462

Public Auth API (#732)Tom Christiebefore adoption12dd157

lines 463–525why, one step back
463## Customizing authentication
464465When 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...466467* A two-tuple of `username`/`password`, to be used with basic authentication.468* An instance of `httpx.BasicAuth()` or `httpx.DigestAuth()`.469* A callable, accepting a request and returning an authenticated request instance.470* A subclass of `httpx.Auth`.471472The 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...473474```python475class MyCustomAuth(httpx.Auth):476 def __init__(self, token):477 self.token = token478479 def auth_flow(self, request):480 # Send the request, with a custom `X-Authentication` header.481 request.headers['X-Authentication'] = self.token482 yield request483```484485If the auth flow requires more that one request, you can issue multiple yields, and obtain the response in each case...486487```python488class MyCustomAuth(httpx.Auth):489 def __init__(self, token):490 self.token = token491492 def auth_flow(self, request):493 response = yield request494 if response.status_code == 401:495 # If the server issues a 401 response then resend the request,496 # with a custom `X-Authentication` header.497 request.headers['X-Authentication'] = self.token498 yield request499```500501Custom 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.502503You will then be able to access `request.content` inside the `.auth_flow()` method.504505```python506class MyCustomAuth(httpx.Auth):507 requires_request_body = True508509 def __init__(self, token):510 self.token = token511512 def auth_flow(self, request):513 response = yield request514 if response.status_code == 401:515 # If the server issues a 401 response then resend the request,516 # with a custom `X-Authentication` header.517 request.headers['X-Authentication'] = self.sign_request(...)518 yield request519520 def sign_request(self, request):521 # Create a request signature, based on `request.method`, `request.url`,522 # `request.headers`, and `request.content`.523 ...524```525

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

lines 526–560why, one step back
526Similarly, 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.
527528```python529class MyCustomAuth(httpx.Auth):530 requires_response_body = True531532 def __init__(self, access_token, refresh_token, refresh_url):533 self.access_token = access_token534 self.refresh_token = refresh_token535 self.refresh_url = refresh_url536537 def auth_flow(self, request):538 request.headers["X-Authentication"] = self.access_token539 response = yield request540541 if response.status_code == 401:542 # If the server issues a 401 response, then issue a request to543 # refresh tokens, and resend the request.544 refresh_response = yield self.build_refresh_request()545 self.update_tokens(refresh_response)546547 request.headers["X-Authentication"] = self.access_token548 yield request549550 def build_refresh_request(self):551 # Return an `httpx.Request` for refreshing tokens.552 ...553554 def update_tokens(self, response):555 # Update the `.access_token` and `.refresh_token` tokens556 # based on a refresh response.557 data = response.json()558 ...559```560

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 561–564why, one step back
561## SSL certificates
562563When 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).564

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

line 565why, one step back
565### Changing the verification defaults

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 566–568why, one step back
566
567By 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.568

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

line 569why, one step back
569If you'd like to use a custom CA bundle, you can use the `verify` parameter.

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 570–573why, one step back
570
571```python572import httpx573

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

line 575why, one step back
575```

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

line 576why, one step back
576

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

lines 577–588why, one step back
577Alternatively, you can pass a standard library `ssl.SSLContext`.
578579```python580>>> import ssl581>>> import httpx582>>> context = ssl.create_default_context()583>>> context.load_verify_locations(cafile="/tmp/client.pem")584>>> httpx.get('https://example.org', verify=context)585<Response [200 OK]>586```587588Or you can also disable the SSL verification entirely, which is _not_ recommended.

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 589–592why, one step back
589
590```python591import httpx592

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 594–600why, one step back
594```
595596### SSL configuration on client instances597598If you're using a `Client()` instance, then you should pass any SSL settings when instantiating the client.599600```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855

lines 602–603why, one step back
602```
603

Update advanced.mdTom Christiebefore adoptionddc4885

line 604why, one step back
604The `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.

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 605–617why, one step back
605
606### Making HTTPS requests to a local server607608When making requests to local servers, such as a development server running on `localhost`, you will typically be using unencrypted HTTP connections.609610If 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:6116121. Use [trustme-cli](https://github.com/sethmlarson/trustme-cli/) to generate a pair of server key/cert files, and a client cert file.6131. 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.)6141. Tell HTTPX to use the certificates stored in `client.pem`:615616```python617>>> import httpx

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

lines 619–620why, one step back
619>>> r
620Response <200 OK>

Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9

lines 621–673why, one step back
621```
622623## Custom Transports624625HTTPX's `Client` also accepts a `transport` argument. This argument allows you626to provide a custom Transport object that will be used to perform the actual627sending of the requests.628629A transport instance must implement the Transport API defined by630[`httpcore`](https://www.encode.io/httpcore/api/). You631should either subclass `httpcore.AsyncHTTPTransport` to implement a transport to632use with `AsyncClient`, or subclass `httpcore.SyncHTTPTransport` to implement a633transport to use with `Client`.634635For example, HTTPX ships with a transport that uses the excellent636[`urllib3` library](https://urllib3.readthedocs.io/en/latest/):637638```python639>>> import httpx640>>> client = httpx.Client(transport=httpx.URLLib3Transport())641>>> client.get("https://example.org")642<Response [200 OK]>643```644645A complete example of a transport implementation would be:646647```python648import json649650import httpcore651import httpx652653654class JSONEchoTransport(httpcore.SyncHTTPTransport):655 """656 A mock transport that returns a JSON response containing the request body.657 """658659 def request(self, method, url, headers=None, stream=None, timeout=None):660 body = b"".join(stream).decode("utf-8")661 content = json.dumps({"body": body}).encode("utf-8")662 stream = httpcore.SyncByteStream([content])663 headers = [(b"content-type", b"application/json")]664 return b"HTTP/1.1", 200, b"OK", headers, stream665```666667Which we can use in the same way:668669```python670>>> client = httpx.Client(transport=JSONEchoTransport())671>>> response = client.post("https://httpbin.org/post", data="Hello, world!")672>>> response.json()673{'body': 'Hello, world!'}

Pool timeouts should be on the TimeoutConfig, not PoolLimits (#563)Tom Christiebefore adoption364378a

line 674why, one step back
674```