Skip to content
Myr

advanced.md

This file

Path

docs/advanced.md

1,184 lines · 39.8 KiB · Markdown

Last changed by

Add netrc environment variable into the documentation (#1675)Meibefore adoption604d09d

History of this file

Take it

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

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.

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

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.

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

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.

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

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:

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

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–230why, 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:230

docs: slightly clarify event hooks (#1645)K900before adoption776dbb5

lines 231–232why, one step back
231* `request` - Called after a request is fully prepared, but before it is sent to the network. Passed the `request` instance.
232* `response` - Called after the response has been fetched from the network, but before it is returned to the caller. Passed the `response` instance.

Event hooks (#1246)Tom Christiebefore adoption54f7708

line 233why, one step back
233

docs: slightly clarify event hooks (#1645)K900before adoption776dbb5

line 234why, one step back
234These allow you to install client-wide functionality such as logging, monitoring or tracing.

Event hooks (#1246)Tom Christiebefore adoption54f7708

lines 235–255why, one step back
235
236```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]})

docs: slightly clarify event hooks (#1645)K900before adoption776dbb5

lines 256–264why, one step back
256```
257258The hooks are also allowed to modify `request` and `response` objects.259260```python261def add_timestamp(request):262 request.headers['x-request-timestamp'] = datetime.now(tz=datetime.utc).isoformat()263 264client = httpx.Client(event_hooks={'request': [add_timestamp]})

Event hooks (#1246)Tom Christiebefore adoption54f7708

lines 265–276why, one step back
265```
266267Event hooks must always be set as a **list of callables**, and you may register268multiple event hooks for each type of event.269270As well as being able to set event hooks on instantiating the client, there271is also an `.event_hooks` property, that allows you to inspect and modify272the installed hooks.273274```python275client = httpx.Client()276client.event_hooks['request'] = [log_request]

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

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

Event hooks (#1246)Tom Christiebefore adoption54f7708

lines 278–284why, one step back
278```
279280!!! note281 If you are using HTTPX's async support, then you need to be aware that282 hooks registered with `httpx.AsyncClient` MUST be async functions,283 rather than plain functions.284

Add progress to streaming download (#1268)cdelerbefore adoptioned16eb3

lines 285–310why, one step back
285## Monitoring download progress
286287If you need to monitor download progress of large responses, you can use response streaming and inspect the `response.num_bytes_downloaded` property.288289This 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.290291For 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…292293```python294import tempfile295296import httpx297from tqdm import tqdm298299with tempfile.NamedTemporaryFile() as download_file:300 url = "https://speed.hetzner.de/100MB.bin"301 with httpx.stream("GET", url) as response:302 total = int(response.headers["Content-Length"])303304 with tqdm(total=total, unit_scale=True, unit_divisor=1024, unit="B") as progress:305 num_bytes_downloaded = response.num_bytes_downloaded306 for chunk in response.iter_bytes():307 download_file.write(chunk)308 progress.update(response.num_bytes_downloaded - num_bytes_downloaded)309 num_bytes_downloaded = response.num_bytes_downloaded310```

Progress examples (#1272)Tom Christiebefore adoption59074c7

lines 311–338why, one step back
311
312![tqdm progress bar](img/tqdm-progress.gif)313314Or an alternate example, this time using the [`rich`](https://github.com/willmcgugan/rich) library…315316```python317import tempfile318import httpx319import rich.progress320321with tempfile.NamedTemporaryFile() as download_file:322 url = "https://speed.hetzner.de/100MB.bin"323 with httpx.stream("GET", url) as response:324 total = int(response.headers["Content-Length"])325326 with rich.progress.Progress(327 "[progress.percentage]{task.percentage:>3.0f}%",328 rich.progress.BarColumn(bar_width=None),329 rich.progress.DownloadColumn(),330 rich.progress.TransferSpeedColumn(),331 ) as progress:332 download_task = progress.add_task("Download", total=total)333 for chunk in response.iter_bytes():334 download_file.write(chunk)335 progress.update(download_task, completed=response.num_bytes_downloaded)336```337338![rich progress bar](img/rich-progress.gif)

Add progress to streaming download (#1268)cdelerbefore adoptioned16eb3

line 339why, one step back
339

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 340–350why, one step back
340## .netrc Support
341342HTTPX supports .netrc file. In `trust_env=True` cases, if auth parameter is343not defined, HTTPX tries to add auth into request's header from .netrc file.344345!!! note346 The NETRC file is cached across requests made by a client.347 If you need to refresh the cache (e.g. because the NETRC file has changed),348 you should create a new client or restart the interpreter.349350As default `trust_env` is true. To set false:

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

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 352–358why, one step back
352>>> httpx.get('https://example.org/', trust_env=False)
353```354355If `NETRC` environment is empty, HTTPX tries to use default files.356(`~/.netrc`, `~/_netrc`)357358To change `NETRC` environment:

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

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 360–372why, one step back
360>>> import os
361>>> os.environ["NETRC"] = "my_default_folder/.my_netrc"362```363364.netrc file content example:365```366machine netrcexample.org367login example-username368password example-password369370...371```372

Add netrc environment variable into the documentation (#1675)Meibefore adoption604d09d

line 373why, one step back
373When using `Client` instances, `trust_env` should be set on the client itself, rather than on the request methods:

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 374–380why, one step back
374
375```python376client = httpx.Client(trust_env=False)377```378379## HTTP Proxying380

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

line 381why, one step back
381HTTPX 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=...)`.

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 382–548why, one step back
382
383_Note: SOCKS proxies are not supported yet._384385<div align="center">386 <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/27/Open_proxy_h2g2bob.svg/480px-Open_proxy_h2g2bob.svg.png"/>387 <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>388</div>389390### Example391392To route all traffic (HTTP and HTTPS) to a proxy located at `http://localhost:8030`, pass the proxy URL to the client...393394```python395with httpx.Client(proxies="http://localhost:8030") as client:396 ...397```398399For 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:400401```python402proxies = {403 "http://": "http://localhost:8030",404 "https://": "http://localhost:8031",405}406407with httpx.Client(proxies=proxies) as client:408 ...409```410411For detailed information about proxy routing, see the [Routing](#routing) section.412413!!! tip "Gotcha"414 In most cases, the proxy URL for the `https://` key _should_ use the `http://` scheme (that's not a typo!).415416 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.417418 For more information, see [FORWARD vs TUNNEL](#forward-vs-tunnel).419420### Authentication421422Proxy credentials can be passed as the `userinfo` section of the proxy URL. For example:423424```python425proxies = {426 "http://": "http://username:password@localhost:8030",427 # ...428}429```430431### Routing432433HTTPX provides fine-grained controls for deciding which requests should go through a proxy, and which shouldn't. This process is known as proxy routing.434435The `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://`).436437HTTPX supports routing proxies based on **scheme**, **domain**, **port**, or a combination of these.438439#### Wildcard routing440441Route everything through a proxy...442443```python444proxies = {445 "all://": "http://localhost:8030",446}447```448449#### Scheme routing450451Route HTTP requests through one proxy, and HTTPS requests through another...452453```python454proxies = {455 "http://": "http://localhost:8030",456 "https://": "http://localhost:8031",457}458```459460#### Domain routing461462Proxy all requests on domain "example.com", let other requests pass through...463464```python465proxies = {466 "all://example.com": "http://localhost:8030",467}468```469470Proxy HTTP requests on domain "example.com", let HTTPS and other requests pass through...471472```python473proxies = {474 "http://example.com": "http://localhost:8030",475}476```477478Proxy all requests to "example.com" and its subdomains, let other requests pass through...479480```python481proxies = {482 "all://*example.com": "http://localhost:8030",483}484```485486Proxy all requests to strict subdomains of "example.com", let "example.com" and other requests pass through...487488```python489proxies = {490 "all://*.example.com": "http://localhost:8030",491}492```493494#### Port routing495496Proxy HTTPS requests on port 1234 to "example.com"...497498```python499proxies = {500 "https://example.com:1234": "http://localhost:8030",501}502```503504Proxy all requests on port 1234...505506```python507proxies = {508 "all://*:1234": "http://localhost:8030",509}510```511512#### No-proxy support513514It is also possible to define requests that _shouldn't_ be routed through proxies.515516To do so, pass `None` as the proxy URL. For example...517518```python519proxies = {520 # Route requests through a proxy by default...521 "all://": "http://localhost:8031",522 # Except those for "example.com".523 "all://example.com": None,524}525```526527#### Complex configuration example528529You can combine the routing features outlined above to build complex proxy routing configurations. For example...530531```python532proxies = {533 # Route all traffic through a proxy by default...534 "all://": "http://localhost:8030",535 # But don't use proxies for HTTPS requests to "domain.io"...536 "https://domain.io": None,537 # And use another proxy for requests to "example.com" and its subdomains...538 "all://*example.com": "http://localhost:8031",539 # And yet another proxy if HTTP is used,540 # and the "internal" subdomain on port 5550 is requested...541 "http://internal.example.com:5550": "http://localhost:8032",542}543```544545#### Environment variables546547HTTP proxying can also be configured through environment variables, although with less fine-grained control.548

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

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 550–594why, one step back
550
551### Proxy mechanisms552553!!! note554 This section describes **advanced** proxy concepts and functionality.555556#### FORWARD vs TUNNEL557558In general, the flow for making an HTTP request through a proxy is as follows:5595601. The client connects to the proxy (initial connection request).5611. The proxy somehow transfers data to the server on your behalf.562563How exactly step 2/ is performed depends on which of two proxying mechanisms is used:564565* **Forwarding**: the proxy makes the request for you, and sends back the response it obtained from the server.566* **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).567568#### Default behavior569570Given the technical definitions above, by default (and regardless of whether you're using an HTTP or HTTPS proxy), HTTPX will:571572* Use forwarding for HTTP requests.573* Use tunneling for HTTPS requests.574575This ensures that you can make HTTP and HTTPS requests in all cases (i.e. regardless of which type of proxy you're using).576577#### Forcing the proxy mechanism578579In most cases, the default behavior should work just fine as well as provide enough security.580581But 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...582583```python584# Route all requests through an HTTPS proxy, using tunneling only.585proxies = httpx.Proxy(586 url="https://localhost:8030",587 mode="TUNNEL_ONLY",588)589590with httpx.Client(proxies=proxies) as client:591 # This HTTP request will be tunneled instead of forwarded.592 r = client.get("http://example.com")593```594

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

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 599–648why, one step back
599## Timeout Configuration
600601HTTPX is careful to enforce timeouts everywhere by default.602603The default behavior is to raise a `TimeoutException` after 5 seconds of604network inactivity.605606### Setting and disabling timeouts607608You can set timeouts for an individual request:609610```python611# Using the top-level API:612httpx.get('http://example.com/api/v1/example', timeout=10.0)613614# Using a client instance:615with httpx.Client() as client:616 client.get("http://example.com/api/v1/example", timeout=10.0)617```618619Or disable timeouts for an individual request:620621```python622# Using the top-level API:623httpx.get('http://example.com/api/v1/example', timeout=None)624625# Using a client instance:626with httpx.Client() as client:627 client.get("http://example.com/api/v1/example", timeout=None)628```629630### Setting a default timeout on a client631632You can set a timeout on a client instance, which results in the given633`timeout` being used as the default for requests made with this client:634635```python636client = httpx.Client() # Use a default 5s timeout everywhere.637client = httpx.Client(timeout=10.0) # Use a default 10s timeout everywhere.638client = httpx.Client(timeout=None) # Disable all timeouts by default.639```640641### Fine tuning the configuration642643HTTPX also allows you to specify the timeout behavior in more fine grained detail.644645There are four different types of timeouts that may occur. These are **connect**,646**read**, **write**, and **pool** timeouts.647648* The **connect** timeout specifies the maximum amount of time to wait until

Tweak advanced timeouts docs (#1420)Florimond Mancabefore adoption584a405

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 650–660why, one step back
650within this time frame, a `ConnectTimeout` exception is raised.
651* The **read** timeout specifies the maximum duration to wait for a chunk of652data to be received (for example, a chunk of the response body). If HTTPX is653unable to receive data within this time frame, a `ReadTimeout` exception is raised.654* The **write** timeout specifies the maximum duration to wait for a chunk of655data to be sent (for example, a chunk of the request body). If HTTPX is unable656to send data within this time frame, a `WriteTimeout` exception is raised.657* The **pool** timeout specifies the maximum duration to wait for acquiring658a connection from the connection pool. If HTTPX is unable to acquire a connection659within this time frame, a `PoolTimeout` exception is raised. A related660configuration here is the maximum number of allowable connections in the

Tweak advanced timeouts docs (#1420)Florimond Mancabefore adoption584a405

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 662–678why, one step back
662
663You can configure the timeout behavior for any of these values...664665```python666# A client with a 60s timeout for connecting, and a 10s timeout elsewhere.667timeout = httpx.Timeout(10.0, connect=60.0)668client = httpx.Client(timeout=timeout)669670response = client.get('http://example.com/')671```672673## Pool limit configuration674675You can control the connection pool size using the `limits` keyword676argument on the client. It takes instances of `httpx.Limits` which define:677678- `max_keepalive`, number of allowable keep-alive connections, or `None` to always

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

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 680–683why, one step back
680- `max_connections`, maximum number of allowable connections, or` None` for no limits.
681(Default 100)682683```python

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

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 685–689why, one step back
685client = httpx.Client(limits=limits)
686```687688## Multipart file encoding689

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

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

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

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

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 695–718why, one step back
695>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}
696>>> r = httpx.post("https://httpbin.org/post", files=files)697>>> print(r.text)698{699 ...700 "files": {701 "upload-file": "<... binary content ...>"702 },703 ...704}705```706707More specifically, if a tuple is used as a value, it must have between 2 and 3 elements:708709- The first element is an optional file name which can be set to `None`.710- The second element may be a file-like object or a string which will be automatically711encoded in UTF-8.712- An optional third element can be used to specify the713[MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_Types)714of the file being uploaded. If not specified HTTPX will attempt to guess the MIME type based715on the file name, with unknown file extensions defaulting to "application/octet-stream".716If the file name is explicitly set to `None` then HTTPX will not include a content-type717MIME header field.718

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

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 720–734why, one step back
720>>> files = {'upload-file': (None, 'text content', 'text/plain')}
721>>> r = httpx.post("https://httpbin.org/post", files=files)722>>> print(r.text)723{724 ...725 "files": {},726 "form": {727 "upload-file": "text-content"728 },729 ...730}731```732733!!! tip734 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 735why, one step back
735

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

line 736why, one step back
736 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 737why, one step back
737

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 738–739why, one step back
738You can also send multiple files in one go with a multiple file field form.
739To 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 740why, one step back
740For instance this request sends 2 files, `foo.png` and `bar.png` in one request on the `images` form field:

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

line 741why, one step back
741

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

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 743–845why, one step back
743>>> files = [('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),
744 ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]745>>> r = httpx.post("https://httpbin.org/post", files=files)746```747748## Customizing authentication749750When 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...751752* A two-tuple of `username`/`password`, to be used with basic authentication.753* An instance of `httpx.BasicAuth()` or `httpx.DigestAuth()`.754* A callable, accepting a request and returning an authenticated request instance.755* A subclass of `httpx.Auth`.756757The 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...758759```python760class MyCustomAuth(httpx.Auth):761 def __init__(self, token):762 self.token = token763764 def auth_flow(self, request):765 # Send the request, with a custom `X-Authentication` header.766 request.headers['X-Authentication'] = self.token767 yield request768```769770If the auth flow requires more that one request, you can issue multiple yields, and obtain the response in each case...771772```python773class MyCustomAuth(httpx.Auth):774 def __init__(self, token):775 self.token = token776777 def auth_flow(self, request):778 response = yield request779 if response.status_code == 401:780 # If the server issues a 401 response then resend the request,781 # with a custom `X-Authentication` header.782 request.headers['X-Authentication'] = self.token783 yield request784```785786Custom 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.787788You will then be able to access `request.content` inside the `.auth_flow()` method.789790```python791class MyCustomAuth(httpx.Auth):792 requires_request_body = True793794 def __init__(self, token):795 self.token = token796797 def auth_flow(self, request):798 response = yield request799 if response.status_code == 401:800 # If the server issues a 401 response then resend the request,801 # with a custom `X-Authentication` header.802 request.headers['X-Authentication'] = self.sign_request(...)803 yield request804805 def sign_request(self, request):806 # Create a request signature, based on `request.method`, `request.url`,807 # `request.headers`, and `request.content`.808 ...809```810811Similarly, 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.812813```python814class MyCustomAuth(httpx.Auth):815 requires_response_body = True816817 def __init__(self, access_token, refresh_token, refresh_url):818 self.access_token = access_token819 self.refresh_token = refresh_token820 self.refresh_url = refresh_url821822 def auth_flow(self, request):823 request.headers["X-Authentication"] = self.access_token824 response = yield request825826 if response.status_code == 401:827 # If the server issues a 401 response, then issue a request to828 # refresh tokens, and resend the request.829 refresh_response = yield self.build_refresh_request()830 self.update_tokens(refresh_response)831832 request.headers["X-Authentication"] = self.access_token833 yield request834835 def build_refresh_request(self):836 # Return an `httpx.Request` for refreshing tokens.837 ...838839 def update_tokens(self, response):840 # Update the `.access_token` and `.refresh_token` tokens841 # based on a refresh response.842 data = response.json()843 ...844```845

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

lines 846–894why, one step back
846If 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`.
847848```python849import asyncio850import threading851import httpx852853854class MyCustomAuth(httpx.Auth):855 def __init__(self):856 self._sync_lock = threading.RLock()857 self._async_lock = asyncio.Lock()858859 def sync_get_token(self):860 with self._sync_lock:861 ...862863 def sync_auth_flow(self, request):864 token = self.sync_get_token()865 request.headers["Authorization"] = f"Token {token}"866 yield request867868 async def async_get_token(self):869 async with self._async_lock:870 ...871872 async def async_auth_flow(self, request):873 token = await self.async_get_token()874 request.headers["Authorization"] = f"Token {token}"875 yield request876```877878If you only want to support one of the two methods, then you should still override it, but raise an explicit `RuntimeError`.879880```python881import httpx882import sync_only_library883884885class MyCustomAuth(httpx.Auth):886 def sync_auth_flow(self, request):887 token = sync_only_library.get_token(...)888 request.headers["Authorization"] = f"Token {token}"889 yield request890891 async def async_auth_flow(self, request):892 raise RuntimeError("Cannot use a sync authentication class with httpx.AsyncClient")893```894

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 895–912why, one step back
895## SSL certificates
896897When 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).898899### Changing the verification defaults900901By 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.902903If you'd like to use a custom CA bundle, you can use the `verify` parameter.904905```python906import httpx907908r = httpx.get("https://example.org", verify="path/to/client.pem")909```910911Alternatively, you can pass a standard library `ssl.SSLContext`.912

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

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 914–923why, one step back
914>>> import ssl
915>>> import httpx916>>> context = ssl.create_default_context()917>>> context.load_verify_locations(cafile="/tmp/client.pem")918>>> httpx.get('https://example.org', verify=context)919<Response [200 OK]>920```921922We also include a helper function for creating properly configured `SSLContext` instances.923

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

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 925–927why, one step back
925>>> context = httpx.create_ssl_context()
926```927

Advanced transport docs (#1165)Tom Christiebefore adoption477824a

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 930–931why, one step back
930as `httpx.Client` or `httpx.AsyncClient`
931

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

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 933–956why, one step back
933>>> import httpx
934>>> context = httpx.create_ssl_context(verify="/tmp/client.pem")935>>> httpx.get('https://example.org', verify=context)936<Response [200 OK]>937```938939Or you can also disable the SSL verification entirely, which is _not_ recommended.940941```python942import httpx943944r = httpx.get("https://example.org", verify=False)945```946947### SSL configuration on client instances948949If you're using a `Client()` instance, then you should pass any SSL settings when instantiating the client.950951```python952client = httpx.Client(verify=False)953```954955The `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.956

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

lines 957–982why, one step back
957### Client Side Certificates
958959You 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)960961```python962import httpx963964r = httpx.get("https://example.org", cert="path/to/client.pem")965```966967Alternatively,968969```pycon970>>> cert = ("path/to/client.pem", "path/to/client.key")971>>> httpx.get("https://example.org", cert=cert)972<Response [200 OK]>973```974975or976977```pycon978>>> cert = ("path/to/client.pem", "path/to/client.key", "password")979>>> httpx.get("https://example.org", cert=cert)980<Response [200 OK]>981```982

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

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

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

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 994–1005why, one step back
994>>> import httpx
995>>> r = httpx.get("https://localhost:8000", verify="/tmp/client.pem")996>>> r997Response <200 OK>998```9991000## Custom Transports10011002HTTPX's `Client` also accepts a `transport` argument. This argument allows you1003to provide a custom Transport object that will be used to perform the actual1004sending of the requests.1005

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

lines 1006–1007why, one step back
1006### Usage
1007

Advanced transport docs (#1165)Tom Christiebefore adoption477824a

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

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

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

line 1011why, one step back
1011

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

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

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

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

Advanced transport docs (#1165)Tom Christiebefore adoption477824a

lines 1015–1017why, one step back
1015>>> client = httpx.Client(transport=transport)
1016```1017

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

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

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

line 1019why, one step back
1019

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

lines 1020–1022why, one step back
1020```pycon
1021>>> import httpx1022>>> transport = httpx.HTTPTransport(retries=1)

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

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

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

lines 1024–1033why, one step back
1024```
10251026Similarly, instantiating a transport directly provides a `uds` option for1027connecting via a Unix Domain Socket that is only available via this low-level API:10281029```pycon1030>>> import httpx1031>>> # Connect to the Docker API via a Unix Socket.1032>>> transport = httpx.HTTPTransport(uds="/var/run/docker.sock")1033>>> client = httpx.Client(transport=transport)

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

lines 1034–1038why, one step back
1034>>> response = client.get("http://docker/info")
1035>>> response.json()1036{"ID": "...", "Containers": 4, "Images": 74, ...}1037```1038

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

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

line 1040why, one step back
1040

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

lines 1041–1042why, one step back
1041This [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`...
1042

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

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

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

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

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 1047–1050why, one step back
1047>>> client.get("https://example.org")
1048<Response [200 OK]>1049```1050

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

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

line 1052why, one step back
1052

Transport API (#1522)Tom Christiebefore adoption1a6e254

lines 1053–1057why, one step back
1053A transport instance must implement the low-level Transport API, which deals
1054with sending a single request, and returning a response. You should either1055subclass `httpx.BaseTransport` to implement a transport to use with `Client`,1056or subclass `httpx.AsyncBaseTransport` to implement a transport to1057use with `AsyncClient`.

Advanced transport docs (#1165)Tom Christiebefore adoption477824a

line 1058why, one step back
1058

Transport API (#1522)Tom Christiebefore adoption1a6e254

lines 1059–1066why, one step back
1059At the layer of the transport API we're using plain primitives.
1060No `Request` or `Response` models, no fancy `URL` or `Header` handling.1061This strict point of cut-off provides a clear design separation between the1062HTTPX API, and the low-level network handling.10631064See the `handle_request` and `handle_async_request` docstrings for more details1065on the specifics of the Transport API.1066

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 1067–1070why, one step back
1067A complete example of a custom transport implementation would be:
10681069```python1070import json

Transport API (#1522)Tom Christiebefore adoption1a6e254

line 1071why, one step back
1071import httpx

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 1072–1073why, one step back
1072
1073

Transport API (#1522)Tom Christiebefore adoption1a6e254

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

line 1075why, one step back
1075 """

Advanced transport docs (#1165)Tom Christiebefore adoption477824a

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 1077–1078why, one step back
1077 """
1078

Transport API (#1522)Tom Christiebefore adoption1a6e254

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

Advanced transport docs (#1165)Tom Christiebefore adoption477824a

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

Stream interface (#1550)Tom Christiebefore adoption110ce85

line 1082why, one step back
1082 stream = httpx.ByteStream(content)

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

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

Transport API (#1522)Tom Christiebefore adoption1a6e254

lines 1084–1085why, one step back
1084 extensions = {}
1085 return 200, headers, stream, extensions

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

lines 1086–1089why, one step back
1086```
10871088Which we can use in the same way:1089

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

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

Advanced transport docs (#1165)Tom Christiebefore adoption477824a

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

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

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

Advanced transport docs (#1165)Tom Christiebefore adoption477824a

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

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

lines 1096–1097why, one step back
1096```
1097

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

lines 1098–1111why, one step back
1098### Mock transports
10991100During testing it can often be useful to be able to mock out a transport,1101and return pre-determined responses, rather than making actual network requests.11021103The `httpx.MockTransport` class accepts a handler function, which can be used1104to map requests onto pre-determined responses:11051106```python1107def handler(request):1108 return httpx.Response(200, json={"text": "Hello, world!"})110911101111# Switch to a mock transport, if the TESTING environment variable is set.

Make the MockTransport example more robust/correct (#1621)Vytautas Liuoliabefore adoption2e4b308

line 1112why, one step back
1112if os.environ.get('TESTING', '').upper() == "TRUE":

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

lines 1113–1122why, one step back
1113 transport = httpx.MockTransport(handler)
1114else:1115 transport = httpx.HTTPTransport()11161117client = httpx.Client(transport=transport)1118```11191120For more advanced use-cases you might want to take a look at either [the third-party1121mocking library, RESPX](https://lundberg.github.io/respx/), or the [pytest-httpx library](https://github.com/Colin-b/pytest_httpx).1122

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

lines 1123–1131why, one step back
1123### Mounting transports
11241125You can also mount transports against given schemes or domains, to control1126which transport an outgoing request should be routed via, with [the same style1127used for specifying proxy routing](#routing).11281129```python1130import httpx1131

Transport API (#1522)Tom Christiebefore adoption1a6e254

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

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

lines 1133–1136why, one step back
1133 """
1134 A transport that always redirects to HTTPS.1135 """1136

Transport API (#1522)Tom Christiebefore adoption1a6e254

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

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

lines 1138–1142why, one step back
1138 scheme, host, port, path = url
1139 if port is None:1140 location = b"https://%s%s" % (host, path)1141 else:1142 location = b"https://%s:%d%s" % (host, port, path)

Stream interface (#1550)Tom Christiebefore adoption110ce85

line 1143why, one step back
1143 stream = httpx.ByteStream(b"")

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

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

Transport API (#1522)Tom Christiebefore adoption1a6e254

lines 1145–1146why, one step back
1145 extensions = {}
1146 return 303, headers, stream, extensions

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

lines 1147–1154why, one step back
1147
11481149# A client where any `http` requests are always redirected to `https`1150mounts = {'http://': HTTPSRedirectTransport()}1151client = httpx.Client(mounts=mounts)1152```11531154A couple of other sketches of how you might take advantage of mounted transports...

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

lines 1155–1164why, one step back
1155
1156Disabling HTTP/2 on a single given domain...11571158```python1159mounts = {1160 "all://": httpx.HTTPTransport(http2=True),1161 "all://*example.org": httpx.HTTPTransport()1162}1163client = httpx.Client(mounts=mounts)1164```

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

lines 1165–1170why, one step back
1165
1166Mocking requests to a given domain:11671168```python1169# All requests to "example.org" should be mocked out.1170# Other requests occur as usual.

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

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

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

lines 1175–1183why, one step back
1175client = httpx.Client(mounts=mounts)
1176```11771178Adding support for custom schemes:11791180```python1181# Support URLs like "file:///Users/sylvia_green/websites/new_client/index.html"1182mounts = {"file://": FileSystemTransport()}1183client = httpx.Client(mounts=mounts)

Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0

line 1184why, one step back
1184```