advanced.md
This file
Path
docs/advanced.md
1,176 lines · 39.3 KiB · Markdown
Last changed by
update docstring/docs for transport using request/response models (#2070)toppkbefore adoption4f8068a
History of this fileTake it
The walk stopped after 200 commits: lines older than 2a2bbe5 point at it.
Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 1–14why, one step back1# Advanced Usage23## 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 resources14Use relative links for interlinking markdown files in docs (#1390)Tom Christiebefore adoption0af6d9a
line 15why, one step back15When 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.Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 16–28why, one step back1617On 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:28Fix typos (#1968)Kian Meng, Angbefore adoption82ba15b
line 29why, one step back29- Cookie persistence across requests.Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 30–31why, one step back30- 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 back32- Using [HTTP/2](http2.md).Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 33–66why, one step back3334The 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:5859```pycon60>>> with httpx.Client() as client:61... r = client.get('https://example.com')62...63>>> r64<Response [200 OK]>65```66Use relative links for interlinking markdown files in docs (#1390)Tom Christiebefore adoption0af6d9a
line 67why, one step back67These 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.Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 68–145why, one step back6869For example, to send a request with custom headers:7071```pycon72>>> 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_:8586```pycon87>>> 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:101102```pycon103>>> 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:119120```pycon121>>> with httpx.Client(auth=('tom', 'mot123')) as client:122... r = client.get('https://example.com', auth=('alice', 'ecila123'))123...124>>> _, _, auth = r.request.headers['Authorization'].partition(' ')125>>> import base64126>>> base64.b64decode(auth)127b'alice:ecila123'128```129130If you need finer-grained control on the merging of client-level and request-level parameters, see [Request instances](#request-instances).131132### Other Client-only configuration options133134Additionally, `Client` accepts some configuration options that aren't available at the request level.135136For example, `base_url` allows you to prepend an URL to all outgoing requests:137138```pycon139>>> 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```145Use relative links for interlinking markdown files in docs (#1390)Tom Christiebefore adoption0af6d9a
line 146why, one step back146For a list of all available client parameters, see the [`Client`](api.md#client) API reference.Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 147–192why, one step back147148## 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 instances192Use relative links for interlinking markdown files in docs (#1390)Tom Christiebefore adoption0af6d9a
line 193why, one step back193For maximum control on what gets sent over the wire, HTTPX supports building explicit [`Request`](api.md#request) instances:Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 194–230why, one step back194195```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```223224## Event Hooks225226HTTPX 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:230docs: slightly clarify event hooks (#1645)K900before adoption776dbb5
lines 231–232why, one step back231* `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.Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 233why, one step back233docs: slightly clarify event hooks (#1645)K900before adoption776dbb5
line 234why, one step back234These allow you to install client-wide functionality such as logging, monitoring or tracing.Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 235–255why, one step back235236```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–257why, one step back256```257Switch event hooks to also run on redirects. (#1806)Tom Christiebefore adoption2d9c358
lines 258–262why, one step back258!!! note259 Response event hooks are called before determining if the response body260 should be read or not.261262 If you need access to the response body inside an event hook, you'llExpand docs note for async custom handler responses (#1916)Tyler Chamberlainbefore adoptionda8f959
line 263why, one step back263 need to call `response.read()`, or for AsyncClients, `response.aread()`.Switch event hooks to also run on redirects. (#1806)Tom Christiebefore adoption2d9c358
line 264why, one step back264docs: slightly clarify event hooks (#1645)K900before adoption776dbb5
lines 265–269why, one step back265The hooks are also allowed to modify `request` and `response` objects.266267```python268def add_timestamp(request):269 request.headers['x-request-timestamp'] = datetime.now(tz=datetime.utc).isoformat()Switch event hooks to also run on redirects. (#1806)Tom Christiebefore adoption2d9c358
line 270why, one step back270docs: slightly clarify event hooks (#1645)K900before adoption776dbb5
line 271why, one step back271client = httpx.Client(event_hooks={'request': [add_timestamp]})Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 272–379why, one step back272```273274Event hooks must always be set as a **list of callables**, and you may register275multiple event hooks for each type of event.276277As well as being able to set event hooks on instantiating the client, there278is also an `.event_hooks` property, that allows you to inspect and modify279the installed hooks.280281```python282client = httpx.Client()283client.event_hooks['request'] = [log_request]284client.event_hooks['response'] = [log_response, raise_on_4xx_5xx]285```286287!!! note288 If you are using HTTPX's async support, then you need to be aware that289 hooks registered with `httpx.AsyncClient` MUST be async functions,290 rather than plain functions.291292## Monitoring download progress293294If you need to monitor download progress of large responses, you can use response streaming and inspect the `response.num_bytes_downloaded` property.295296This 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.297298For 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…299300```python301import tempfile302303import httpx304from tqdm import tqdm305306with tempfile.NamedTemporaryFile() as download_file:307 url = "https://speed.hetzner.de/100MB.bin"308 with httpx.stream("GET", url) as response:309 total = int(response.headers["Content-Length"])310311 with tqdm(total=total, unit_scale=True, unit_divisor=1024, unit="B") as progress:312 num_bytes_downloaded = response.num_bytes_downloaded313 for chunk in response.iter_bytes():314 download_file.write(chunk)315 progress.update(response.num_bytes_downloaded - num_bytes_downloaded)316 num_bytes_downloaded = response.num_bytes_downloaded317```318319320321Or an alternate example, this time using the [`rich`](https://github.com/willmcgugan/rich) library…322323```python324import tempfile325import httpx326import rich.progress327328with tempfile.NamedTemporaryFile() as download_file:329 url = "https://speed.hetzner.de/100MB.bin"330 with httpx.stream("GET", url) as response:331 total = int(response.headers["Content-Length"])332333 with rich.progress.Progress(334 "[progress.percentage]{task.percentage:>3.0f}%",335 rich.progress.BarColumn(bar_width=None),336 rich.progress.DownloadColumn(),337 rich.progress.TransferSpeedColumn(),338 ) as progress:339 download_task = progress.add_task("Download", total=total)340 for chunk in response.iter_bytes():341 download_file.write(chunk)342 progress.update(download_task, completed=response.num_bytes_downloaded)343```344345346347## .netrc Support348349HTTPX supports .netrc file. In `trust_env=True` cases, if auth parameter is350not defined, HTTPX tries to add auth into request's header from .netrc file.351352!!! note353 The NETRC file is cached across requests made by a client.354 If you need to refresh the cache (e.g. because the NETRC file has changed),355 you should create a new client or restart the interpreter.356357As default `trust_env` is true. To set false:358```pycon359>>> httpx.get('https://example.org/', trust_env=False)360```361362If `NETRC` environment is empty, HTTPX tries to use default files.363(`~/.netrc`, `~/_netrc`)364365To change `NETRC` environment:366```pycon367>>> import os368>>> os.environ["NETRC"] = "my_default_folder/.my_netrc"369```370371.netrc file content example:372```373machine netrcexample.org374login example-username375password example-password376377...378```379Add netrc environment variable into the documentation (#1675)Meibefore adoption604d09d
line 380why, one step back380When using `Client` instances, `trust_env` should be set on the client itself, rather than on the request methods:Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 381–553why, one step back381382```python383client = httpx.Client(trust_env=False)384```385386## HTTP Proxying387388HTTPX 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=...)`.389390<div align="center">391 <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/27/Open_proxy_h2g2bob.svg/480px-Open_proxy_h2g2bob.svg.png"/>392 <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>393</div>394395### Example396397To route all traffic (HTTP and HTTPS) to a proxy located at `http://localhost:8030`, pass the proxy URL to the client...398399```python400with httpx.Client(proxies="http://localhost:8030") as client:401 ...402```403404For 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:405406```python407proxies = {408 "http://": "http://localhost:8030",409 "https://": "http://localhost:8031",410}411412with httpx.Client(proxies=proxies) as client:413 ...414```415416For detailed information about proxy routing, see the [Routing](#routing) section.417418!!! tip "Gotcha"419 In most cases, the proxy URL for the `https://` key _should_ use the `http://` scheme (that's not a typo!).420421 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.422423 For more information, see [FORWARD vs TUNNEL](#forward-vs-tunnel).424425### Authentication426427Proxy credentials can be passed as the `userinfo` section of the proxy URL. For example:428429```python430proxies = {431 "http://": "http://username:password@localhost:8030",432 # ...433}434```435436### Routing437438HTTPX provides fine-grained controls for deciding which requests should go through a proxy, and which shouldn't. This process is known as proxy routing.439440The `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://`).441442HTTPX supports routing proxies based on **scheme**, **domain**, **port**, or a combination of these.443444#### Wildcard routing445446Route everything through a proxy...447448```python449proxies = {450 "all://": "http://localhost:8030",451}452```453454#### Scheme routing455456Route HTTP requests through one proxy, and HTTPS requests through another...457458```python459proxies = {460 "http://": "http://localhost:8030",461 "https://": "http://localhost:8031",462}463```464465#### Domain routing466467Proxy all requests on domain "example.com", let other requests pass through...468469```python470proxies = {471 "all://example.com": "http://localhost:8030",472}473```474475Proxy HTTP requests on domain "example.com", let HTTPS and other requests pass through...476477```python478proxies = {479 "http://example.com": "http://localhost:8030",480}481```482483Proxy all requests to "example.com" and its subdomains, let other requests pass through...484485```python486proxies = {487 "all://*example.com": "http://localhost:8030",488}489```490491Proxy all requests to strict subdomains of "example.com", let "example.com" and other requests pass through...492493```python494proxies = {495 "all://*.example.com": "http://localhost:8030",496}497```498499#### Port routing500501Proxy HTTPS requests on port 1234 to "example.com"...502503```python504proxies = {505 "https://example.com:1234": "http://localhost:8030",506}507```508509Proxy all requests on port 1234...510511```python512proxies = {513 "all://*:1234": "http://localhost:8030",514}515```516517#### No-proxy support518519It is also possible to define requests that _shouldn't_ be routed through proxies.520521To do so, pass `None` as the proxy URL. For example...522523```python524proxies = {525 # Route requests through a proxy by default...526 "all://": "http://localhost:8031",527 # Except those for "example.com".528 "all://example.com": None,529}530```531532#### Complex configuration example533534You can combine the routing features outlined above to build complex proxy routing configurations. For example...535536```python537proxies = {538 # Route all traffic through a proxy by default...539 "all://": "http://localhost:8030",540 # But don't use proxies for HTTPS requests to "domain.io"...541 "https://domain.io": None,542 # And use another proxy for requests to "example.com" and its subdomains...543 "all://*example.com": "http://localhost:8031",544 # And yet another proxy if HTTP is used,545 # and the "internal" subdomain on port 5550 is requested...546 "http://internal.example.com:5550": "http://localhost:8032",547}548```549550#### Environment variables551552HTTP proxying can also be configured through environment variables, although with less fine-grained control.553Use relative links for interlinking markdown files in docs (#1390)Tom Christiebefore adoption0af6d9a
line 554why, one step back554See documentation on [`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`](environment_variables.md#http_proxy-https_proxy-all_proxy) for more information.Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 555–565why, one step back555556### Proxy mechanisms557558!!! note559 This section describes **advanced** proxy concepts and functionality.560561#### FORWARD vs TUNNEL562563In general, the flow for making an HTTP request through a proxy is as follows:5645651. The client connects to the proxy (initial connection request).SOCKS proxy support (#2034)Tom Christiebefore adoption8dc9b6b
line 566why, one step back5662. The proxy transfers data to the server on your behalf.Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 567–570why, one step back567568How exactly step 2/ is performed depends on which of two proxying mechanisms is used:569570* **Forwarding**: the proxy makes the request for you, and sends back the response it obtained from the server.SOCKS proxy support (#2034)Tom Christiebefore adoption8dc9b6b
line 571why, one step back571* **Tunnelling**: 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).Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 572why, one step back572SOCKS proxy support (#2034)Tom Christiebefore adoption8dc9b6b
line 573why, one step back573### Troubleshooting proxiesTighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 574why, one step back574SOCKS proxy support (#2034)Tom Christiebefore adoption8dc9b6b
line 575why, one step back575If you encounter issues when setting up proxies, please refer to our [Troubleshooting guide](troubleshooting.md#proxies).Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 576why, one step back576SOCKS proxy support (#2034)Tom Christiebefore adoption8dc9b6b
line 577why, one step back577## SOCKSTighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 578why, one step back578SOCKS proxy support (#2034)Tom Christiebefore adoption8dc9b6b
lines 579–580why, one step back579In addition to HTTP proxies, `httpcore` also supports proxies using the SOCKS protocol.580This is an optional feature that requires an additional third-party library be installed before use.Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 581why, one step back581SOCKS proxy support (#2034)Tom Christiebefore adoption8dc9b6b
line 582why, one step back582You can install SOCKS support using `pip`:Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 583why, one step back583SOCKS proxy support (#2034)Tom Christiebefore adoption8dc9b6b
lines 584–586why, one step back584```shell585$ pip install httpx[socks]586```Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 587why, one step back587SOCKS proxy support (#2034)Tom Christiebefore adoption8dc9b6b
line 588why, one step back588You can now configure a client to make requests via a proxy using the SOCKS protocol:Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 589–590why, one step back589590```pythonSOCKS proxy support (#2034)Tom Christiebefore adoption8dc9b6b
line 591why, one step back591httpx.Client(proxies='socks5://user:pass@host:port')Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 592why, one step back592```Add troubleshooting guide, with initial proxies entries (#1435)Florimond Mancabefore adoption25781a7
line 593why, one step back593Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 594–643why, one step back594## Timeout Configuration595596HTTPX is careful to enforce timeouts everywhere by default.597598The default behavior is to raise a `TimeoutException` after 5 seconds of599network inactivity.600601### Setting and disabling timeouts602603You can set timeouts for an individual request:604605```python606# Using the top-level API:607httpx.get('http://example.com/api/v1/example', timeout=10.0)608609# Using a client instance:610with httpx.Client() as client:611 client.get("http://example.com/api/v1/example", timeout=10.0)612```613614Or disable timeouts for an individual request:615616```python617# Using the top-level API:618httpx.get('http://example.com/api/v1/example', timeout=None)619620# Using a client instance:621with httpx.Client() as client:622 client.get("http://example.com/api/v1/example", timeout=None)623```624625### Setting a default timeout on a client626627You can set a timeout on a client instance, which results in the given628`timeout` being used as the default for requests made with this client:629630```python631client = httpx.Client() # Use a default 5s timeout everywhere.632client = httpx.Client(timeout=10.0) # Use a default 10s timeout everywhere.633client = httpx.Client(timeout=None) # Disable all timeouts by default.634```635636### Fine tuning the configuration637638HTTPX also allows you to specify the timeout behavior in more fine grained detail.639640There are four different types of timeouts that may occur. These are **connect**,641**read**, **write**, and **pool** timeouts.642643* The **connect** timeout specifies the maximum amount of time to wait untilTweak advanced timeouts docs (#1420)Florimond Mancabefore adoption584a405
line 644why, one step back644a socket connection to the requested host is established. If HTTPX is unable to connectTighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 645–655why, one step back645within this time frame, a `ConnectTimeout` exception is raised.646* The **read** timeout specifies the maximum duration to wait for a chunk of647data to be received (for example, a chunk of the response body). If HTTPX is648unable to receive data within this time frame, a `ReadTimeout` exception is raised.649* The **write** timeout specifies the maximum duration to wait for a chunk of650data to be sent (for example, a chunk of the request body). If HTTPX is unable651to send data within this time frame, a `WriteTimeout` exception is raised.652* The **pool** timeout specifies the maximum duration to wait for acquiring653a connection from the connection pool. If HTTPX is unable to acquire a connection654within this time frame, a `PoolTimeout` exception is raised. A related655configuration here is the maximum number of allowable connections in theTweak advanced timeouts docs (#1420)Florimond Mancabefore adoption584a405
line 656why, one step back656connection pool, which is configured by the `limits` argument.Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 657–673why, one step back657658You can configure the timeout behavior for any of these values...659660```python661# A client with a 60s timeout for connecting, and a 10s timeout elsewhere.662timeout = httpx.Timeout(10.0, connect=60.0)663client = httpx.Client(timeout=timeout)664665response = client.get('http://example.com/')666```667668## Pool limit configuration669670You can control the connection pool size using the `limits` keyword671argument on the client. It takes instances of `httpx.Limits` which define:672673- `max_keepalive`, number of allowable keep-alive connections, or `None` to alwaysFix typo to match library default (#1535)Louis Maddoxbefore adoption68cf1ff
line 674why, one step back674allow. (Defaults 20)Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 675–684why, one step back675- `max_connections`, maximum number of allowable connections, or` None` for no limits.676(Default 100)677678```python679limits = httpx.Limits(max_keepalive_connections=5, max_connections=10)680client = httpx.Client(limits=limits)681```682683## Multipart file encoding684Use relative links for interlinking markdown files in docs (#1390)Tom Christiebefore adoption0af6d9a
line 685why, one step back685As mentioned in the [quickstart](quickstart.md#sending-multipart-file-uploads)Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 686–951why, one step back686multipart file encoding is available by passing a dictionary with the687name of the payloads as keys and either tuple of elements or a file-like object or a string as values.688689```pycon690>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}691>>> r = httpx.post("https://httpbin.org/post", files=files)692>>> print(r.text)693{694 ...695 "files": {696 "upload-file": "<... binary content ...>"697 },698 ...699}700```701702More specifically, if a tuple is used as a value, it must have between 2 and 3 elements:703704- The first element is an optional file name which can be set to `None`.705- The second element may be a file-like object or a string which will be automatically706encoded in UTF-8.707- An optional third element can be used to specify the708[MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_Types)709of the file being uploaded. If not specified HTTPX will attempt to guess the MIME type based710on the file name, with unknown file extensions defaulting to "application/octet-stream".711If the file name is explicitly set to `None` then HTTPX will not include a content-type712MIME header field.713714```pycon715>>> files = {'upload-file': (None, 'text content', 'text/plain')}716>>> r = httpx.post("https://httpbin.org/post", files=files)717>>> print(r.text)718{719 ...720 "files": {},721 "form": {722 "upload-file": "text-content"723 },724 ...725}726```727728!!! tip729 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.730731 Non-file data fields can be included in the multipart form using by passing them to `data=...`.732733You can also send multiple files in one go with a multiple file field form.734To do that, pass a list of `(field, <file>)` items instead of a dictionary, allowing you to pass multiple items with the same `field`.735For instance this request sends 2 files, `foo.png` and `bar.png` in one request on the `images` form field:736737```pycon738>>> files = [('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),739 ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]740>>> r = httpx.post("https://httpbin.org/post", files=files)741```742743## Customizing authentication744745When 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...746747* A two-tuple of `username`/`password`, to be used with basic authentication.748* An instance of `httpx.BasicAuth()` or `httpx.DigestAuth()`.749* A callable, accepting a request and returning an authenticated request instance.750* A subclass of `httpx.Auth`.751752The 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...753754```python755class MyCustomAuth(httpx.Auth):756 def __init__(self, token):757 self.token = token758759 def auth_flow(self, request):760 # Send the request, with a custom `X-Authentication` header.761 request.headers['X-Authentication'] = self.token762 yield request763```764765If the auth flow requires more that one request, you can issue multiple yields, and obtain the response in each case...766767```python768class MyCustomAuth(httpx.Auth):769 def __init__(self, token):770 self.token = token771772 def auth_flow(self, request):773 response = yield request774 if response.status_code == 401:775 # If the server issues a 401 response then resend the request,776 # with a custom `X-Authentication` header.777 request.headers['X-Authentication'] = self.token778 yield request779```780781Custom 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.782783You will then be able to access `request.content` inside the `.auth_flow()` method.784785```python786class MyCustomAuth(httpx.Auth):787 requires_request_body = True788789 def __init__(self, token):790 self.token = token791792 def auth_flow(self, request):793 response = yield request794 if response.status_code == 401:795 # If the server issues a 401 response then resend the request,796 # with a custom `X-Authentication` header.797 request.headers['X-Authentication'] = self.sign_request(...)798 yield request799800 def sign_request(self, request):801 # Create a request signature, based on `request.method`, `request.url`,802 # `request.headers`, and `request.content`.803 ...804```805806Similarly, 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.807808```python809class MyCustomAuth(httpx.Auth):810 requires_response_body = True811812 def __init__(self, access_token, refresh_token, refresh_url):813 self.access_token = access_token814 self.refresh_token = refresh_token815 self.refresh_url = refresh_url816817 def auth_flow(self, request):818 request.headers["X-Authentication"] = self.access_token819 response = yield request820821 if response.status_code == 401:822 # If the server issues a 401 response, then issue a request to823 # refresh tokens, and resend the request.824 refresh_response = yield self.build_refresh_request()825 self.update_tokens(refresh_response)826827 request.headers["X-Authentication"] = self.access_token828 yield request829830 def build_refresh_request(self):831 # Return an `httpx.Request` for refreshing tokens.832 ...833834 def update_tokens(self, response):835 # Update the `.access_token` and `.refresh_token` tokens836 # based on a refresh response.837 data = response.json()838 ...839```840841If 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`.842843```python844import asyncio845import threading846import httpx847848849class MyCustomAuth(httpx.Auth):850 def __init__(self):851 self._sync_lock = threading.RLock()852 self._async_lock = asyncio.Lock()853854 def sync_get_token(self):855 with self._sync_lock:856 ...857858 def sync_auth_flow(self, request):859 token = self.sync_get_token()860 request.headers["Authorization"] = f"Token {token}"861 yield request862863 async def async_get_token(self):864 async with self._async_lock:865 ...866867 async def async_auth_flow(self, request):868 token = await self.async_get_token()869 request.headers["Authorization"] = f"Token {token}"870 yield request871```872873If you only want to support one of the two methods, then you should still override it, but raise an explicit `RuntimeError`.874875```python876import httpx877import sync_only_library878879880class MyCustomAuth(httpx.Auth):881 def sync_auth_flow(self, request):882 token = sync_only_library.get_token(...)883 request.headers["Authorization"] = f"Token {token}"884 yield request885886 async def async_auth_flow(self, request):887 raise RuntimeError("Cannot use a sync authentication class with httpx.AsyncClient")888```889890## SSL certificates891892When 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).893894### Changing the verification defaults895896By 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.897898If you'd like to use a custom CA bundle, you can use the `verify` parameter.899900```python901import httpx902903r = httpx.get("https://example.org", verify="path/to/client.pem")904```905906Alternatively, you can pass a standard library `ssl.SSLContext`.907908```pycon909>>> import ssl910>>> import httpx911>>> context = ssl.create_default_context()912>>> context.load_verify_locations(cafile="/tmp/client.pem")913>>> httpx.get('https://example.org', verify=context)914<Response [200 OK]>915```916917We also include a helper function for creating properly configured `SSLContext` instances.918919```pycon920>>> context = httpx.create_ssl_context()921```922923The `create_ssl_context` function accepts the same set of SSL configuration arguments924(`trust_env`, `verify`, `cert` and `http2` arguments)925as `httpx.Client` or `httpx.AsyncClient`926927```pycon928>>> import httpx929>>> context = httpx.create_ssl_context(verify="/tmp/client.pem")930>>> httpx.get('https://example.org', verify=context)931<Response [200 OK]>932```933934Or you can also disable the SSL verification entirely, which is _not_ recommended.935936```python937import httpx938939r = httpx.get("https://example.org", verify=False)940```941942### SSL configuration on client instances943944If you're using a `Client()` instance, then you should pass any SSL settings when instantiating the client.945946```python947client = httpx.Client(verify=False)948```949950The `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.951Added docs for using client-side ssl certificates (#1570)Hemanth kumarbefore adoption535df6c
lines 952–977why, one step back952### Client Side Certificates953954You 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)955956```python957import httpx958959r = httpx.get("https://example.org", cert="path/to/client.pem")960```961962Alternatively,963964```pycon965>>> cert = ("path/to/client.pem", "path/to/client.key")966>>> httpx.get("https://example.org", cert=cert)967<Response [200 OK]>968```969970or971972```pycon973>>> cert = ("path/to/client.pem", "path/to/client.key", "password")974>>> httpx.get("https://example.org", cert=cert)975<Response [200 OK]>976```977Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 978–1003why, one step back978### Making HTTPS requests to a local server979980When making requests to local servers, such as a development server running on `localhost`, you will typically be using unencrypted HTTP connections.981982If 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:9839841. Use [trustme-cli](https://github.com/sethmlarson/trustme-cli/) to generate a pair of server key/cert files, and a client cert file.9851. 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.)9861. Tell HTTPX to use the certificates stored in `client.pem`:987988```pycon989>>> import httpx990>>> r = httpx.get("https://localhost:8000", verify="/tmp/client.pem")991>>> r992Response <200 OK>993```994995## Custom Transports996997HTTPX's `Client` also accepts a `transport` argument. This argument allows you998to provide a custom Transport object that will be used to perform the actual999sending of the requests.10001001### Usage10021003For some advanced configuration you might need to instantiate a transportAdd `HTTPTransport` and `AsyncHTTPTransport` (#1399)Tom Christiebefore adoption89fb0cb
lines 1004–1005why, one step back1004class directly, and pass it to the client instance. One example is the1005`local_address` configuration which is only available via this low-level API.Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 1006–1007why, one step back10061007```pyconAdd `HTTPTransport` and `AsyncHTTPTransport` (#1399)Tom Christiebefore adoption89fb0cb
lines 1008–1009why, one step back1008>>> import httpx1009>>> transport = httpx.HTTPTransport(local_address="0.0.0.0")Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 1010–1012why, one step back1010>>> client = httpx.Client(transport=transport)1011```1012Add `HTTPTransport` and `AsyncHTTPTransport` (#1399)Tom Christiebefore adoption89fb0cb
line 1013why, one step back1013Connection retries are also available via this interface.Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 1014why, one step back1014Add `HTTPTransport` and `AsyncHTTPTransport` (#1399)Tom Christiebefore adoption89fb0cb
lines 1015–1017why, one step back1015```pycon1016>>> import httpx1017>>> transport = httpx.HTTPTransport(retries=1)Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 1018why, one step back1018>>> client = httpx.Client(transport=transport)Add `HTTPTransport` and `AsyncHTTPTransport` (#1399)Tom Christiebefore adoption89fb0cb
lines 1019–1028why, one step back1019```10201021Similarly, instantiating a transport directly provides a `uds` option for1022connecting via a Unix Domain Socket that is only available via this low-level API:10231024```pycon1025>>> import httpx1026>>> # Connect to the Docker API via a Unix Socket.1027>>> transport = httpx.HTTPTransport(uds="/var/run/docker.sock")1028>>> client = httpx.Client(transport=transport)Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 1029–1047why, one step back1029>>> response = client.get("http://docker/info")1030>>> response.json()1031{"ID": "...", "Containers": 4, "Images": 74, ...}1032```10331034### urllib3 transport10351036This [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`...10371038```pycon1039>>> import httpx1040>>> from urllib3_transport import URLLib3Transport1041>>> client = httpx.Client(transport=URLLib3Transport())1042>>> client.get("https://example.org")1043<Response [200 OK]>1044```10451046### Writing custom transports1047Transport API (#1522)Tom Christiebefore adoption1a6e254
lines 1048–1052why, one step back1048A transport instance must implement the low-level Transport API, which deals1049with sending a single request, and returning a response. You should either1050subclass `httpx.BaseTransport` to implement a transport to use with `Client`,1051or subclass `httpx.AsyncBaseTransport` to implement a transport to1052use with `AsyncClient`.Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 1053why, one step back1053update docstring/docs for transport using request/response models (#2070)toppkbefore adoption4f8068a
lines 1054–1055why, one step back1054At the layer of the transport API we're using the familiar `Request` and1055`Response` models.Transport API (#1522)Tom Christiebefore adoption1a6e254
lines 1056–1059why, one step back10561057See the `handle_request` and `handle_async_request` docstrings for more details1058on the specifics of the Transport API.1059Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 1060–1063why, one step back1060A complete example of a custom transport implementation would be:10611062```python1063import jsonTransport API (#1522)Tom Christiebefore adoption1a6e254
line 1064why, one step back1064import httpxTighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 1065–1066why, one step back10651066Transport API (#1522)Tom Christiebefore adoption1a6e254
line 1067why, one step back1067class HelloWorldTransport(httpx.BaseTransport):Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 1068–1071why, one step back1068 """1069 A mock transport that always returns a JSON "Hello, world!" response.1070 """1071update docstring/docs for transport using request/response models (#2070)toppkbefore adoption4f8068a
line 1072why, one step back1072 def handle_request(self, request):Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 1073–1074why, one step back1073 message = {"text": "Hello, world!"}1074 content = json.dumps(message).encode("utf-8")Stream interface (#1550)Tom Christiebefore adoption110ce85
line 1075why, one step back1075 stream = httpx.ByteStream(content)Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 1076why, one step back1076 headers = [(b"content-type", b"application/json")]update docstring/docs for transport using request/response models (#2070)toppkbefore adoption4f8068a
line 1077why, one step back1077 return httpx.Response(200, headers=headers, stream=stream)Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
lines 1078–1087why, one step back1078```10791080Which we can use in the same way:10811082```pycon1083>>> import httpx1084>>> client = httpx.Client(transport=HelloWorldTransport())1085>>> response = client.get("https://example.org/")1086>>> response.json()1087{"text": "Hello, world!"}Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 1088–1089why, one step back1088```1089Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
lines 1090–1103why, one step back1090### Mock transports10911092During testing it can often be useful to be able to mock out a transport,1093and return pre-determined responses, rather than making actual network requests.10941095The `httpx.MockTransport` class accepts a handler function, which can be used1096to map requests onto pre-determined responses:10971098```python1099def handler(request):1100 return httpx.Response(200, json={"text": "Hello, world!"})110111021103# Switch to a mock transport, if the TESTING environment variable is set.Make the MockTransport example more robust/correct (#1621)Vytautas Liuoliabefore adoption2e4b308
line 1104why, one step back1104if os.environ.get('TESTING', '').upper() == "TRUE":Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
lines 1105–1114why, one step back1105 transport = httpx.MockTransport(handler)1106else:1107 transport = httpx.HTTPTransport()11081109client = httpx.Client(transport=transport)1110```11111112For more advanced use-cases you might want to take a look at either [the third-party1113mocking library, RESPX](https://lundberg.github.io/respx/), or the [pytest-httpx library](https://github.com/Colin-b/pytest_httpx).1114Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 1115–1123why, one step back1115### Mounting transports11161117You can also mount transports against given schemes or domains, to control1118which transport an outgoing request should be routed via, with [the same style1119used for specifying proxy routing](#routing).11201121```python1122import httpx1123Transport API (#1522)Tom Christiebefore adoption1a6e254
line 1124why, one step back1124class HTTPSRedirectTransport(httpx.BaseTransport):Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 1125–1128why, one step back1125 """1126 A transport that always redirects to HTTPS.1127 """1128Transport API (#1522)Tom Christiebefore adoption1a6e254
line 1129why, one step back1129 def handle_request(self, method, url, headers, stream, extensions):Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 1130–1134why, one step back1130 scheme, host, port, path = url1131 if port is None:1132 location = b"https://%s%s" % (host, path)1133 else:1134 location = b"https://%s:%d%s" % (host, port, path)Stream interface (#1550)Tom Christiebefore adoption110ce85
line 1135why, one step back1135 stream = httpx.ByteStream(b"")Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
line 1136why, one step back1136 headers = [(b"location", location)]Transport API (#1522)Tom Christiebefore adoption1a6e254
lines 1137–1138why, one step back1137 extensions = {}1138 return 303, headers, stream, extensionsAdd support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 1139–1146why, one step back113911401141# A client where any `http` requests are always redirected to `https`1142mounts = {'http://': HTTPSRedirectTransport()}1143client = httpx.Client(mounts=mounts)1144```11451146A couple of other sketches of how you might take advantage of mounted transports...Add `HTTPTransport` and `AsyncHTTPTransport` (#1399)Tom Christiebefore adoption89fb0cb
lines 1147–1156why, one step back11471148Disabling HTTP/2 on a single given domain...11491150```python1151mounts = {1152 "all://": httpx.HTTPTransport(http2=True),1153 "all://*example.org": httpx.HTTPTransport()1154}1155client = httpx.Client(mounts=mounts)1156```Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 1157–1162why, one step back11571158Mocking requests to a given domain:11591160```python1161# All requests to "example.org" should be mocked out.1162# Other requests occur as usual.Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
lines 1163–1166why, one step back1163def handler(request):1164 return httpx.Response(200, json={"text": "Hello, World!"})11651166mounts = {"all://example.org": httpx.MockTransport(handler)}Add support for Mount API (#1362)Tom Christiebefore adoptionc4d2e6f
lines 1167–1175why, one step back1167client = httpx.Client(mounts=mounts)1168```11691170Adding support for custom schemes:11711172```python1173# Support URLs like "file:///Users/sylvia_green/websites/new_client/index.html"1174mounts = {"file://": FileSystemTransport()}1175client = httpx.Client(mounts=mounts)Tighten client closed-state behaviour (#1346)Tom Christiebefore adoption2a2bbe5
line 1176why, one step back1176```