Skip to content
Myr

advanced.md

This file

Path

docs/advanced.md

1,175 lines · 39.4 KiB · Markdown

Last changed by

Added docs for using client-side ssl certificates (#1570)Hemanth kumarbefore adoption535df6c

History of this file

Take it

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

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 1–14why, one step back
1# Advanced Usage
23## Client Instances45!!! hint6 If you are coming from Requests, `httpx.Client()` is what you can use instead of `requests.Session()`.78### Why use a Client?910!!! note "TL;DR"11 If you do anything more than experimentation, one-off scripts, or prototypes, then you should use a `Client` instance.1213#### More efficient usage of network resources14

Use relative links for interlinking markdown files in docs (#1390)Tom Christiebefore adoption0af6d9a

line 15why, one step back
15When you make requests using the top-level API as documented in the [Quickstart](quickstart.md) 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.

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 16–31why, one step back
16
17On 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.

Use relative links for interlinking markdown files in docs (#1390)Tom Christiebefore adoption0af6d9a

line 32why, one step back
32- Using [HTTP/2](http2.md).

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 33–58why, one step back
33
34The other sections on this page go into further detail about what you can do with a `Client` instance.3536### Usage3738The 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```python41with httpx.Client() as client:42 ...43```4445Alternatively, you can explicitly close the connection pool without block-usage using `.close()`:4647```python48client = 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:58

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 59why, one step back
59```pycon

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 60–66why, one step back
60>>> with httpx.Client() as client:
61... r = client.get('https://example.com')62...63>>> r64<Response [200 OK]>65```66

Use relative links for interlinking markdown files in docs (#1390)Tom Christiebefore adoption0af6d9a

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.md) guide are also available at the client level.

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 68–70why, one step back
68
69For example, to send a request with custom headers:70

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 71why, one step back
71```pycon

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 72–85why, one step back
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 requests8182Clients allow you to apply configuration to all outgoing requests by passing parameters to the `Client` constructor.8384For example, to apply a set of custom headers _on every request_:85

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 86why, one step back
86```pycon

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 87–101why, one step back
87>>> url = 'http://httpbin.org/headers'
88>>> headers = {'user-agent': 'my-app/0.0.1'}89>>> with httpx.Client(headers=headers) as client:90... r = client.get(url)91...92>>> r.json()['headers']['User-Agent']93'my-app/0.0.1'94```9596### Merging of configuration9798When a configuration option is provided at both the client-level and request-level, one of two things can happen:99100- For headers, query parameters and cookies, the values are combined together. For example:101

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 102why, one step back
102```pycon

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 103–119why, one step back
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```117118- For all other parameters, the request-level value takes priority. For example:119

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

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

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 121–137why, 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:137

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 138why, one step back
138```pycon

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

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

Use relative links for interlinking markdown files in docs (#1390)Tom Christiebefore adoption0af6d9a

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

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 147–192why, one step back
147
148## Calling into Python Web Apps149150You can configure an `httpx` client to call directly into a Python web application using the WSGI protocol.151152This 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.156157Here's an example of integrating against a Flask application:158159```python160from flask import Flask161import httpx162163164app = Flask(__name__)165166@app.route("/")167def hello():168 return "Hello World!"169170with httpx.Client(app=app, base_url="http://testserver") as client:171 r = client.get("/")172 assert r.status_code == 200173 assert r.text == "Hello World!"174```175176For some more complex cases you might need to customize the WSGI transport. This allows you to:177178* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.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).181182For example:183184```python185# Instantiate a client that makes WSGI requests with a client IP of "1.2.3.4".186transport = httpx.WSGITransport(app=app, remote_addr="1.2.3.4")187with httpx.Client(transport=transport, base_url="http://testserver") as client:188 ...189```190191## Request instances192

Use relative links for interlinking markdown files in docs (#1390)Tom Christiebefore adoption0af6d9a

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

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 194–223why, one step back
194
195```python196request = 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 ...222```223

Event hooks (#1246)Tom Christiebefore adoption54f7708

lines 224–267why, one step back
224## Event Hooks
225226HTTPX allows you to register "event hooks" with the client, that are called227every time a particular type of event takes place.228229There are currently two event hooks:230231* `request` - Called once a request is about to be sent. Passed the `request` instance.232* `response` - Called once the response has been returned. Passed the `response` instance.233234These allow you to install client-wide functionality such as logging and monitoring.235236```python237def log_request(request):238 print(f"Request event hook: {request.method} {request.url} - Waiting for response")239240def log_response(response):241 request = response.request242 print(f"Response event hook: {request.method} {request.url} - Status {response.status_code}")243244client = httpx.Client(event_hooks={'request': [log_request], 'response': [log_response]})245```246247You can also use these hooks to install response processing code, such as this248example, which creates a client instance that always raises `httpx.HTTPStatusError`249on 4xx and 5xx responses.250251```python252def raise_on_4xx_5xx(response):253 response.raise_for_status()254255client = httpx.Client(event_hooks={'response': [raise_on_4xx_5xx]})256```257258Event hooks must always be set as a **list of callables**, and you may register259multiple event hooks for each type of event.260261As well as being able to set event hooks on instantiating the client, there262is also an `.event_hooks` property, that allows you to inspect and modify263the installed hooks.264265```python266client = httpx.Client()267client.event_hooks['request'] = [log_request]

Fix function name in event hooks docs (#1290)Stephen Brown IIbefore adoptiona394df5

line 268why, one step back
268client.event_hooks['response'] = [log_response, raise_on_4xx_5xx]

Event hooks (#1246)Tom Christiebefore adoption54f7708

lines 269–275why, one step back
269```
270271!!! note272 If you are using HTTPX's async support, then you need to be aware that273 hooks registered with `httpx.AsyncClient` MUST be async functions,274 rather than plain functions.275

Add progress to streaming download (#1268)cdelerbefore adoptioned16eb3

lines 276–301why, one step back
276## Monitoring download progress
277278If you need to monitor download progress of large responses, you can use response streaming and inspect the `response.num_bytes_downloaded` property.279280This interface is required for properly determining download progress, because the total number of bytes returned by `response.content` or `response.iter_content()` will not always correspond with the raw content length of the response if HTTP response compression is being used.281282For example, showing a progress bar using the [`tqdm`](https://github.com/tqdm/tqdm) library while a response is being downloaded could be done like this…283284```python285import tempfile286287import httpx288from tqdm import tqdm289290with tempfile.NamedTemporaryFile() as download_file:291 url = "https://speed.hetzner.de/100MB.bin"292 with httpx.stream("GET", url) as response:293 total = int(response.headers["Content-Length"])294295 with tqdm(total=total, unit_scale=True, unit_divisor=1024, unit="B") as progress:296 num_bytes_downloaded = response.num_bytes_downloaded297 for chunk in response.iter_bytes():298 download_file.write(chunk)299 progress.update(response.num_bytes_downloaded - num_bytes_downloaded)300 num_bytes_downloaded = response.num_bytes_downloaded301```

Progress examples (#1272)Tom Christiebefore adoption59074c7

lines 302–329why, one step back
302
303![tqdm progress bar](img/tqdm-progress.gif)304305Or an alternate example, this time using the [`rich`](https://github.com/willmcgugan/rich) library…306307```python308import tempfile309import httpx310import rich.progress311312with tempfile.NamedTemporaryFile() as download_file:313 url = "https://speed.hetzner.de/100MB.bin"314 with httpx.stream("GET", url) as response:315 total = int(response.headers["Content-Length"])316317 with rich.progress.Progress(318 "[progress.percentage]{task.percentage:>3.0f}%",319 rich.progress.BarColumn(bar_width=None),320 rich.progress.DownloadColumn(),321 rich.progress.TransferSpeedColumn(),322 ) as progress:323 download_task = progress.add_task("Download", total=total)324 for chunk in response.iter_bytes():325 download_file.write(chunk)326 progress.update(download_task, completed=response.num_bytes_downloaded)327```328329![rich progress bar](img/rich-progress.gif)

Add progress to streaming download (#1268)cdelerbefore adoptioned16eb3

line 330why, one step back
330

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 331–341why, one step back
331## .netrc Support
332333HTTPX supports .netrc file. In `trust_env=True` cases, if auth parameter is334not defined, HTTPX tries to add auth into request's header from .netrc file.335336!!! note337 The NETRC file is cached across requests made by a client.338 If you need to refresh the cache (e.g. because the NETRC file has changed),339 you should create a new client or restart the interpreter.340341As default `trust_env` is true. To set false:

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 342why, one step back
342```pycon

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 343–349why, one step back
343>>> httpx.get('https://example.org/', trust_env=False)
344```345346If `NETRC` environment is empty, HTTPX tries to use default files.347(`~/.netrc`, `~/_netrc`)348349To change `NETRC` environment:

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 350why, one step back
350```pycon

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 351–371why, one step back
351>>> import os
352>>> os.environ["NETRC"] = "my_default_folder/.my_netrc"353```354355.netrc file content example:356```357machine netrcexample.org358login example-username359password example-password360361...362```363364When using `Client` instances, `trust_env` should be set on the client itself, rather that on the request methods:365366```python367client = httpx.Client(trust_env=False)368```369370## HTTP Proxying371

Add `proxies` parameter to top-level API functions (#1198)Joebefore adoption84ca201

line 372why, one step back
372HTTPX 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 or top-level API functions like `httpx.get(..., proxies=...)`.

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

line 373why, one step back
373

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

lines 374–384why, one step back
374_Note: SOCKS proxies are not supported yet._
375376<div align="center">377 <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/27/Open_proxy_h2g2bob.svg/480px-Open_proxy_h2g2bob.svg.png"/>378 <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>379</div>380381### Example382383To route all traffic (HTTP and HTTPS) to a proxy located at `http://localhost:8030`, pass the proxy URL to the client...384

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

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

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

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

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 388–389why, one step back
388```
389

Refine docs phrasing on proxy routing (#1124)Florimond Mancabefore adoption0fb28e8

line 390why, one step back
390For more advanced use cases, pass a proxies `dict`. For example, to 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:

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

line 391why, one step back
391

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

lines 392–393why, one step back
392```python
393proxies = {

Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4

lines 394–395why, one step back
394 "http://": "http://localhost:8030",
395 "https://": "http://localhost:8031",

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

line 396why, one step back
396}

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

line 397why, one step back
397

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

lines 398–404why, one step back
398with httpx.Client(proxies=proxies) as client:
399 ...400```401402For detailed information about proxy routing, see the [Routing](#routing) section.403404!!! tip "Gotcha"

Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4

line 405why, one step back
405 In most cases, the proxy URL for the `https://` key _should_ use the `http://` scheme (that's not a typo!).

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

lines 406–414why, one step back
406
407 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.408409 For more information, see [FORWARD vs TUNNEL](#forward-vs-tunnel).410411### Authentication412413Proxy credentials can be passed as the `userinfo` section of the proxy URL. For example:414

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

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

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

line 416why, one step back
416proxies = {

Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4

line 417why, one step back
417 "http://": "http://username:password@localhost:8030",

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

lines 418–419why, one step back
418 # ...
419}

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 420–421why, one step back
420```
421

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

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

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

line 423why, one step back
423

Refine docs phrasing on proxy routing (#1124)Florimond Mancabefore adoption0fb28e8

line 424why, one step back
424HTTPX provides fine-grained controls for deciding which requests should go through a proxy, and which shouldn't. This process is known as proxy routing.

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

line 425why, one step back
425

Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4

line 426why, one step back
426The `proxies` dictionary maps URL patterns ("proxy keys") to proxy URLs. HTTPX matches requested URLs against proxy keys to decide which proxy should be used, if any. Matching is done from most specific proxy keys (e.g. `https://<domain>:<port>`) to least specific ones (e.g. `https://`).

Refine docs phrasing on proxy routing (#1124)Florimond Mancabefore adoption0fb28e8

lines 427–429why, one step back
427
428HTTPX supports routing proxies based on **scheme**, **domain**, **port**, or a combination of these.429

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

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

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

line 431why, one step back
431

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

lines 432–433why, one step back
432Route everything through a proxy...
433

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

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

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

line 435why, one step back
435proxies = {

Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4

line 436why, one step back
436 "all://": "http://localhost:8030",

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

line 437why, one step back
437}

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 438–439why, one step back
438```
439

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

lines 440–445why, one step back
440#### Scheme routing
441442Route HTTP requests through one proxy, and HTTPS requests through another...443444```python445proxies = {

Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4

lines 446–447why, one step back
446 "http://": "http://localhost:8030",
447 "https://": "http://localhost:8031",

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

lines 448–511why, one step back
448}
449```450451#### Domain routing452453Proxy all requests on domain "example.com", let other requests pass through...454455```python456proxies = {457 "all://example.com": "http://localhost:8030",458}459```460461Proxy HTTP requests on domain "example.com", let HTTPS and other requests pass through...462463```python464proxies = {465 "http://example.com": "http://localhost:8030",466}467```468469Proxy all requests to "example.com" and its subdomains, let other requests pass through...470471```python472proxies = {473 "all://*example.com": "http://localhost:8030",474}475```476477Proxy all requests to strict subdomains of "example.com", let "example.com" and other requests pass through...478479```python480proxies = {481 "all://*.example.com": "http://localhost:8030",482}483```484485#### Port routing486487Proxy HTTPS requests on port 1234 to "example.com"...488489```python490proxies = {491 "https://example.com:1234": "http://localhost:8030",492}493```494495Proxy all requests on port 1234...496497```python498proxies = {499 "all://*:1234": "http://localhost:8030",500}501```502503#### No-proxy support504505It is also possible to define requests that _shouldn't_ be routed through proxies.506507To do so, pass `None` as the proxy URL. For example...508509```python510proxies = {511 # Route requests through a proxy by default...

Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4

line 512why, one step back
512 "all://": "http://localhost:8031",

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

lines 513–524why, one step back
513 # Except those for "example.com".
514 "all://example.com": None,515}516```517518#### Complex configuration example519520You can combine the routing features outlined above to build complex proxy routing configurations. For example...521522```python523proxies = {524 # Route all traffic through a proxy by default...

Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4

line 525why, one step back
525 "all://": "http://localhost:8030",

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

lines 526–539why, one step back
526 # But don't use proxies for HTTPS requests to "domain.io"...
527 "https://domain.io": None,528 # And use another proxy for requests to "example.com" and its subdomains...529 "all://*example.com": "http://localhost:8031",530 # And yet another proxy if HTTP is used,531 # and the "internal" subdomain on port 5550 is requested...532 "http://internal.example.com:5550": "http://localhost:8032",533}534```535536#### Environment variables537538HTTP proxying can also be configured through environment variables, although with less fine-grained control.539

Use relative links for interlinking markdown files in docs (#1390)Tom Christiebefore adoption0af6d9a

line 540why, one step back
540See documentation on [`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`](environment_variables.md#http_proxy-https_proxy-all_proxy) for more information.

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

lines 541–543why, one step back
541
542### Proxy mechanisms543

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

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

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

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

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

line 546why, one step back
546

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

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

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

line 548why, one step back
548

Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95

lines 549–584why, one step back
549In general, the flow for making an HTTP request through a proxy is as follows:
5505511. The client connects to the proxy (initial connection request).5521. The proxy somehow transfers data to the server on your behalf.553554How exactly step 2/ is performed depends on which of two proxying mechanisms is used:555556* **Forwarding**: the proxy makes the request for you, and sends back the response it obtained from the server.557* **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).558559#### Default behavior560561Given the technical definitions above, by default (and regardless of whether you're using an HTTP or HTTPS proxy), HTTPX will:562563* Use forwarding for HTTP requests.564* Use tunneling for HTTPS requests.565566This ensures that you can make HTTP and HTTPS requests in all cases (i.e. regardless of which type of proxy you're using).567568#### Forcing the proxy mechanism569570In most cases, the default behavior should work just fine as well as provide enough security.571572But 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...573574```python575# Route all requests through an HTTPS proxy, using tunneling only.576proxies = httpx.Proxy(577 url="https://localhost:8030",578 mode="TUNNEL_ONLY",579)580581with httpx.Client(proxies=proxies) as client:582 # This HTTP request will be tunneled instead of forwarded.583 r = client.get("http://example.com")584```

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

line 585why, one step back
585

Add troubleshooting guide, with initial proxies entries (#1435)Florimond Mancabefore adoption25781a7

lines 586–589why, one step back
586### Troubleshooting proxies
587588If you encounter issues when setting up proxies, please refer to our [Troubleshooting guide](troubleshooting.md#proxies).589

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 590–638why, one step back
590## Timeout Configuration
591592HTTPX is careful to enforce timeouts everywhere by default.593594The default behavior is to raise a `TimeoutException` after 5 seconds of595network inactivity.596597### Setting and disabling timeouts598599You can set timeouts for an individual request:600601```python602# Using the top-level API:603httpx.get('http://example.com/api/v1/example', timeout=10.0)604605# Using a client instance:606with httpx.Client() as client:607 client.get("http://example.com/api/v1/example", timeout=10.0)608```609610Or disable timeouts for an individual request:611612```python613# Using the top-level API:614httpx.get('http://example.com/api/v1/example', timeout=None)615616# Using a client instance:617with httpx.Client() as client:618 client.get("http://example.com/api/v1/example", timeout=None)619```620621### Setting a default timeout on a client622623You can set a timeout on a client instance, which results in the given624`timeout` being used as the default for requests made with this client:625626```python627client = httpx.Client() # Use a default 5s timeout everywhere.628client = httpx.Client(timeout=10.0) # Use a default 10s timeout everywhere.629client = httpx.Client(timeout=None) # Disable all timeouts by default.630```631632### Fine tuning the configuration633634HTTPX also allows you to specify the timeout behavior in more fine grained detail.635636There are four different types of timeouts that may occur. These are **connect**,637**read**, **write**, and **pool** timeouts.638

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

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

Tweak advanced timeouts docs (#1420)Florimond Mancabefore adoption584a405

line 640why, one step back
640a socket connection to the requested host is established. If HTTPX is unable to connect

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

line 641why, one step back
641within this time frame, a `ConnectTimeout` exception is raised.

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

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

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

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

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

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

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

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

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

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

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 649–651why, one step back
649a connection from the connection pool. If HTTPX is unable to acquire a connection
650within this time frame, a `PoolTimeout` exception is raised. A related651configuration here is the maximum number of allowable connections in the

Tweak advanced timeouts docs (#1420)Florimond Mancabefore adoption584a405

line 652why, one step back
652connection pool, which is configured by the `limits` argument.

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 653–657why, one step back
653
654You can configure the timeout behavior for any of these values...655656```python657# A client with a 60s timeout for connecting, and a 10s timeout elsewhere.

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

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

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 659–665why, one step back
659client = httpx.Client(timeout=timeout)
660661response = client.get('http://example.com/')662```663664## Pool limit configuration665

Rename PoolLimits to Limits (#1113)Florimond Mancabefore adoptionf67e925

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

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 668–669why, one step back
668
669- `max_keepalive`, number of allowable keep-alive connections, or `None` to always

Fix typo to match library default (#1535)Louis Maddoxbefore adoption68cf1ff

line 670why, one step back
670allow. (Defaults 20)

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 671–674why, one step back
671- `max_connections`, maximum number of allowable connections, or` None` for no limits.
672(Default 100)673674```python

update arg name to `max_keepalive_connections` (#1309)emlazzarinbefore adoption257b8fa

line 675why, one step back
675limits = httpx.Limits(max_keepalive_connections=5, max_connections=10)

Rename PoolLimits to Limits (#1113)Florimond Mancabefore adoptionf67e925

line 676why, one step back
676client = httpx.Client(limits=limits)

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 677–680why, one step back
677```
678679## Multipart file encoding680

Use relative links for interlinking markdown files in docs (#1390)Tom Christiebefore adoption0af6d9a

line 681why, one step back
681As mentioned in the [quickstart](quickstart.md#sending-multipart-file-uploads)

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 682–684why, one step back
682multipart file encoding is available by passing a dictionary with the
683name of the payloads as keys and either tuple of elements or a file-like object or a string as values.684

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 685why, one step back
685```pycon

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 686–709why, one step back
686>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}
687>>> r = httpx.post("https://httpbin.org/post", files=files)688>>> print(r.text)689{690 ...691 "files": {692 "upload-file": "<... binary content ...>"693 },694 ...695}696```697698More specifically, if a tuple is used as a value, it must have between 2 and 3 elements:699700- The first element is an optional file name which can be set to `None`.701- The second element may be a file-like object or a string which will be automatically702encoded in UTF-8.703- An optional third element can be used to specify the704[MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_Types)705of the file being uploaded. If not specified HTTPX will attempt to guess the MIME type based706on the file name, with unknown file extensions defaulting to "application/octet-stream".707If the file name is explicitly set to `None` then HTTPX will not include a content-type708MIME header field.709

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 710why, one step back
710```pycon

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 711–725why, one step back
711>>> files = {'upload-file': (None, 'text content', 'text/plain')}
712>>> r = httpx.post("https://httpbin.org/post", files=files)713>>> print(r.text)714{715 ...716 "files": {},717 "form": {718 "upload-file": "text-content"719 },720 ...721}722```723724!!! tip725 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.

Advanced transport docs (#1165)Tom Christiebefore adoption477824a

line 726why, one step back
726

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

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

Advanced transport docs (#1165)Tom Christiebefore adoption477824a

line 728why, one step back
728

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 729–730why, one step back
729You can also send multiple files in one go with a multiple file field form.
730To do that, pass a list of `(field, <file>)` items instead of a dictionary, allowing you to pass multiple items with the same `field`.

Advanced transport docs (#1165)Tom Christiebefore adoption477824a

line 731why, one step back
731For instance this request sends 2 files, `foo.png` and `bar.png` in one request on the `images` form field:

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

line 732why, one step back
732

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 733why, one step back
733```pycon

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 734–836why, one step back
734>>> files = [('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),
735 ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]736>>> r = httpx.post("https://httpbin.org/post", files=files)737```738739## Customizing authentication740741When 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...742743* A two-tuple of `username`/`password`, to be used with basic authentication.744* An instance of `httpx.BasicAuth()` or `httpx.DigestAuth()`.745* A callable, accepting a request and returning an authenticated request instance.746* A subclass of `httpx.Auth`.747748The 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...749750```python751class MyCustomAuth(httpx.Auth):752 def __init__(self, token):753 self.token = token754755 def auth_flow(self, request):756 # Send the request, with a custom `X-Authentication` header.757 request.headers['X-Authentication'] = self.token758 yield request759```760761If the auth flow requires more that one request, you can issue multiple yields, and obtain the response in each case...762763```python764class MyCustomAuth(httpx.Auth):765 def __init__(self, token):766 self.token = token767768 def auth_flow(self, request):769 response = yield request770 if response.status_code == 401:771 # If the server issues a 401 response then resend the request,772 # with a custom `X-Authentication` header.773 request.headers['X-Authentication'] = self.token774 yield request775```776777Custom 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.778779You will then be able to access `request.content` inside the `.auth_flow()` method.780781```python782class MyCustomAuth(httpx.Auth):783 requires_request_body = True784785 def __init__(self, token):786 self.token = token787788 def auth_flow(self, request):789 response = yield request790 if response.status_code == 401:791 # If the server issues a 401 response then resend the request,792 # with a custom `X-Authentication` header.793 request.headers['X-Authentication'] = self.sign_request(...)794 yield request795796 def sign_request(self, request):797 # Create a request signature, based on `request.method`, `request.url`,798 # `request.headers`, and `request.content`.799 ...800```801802Similarly, 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.803804```python805class MyCustomAuth(httpx.Auth):806 requires_response_body = True807808 def __init__(self, access_token, refresh_token, refresh_url):809 self.access_token = access_token810 self.refresh_token = refresh_token811 self.refresh_url = refresh_url812813 def auth_flow(self, request):814 request.headers["X-Authentication"] = self.access_token815 response = yield request816817 if response.status_code == 401:818 # If the server issues a 401 response, then issue a request to819 # refresh tokens, and resend the request.820 refresh_response = yield self.build_refresh_request()821 self.update_tokens(refresh_response)822823 request.headers["X-Authentication"] = self.access_token824 yield request825826 def build_refresh_request(self):827 # Return an `httpx.Request` for refreshing tokens.828 ...829830 def update_tokens(self, response):831 # Update the `.access_token` and `.refresh_token` tokens832 # based on a refresh response.833 data = response.json()834 ...835```836

Add support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee

lines 837–885why, one step back
837If you _do_ need to perform I/O other than HTTP requests, such as accessing a disk-based cache, or you need to use concurrency primitives, such as locks, then you should override `.sync_auth_flow()` and `.async_auth_flow()` (instead of `.auth_flow()`). The former will be used by `httpx.Client`, while the latter will be used by `httpx.AsyncClient`.
838839```python840import asyncio841import threading842import httpx843844845class MyCustomAuth(httpx.Auth):846 def __init__(self):847 self._sync_lock = threading.RLock()848 self._async_lock = asyncio.Lock()849850 def sync_get_token(self):851 with self._sync_lock:852 ...853854 def sync_auth_flow(self, request):855 token = self.sync_get_token()856 request.headers["Authorization"] = f"Token {token}"857 yield request858859 async def async_get_token(self):860 async with self._async_lock:861 ...862863 async def async_auth_flow(self, request):864 token = await self.async_get_token()865 request.headers["Authorization"] = f"Token {token}"866 yield request867```868869If you only want to support one of the two methods, then you should still override it, but raise an explicit `RuntimeError`.870871```python872import httpx873import sync_only_library874875876class MyCustomAuth(httpx.Auth):877 def sync_auth_flow(self, request):878 token = sync_only_library.get_token(...)879 request.headers["Authorization"] = f"Token {token}"880 yield request881882 async def async_auth_flow(self, request):883 raise RuntimeError("Cannot use a sync authentication class with httpx.AsyncClient")884```885

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 886–903why, one step back
886## SSL certificates
887888When 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).889890### Changing the verification defaults891892By 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.893894If you'd like to use a custom CA bundle, you can use the `verify` parameter.895896```python897import httpx898899r = httpx.get("https://example.org", verify="path/to/client.pem")900```901902Alternatively, you can pass a standard library `ssl.SSLContext`.903

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 904why, one step back
904```pycon

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 905–912why, one step back
905>>> import ssl
906>>> import httpx907>>> context = ssl.create_default_context()908>>> context.load_verify_locations(cafile="/tmp/client.pem")909>>> httpx.get('https://example.org', verify=context)910<Response [200 OK]>911```912

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

lines 913–914why, one step back
913We also include a helper function for creating properly configured `SSLContext` instances.
914

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 915why, one step back
915```pycon

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

lines 916–918why, one step back
916>>> context = httpx.create_ssl_context()
917```918

Advanced transport docs (#1165)Tom Christiebefore adoption477824a

lines 919–920why, one step back
919The `create_ssl_context` function accepts the same set of SSL configuration arguments
920(`trust_env`, `verify`, `cert` and `http2` arguments)

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

lines 921–922why, one step back
921as `httpx.Client` or `httpx.AsyncClient`
922

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 923why, one step back
923```pycon

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

lines 924–929why, one step back
924>>> import httpx
925>>> context = httpx.create_ssl_context(verify="/tmp/client.pem")926>>> httpx.get('https://example.org', verify=context)927<Response [200 OK]>928```929

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 930–947why, one step back
930Or you can also disable the SSL verification entirely, which is _not_ recommended.
931932```python933import httpx934935r = httpx.get("https://example.org", verify=False)936```937938### SSL configuration on client instances939940If you're using a `Client()` instance, then you should pass any SSL settings when instantiating the client.941942```python943client = httpx.Client(verify=False)944```945946The `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.947

Added docs for using client-side ssl certificates (#1570)Hemanth kumarbefore adoption535df6c

lines 948–973why, one step back
948### Client Side Certificates
949950You can also specify a local cert to use as a client-side certificate, either a path to an SSL certificate file, or two-tuple of (certificate file, key file), or a three-tuple of (certificate file, key file, password)951952```python953import httpx954955r = httpx.get("https://example.org", cert="path/to/client.pem")956```957958Alternatively,959960```pycon961>>> cert = ("path/to/client.pem", "path/to/client.key")962>>> httpx.get("https://example.org", cert=cert)963<Response [200 OK]>964```965966or967968```pycon969>>> cert = ("path/to/client.pem", "path/to/client.key", "password")970>>> httpx.get("https://example.org", cert=cert)971<Response [200 OK]>972```973

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 974–983why, one step back
974### Making HTTPS requests to a local server
975976When making requests to local servers, such as a development server running on `localhost`, you will typically be using unencrypted HTTP connections.977978If 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:9799801. Use [trustme-cli](https://github.com/sethmlarson/trustme-cli/) to generate a pair of server key/cert files, and a client cert file.9811. 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.)9821. Tell HTTPX to use the certificates stored in `client.pem`:983

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 984why, one step back
984```pycon

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 985–996why, one step back
985>>> import httpx
986>>> r = httpx.get("https://localhost:8000", verify="/tmp/client.pem")987>>> r988Response <200 OK>989```990991## Custom Transports992993HTTPX's `Client` also accepts a `transport` argument. This argument allows you994to provide a custom Transport object that will be used to perform the actual995sending of the requests.996

Drop urllib3 in favor of public gist (#1182)Florimond Mancabefore adoption8fa8765

lines 997–998why, one step back
997### Usage
998

Advanced transport docs (#1165)Tom Christiebefore adoption477824a

line 999why, one step back
999For some advanced configuration you might need to instantiate a transport

Add `HTTPTransport` and `AsyncHTTPTransport` (#1399)Tom Christiebefore adoption89fb0cb

lines 1000–1001why, one step back
1000class directly, and pass it to the client instance. One example is the
1001`local_address` configuration which is only available via this low-level API.

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

line 1002why, one step back
1002

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 1003why, one step back
1003```pycon

Add `HTTPTransport` and `AsyncHTTPTransport` (#1399)Tom Christiebefore adoption89fb0cb

lines 1004–1005why, one step back
1004>>> import httpx
1005>>> transport = httpx.HTTPTransport(local_address="0.0.0.0")

Advanced transport docs (#1165)Tom Christiebefore adoption477824a

lines 1006–1008why, one step back
1006>>> client = httpx.Client(transport=transport)
1007```1008

Add `HTTPTransport` and `AsyncHTTPTransport` (#1399)Tom Christiebefore adoption89fb0cb

line 1009why, one step back
1009Connection retries are also available via this interface.

Document Unix Domain Socket usage (#1186)Florimond Mancabefore adoption34ba0e1

line 1010why, one step back
1010

Add `HTTPTransport` and `AsyncHTTPTransport` (#1399)Tom Christiebefore adoption89fb0cb

lines 1011–1013why, one step back
1011```pycon
1012>>> import httpx1013>>> transport = httpx.HTTPTransport(retries=1)

Document Unix Domain Socket usage (#1186)Florimond Mancabefore adoption34ba0e1

line 1014why, one step back
1014>>> client = httpx.Client(transport=transport)

Add `HTTPTransport` and `AsyncHTTPTransport` (#1399)Tom Christiebefore adoption89fb0cb

lines 1015–1024why, one step back
1015```
10161017Similarly, instantiating a transport directly provides a `uds` option for1018connecting via a Unix Domain Socket that is only available via this low-level API:10191020```pycon1021>>> import httpx1022>>> # Connect to the Docker API via a Unix Socket.1023>>> transport = httpx.HTTPTransport(uds="/var/run/docker.sock")1024>>> client = httpx.Client(transport=transport)

Document Unix Domain Socket usage (#1186)Florimond Mancabefore adoption34ba0e1

lines 1025–1029why, one step back
1025>>> response = client.get("http://docker/info")
1026>>> response.json()1027{"ID": "...", "Containers": 4, "Images": 74, ...}1028```1029

Drop urllib3 in favor of public gist (#1182)Florimond Mancabefore adoption8fa8765

line 1030why, one step back
1030### urllib3 transport

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

line 1031why, one step back
1031

Drop urllib3 in favor of public gist (#1182)Florimond Mancabefore adoption8fa8765

lines 1032–1033why, one step back
1032This [public gist](https://gist.github.com/florimondmanca/d56764d78d748eb9f73165da388e546e) provides a transport that uses the excellent [`urllib3` library](https://urllib3.readthedocs.io/en/latest/), and can be used with the sync `Client`...
1033

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 1034why, one step back
1034```pycon

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

line 1035why, one step back
1035>>> import httpx

Drop urllib3 in favor of public gist (#1182)Florimond Mancabefore adoption8fa8765

lines 1036–1037why, one step back
1036>>> from urllib3_transport import URLLib3Transport
1037>>> client = httpx.Client(transport=URLLib3Transport())

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 1038–1041why, one step back
1038>>> client.get("https://example.org")
1039<Response [200 OK]>1040```1041

Drop urllib3 in favor of public gist (#1182)Florimond Mancabefore adoption8fa8765

line 1042why, one step back
1042### Writing custom transports

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

line 1043why, one step back
1043

Transport API (#1522)Tom Christiebefore adoption1a6e254

lines 1044–1048why, one step back
1044A transport instance must implement the low-level Transport API, which deals
1045with sending a single request, and returning a response. You should either1046subclass `httpx.BaseTransport` to implement a transport to use with `Client`,1047or subclass `httpx.AsyncBaseTransport` to implement a transport to1048use with `AsyncClient`.

Advanced transport docs (#1165)Tom Christiebefore adoption477824a

line 1049why, one step back
1049

Transport API (#1522)Tom Christiebefore adoption1a6e254

lines 1050–1057why, one step back
1050At the layer of the transport API we're using plain primitives.
1051No `Request` or `Response` models, no fancy `URL` or `Header` handling.1052This strict point of cut-off provides a clear design separation between the1053HTTPX API, and the low-level network handling.10541055See the `handle_request` and `handle_async_request` docstrings for more details1056on the specifics of the Transport API.1057

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 1058–1061why, one step back
1058A complete example of a custom transport implementation would be:
10591060```python1061import json

Transport API (#1522)Tom Christiebefore adoption1a6e254

line 1062why, one step back
1062import httpx

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 1063–1064why, one step back
1063
1064

Transport API (#1522)Tom Christiebefore adoption1a6e254

line 1065why, one step back
1065class HelloWorldTransport(httpx.BaseTransport):

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

line 1066why, one step back
1066 """

Advanced transport docs (#1165)Tom Christiebefore adoption477824a

line 1067why, one step back
1067 A mock transport that always returns a JSON "Hello, world!" response.

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 1068–1069why, one step back
1068 """
1069

Transport API (#1522)Tom Christiebefore adoption1a6e254

line 1070why, one step back
1070 def handle_request(self, method, url, headers, stream, extensions):

Advanced transport docs (#1165)Tom Christiebefore adoption477824a

lines 1071–1072why, one step back
1071 message = {"text": "Hello, world!"}
1072 content = json.dumps(message).encode("utf-8")

Transport API (#1522)Tom Christiebefore adoption1a6e254

line 1073why, one step back
1073 stream = [content]

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

line 1074why, one step back
1074 headers = [(b"content-type", b"application/json")]

Transport API (#1522)Tom Christiebefore adoption1a6e254

lines 1075–1076why, one step back
1075 extensions = {}
1076 return 200, headers, stream, extensions

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

lines 1077–1080why, one step back
1077```
10781079Which we can use in the same way:1080

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 1081why, one step back
1081```pycon

Advanced transport docs (#1165)Tom Christiebefore adoption477824a

lines 1082–1084why, one step back
1082>>> import httpx
1083>>> client = httpx.Client(transport=HelloWorldTransport())1084>>> response = client.get("https://example.org/")

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

line 1085why, one step back
1085>>> response.json()

Advanced transport docs (#1165)Tom Christiebefore adoption477824a

line 1086why, one step back
1086{"text": "Hello, world!"}

Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f

lines 1087–1088why, one step back
1087```
1088

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

lines 1089–1113why, one step back
1089### Mock transports
10901091During testing it can often be useful to be able to mock out a transport,1092and return pre-determined responses, rather than making actual network requests.10931094The `httpx.MockTransport` class accepts a handler function, which can be used1095to map requests onto pre-determined responses:10961097```python1098def handler(request):1099 return httpx.Response(200, json={"text": "Hello, world!"})110011011102# Switch to a mock transport, if the TESTING environment variable is set.1103if os.environ['TESTING'].upper() == "TRUE":1104 transport = httpx.MockTransport(handler)1105else:1106 transport = httpx.HTTPTransport()11071108client = httpx.Client(transport=transport)1109```11101111For more advanced use-cases you might want to take a look at either [the third-party1112mocking library, RESPX](https://lundberg.github.io/respx/), or the [pytest-httpx library](https://github.com/Colin-b/pytest_httpx).1113

Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f

lines 1114–1122why, one step back
1114### Mounting transports
11151116You can also mount transports against given schemes or domains, to control1117which transport an outgoing request should be routed via, with [the same style1118used for specifying proxy routing](#routing).11191120```python1121import httpx1122

Transport API (#1522)Tom Christiebefore adoption1a6e254

line 1123why, one step back
1123class HTTPSRedirectTransport(httpx.BaseTransport):

Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f

lines 1124–1127why, one step back
1124 """
1125 A transport that always redirects to HTTPS.1126 """1127

Transport API (#1522)Tom Christiebefore adoption1a6e254

line 1128why, one step back
1128 def handle_request(self, method, url, headers, stream, extensions):

Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f

lines 1129–1133why, one step back
1129 scheme, host, port, path = url
1130 if port is None:1131 location = b"https://%s%s" % (host, path)1132 else:1133 location = b"https://%s:%d%s" % (host, port, path)

Transport API (#1522)Tom Christiebefore adoption1a6e254

line 1134why, one step back
1134 stream = [b""]

Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f

line 1135why, one step back
1135 headers = [(b"location", location)]

Transport API (#1522)Tom Christiebefore adoption1a6e254

lines 1136–1137why, one step back
1136 extensions = {}
1137 return 303, headers, stream, extensions

Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f

lines 1138–1145why, one step back
1138
11391140# A client where any `http` requests are always redirected to `https`1141mounts = {'http://': HTTPSRedirectTransport()}1142client = httpx.Client(mounts=mounts)1143```11441145A couple of other sketches of how you might take advantage of mounted transports...

Add `HTTPTransport` and `AsyncHTTPTransport` (#1399)Tom Christiebefore adoption89fb0cb

lines 1146–1155why, one step back
1146
1147Disabling HTTP/2 on a single given domain...11481149```python1150mounts = {1151 "all://": httpx.HTTPTransport(http2=True),1152 "all://*example.org": httpx.HTTPTransport()1153}1154client = httpx.Client(mounts=mounts)1155```

Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f

lines 1156–1161why, one step back
1156
1157Mocking requests to a given domain:11581159```python1160# All requests to "example.org" should be mocked out.1161# Other requests occur as usual.

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

lines 1162–1165why, one step back
1162def handler(request):
1163 return httpx.Response(200, json={"text": "Hello, World!"})11641165mounts = {"all://example.org": httpx.MockTransport(handler)}

Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f

lines 1166–1174why, one step back
1166client = httpx.Client(mounts=mounts)
1167```11681169Adding support for custom schemes:11701171```python1172# Support URLs like "file:///Users/sylvia_green/websites/new_client/index.html"1173mounts = {"file://": FileSystemTransport()}1174client = httpx.Client(mounts=mounts)

URL.port becomes Optional[int] (#1080)Tom Christiebefore adoptionc089480

line 1175why, one step back
1175```