advanced.md
This file
Path
docs/advanced.md
1,007 lines · 34.4 KiB · Markdown
Last changed by
Progress examples (#1272)Tom Christiebefore adoption59074c7
History of this fileTake it
The walk stopped after 200 commits: lines older than 21f5337 point at it.
Add 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 1–58why, 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 resources1415When you make requests using the top-level API as documented in the [Quickstart](/quickstart) guide, HTTPX has to establish a new connection _for every single request_ (connections are not reused). As the number of requests to a host increases, this quickly becomes inefficient.1617On the other hand, a `Client` instance uses [HTTP connection pooling](https://en.wikipedia.org/wiki/HTTP_persistent_connection). This means that when you make several requests to the same host, the `Client` will reuse the underlying TCP connection, instead of recreating one for every single request.1819This can bring **significant performance improvements** compared to using the top-level API, including:2021- Reduced latency across requests (no handshaking).22- Reduced CPU usage and round-trips.23- Reduced network congestion.2425#### Extra features2627`Client` instances also support features that aren't available at the top-level API, such as:2829- Cookie persistance across requests.30- Applying configuration across all outgoing requests.31- Sending requests through HTTP proxies.32- Using [HTTP/2](/http2).3334The other sections on this page go into further detail about what you can do with a `Client` instance.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:58Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 59why, one step back59```pyconAdd 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 60–70why, one step back60>>> with httpx.Client() as client:61... r = client.get('https://example.com')62...63>>> r64<Response [200 OK]>65```6667These methods accept the same arguments as `httpx.get()`, `httpx.post()`, etc. This means that all features documented in the [Quickstart](/quickstart) guide are also available at the client level.6869For example, to send a request with custom headers:70Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 71why, one step back71```pyconAdd 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 72–85why, one step back72>>> 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_:85Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 86why, one step back86```pyconAdd 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 87–101why, one step back87>>> 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:101Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 102why, one step back102```pyconAdd 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 103–119why, one step back103>>> 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:119Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 120why, one step back120```pyconAdd 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 121–137why, one step back121>>> 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:137Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 138why, one step back138```pyconAdd 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 139–175why, one step back139>>> 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```145146For a list of all available client parameters, see the [`Client`](/api/#client) API reference.147148## 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```175Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
line 176why, one step back176For some more complex cases you might need to customize the WSGI transport. This allows you to:Add 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 177–185why, one step back177178* 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".Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
lines 186–187why, one step back186transport = httpx.WSGITransport(app=app, remote_addr="1.2.3.4")187with httpx.Client(transport=transport, base_url="http://testserver") as client:Add 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 188–223why, one step back188 ...189```190191## Request instances192193For maximum control on what gets sent over the wire, HTTPX supports building explicit [`Request`](/api#request) instances:194195```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```223Add progress to streaming download (#1268)cdelerbefore adoptioned16eb3
lines 224–249why, one step back224## Monitoring download progress225226If you need to monitor download progress of large responses, you can use response streaming and inspect the `response.num_bytes_downloaded` property.227228This 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.229230For 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…231232```python233import tempfile234235import httpx236from tqdm import tqdm237238with tempfile.NamedTemporaryFile() as download_file:239 url = "https://speed.hetzner.de/100MB.bin"240 with httpx.stream("GET", url) as response:241 total = int(response.headers["Content-Length"])242243 with tqdm(total=total, unit_scale=True, unit_divisor=1024, unit="B") as progress:244 num_bytes_downloaded = response.num_bytes_downloaded245 for chunk in response.iter_bytes():246 download_file.write(chunk)247 progress.update(response.num_bytes_downloaded - num_bytes_downloaded)248 num_bytes_downloaded = response.num_bytes_downloaded249```Progress examples (#1272)Tom Christiebefore adoption59074c7
lines 250–277why, one step back250251252253Or an alternate example, this time using the [`rich`](https://github.com/willmcgugan/rich) library…254255```python256import tempfile257import httpx258import rich.progress259260with tempfile.NamedTemporaryFile() as download_file:261 url = "https://speed.hetzner.de/100MB.bin"262 with httpx.stream("GET", url) as response:263 total = int(response.headers["Content-Length"])264265 with rich.progress.Progress(266 "[progress.percentage]{task.percentage:>3.0f}%",267 rich.progress.BarColumn(bar_width=None),268 rich.progress.DownloadColumn(),269 rich.progress.TransferSpeedColumn(),270 ) as progress:271 download_task = progress.add_task("Download", total=total)272 for chunk in response.iter_bytes():273 download_file.write(chunk)274 progress.update(download_task, completed=response.num_bytes_downloaded)275```276277Add progress to streaming download (#1268)cdelerbefore adoptioned16eb3
line 278why, one step back278Add 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 279–289why, one step back279## .netrc Support280281HTTPX supports .netrc file. In `trust_env=True` cases, if auth parameter is282not defined, HTTPX tries to add auth into request's header from .netrc file.283284!!! note285 The NETRC file is cached across requests made by a client.286 If you need to refresh the cache (e.g. because the NETRC file has changed),287 you should create a new client or restart the interpreter.288289As default `trust_env` is true. To set false:Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 290why, one step back290```pyconAdd 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 291–297why, one step back291>>> httpx.get('https://example.org/', trust_env=False)292```293294If `NETRC` environment is empty, HTTPX tries to use default files.295(`~/.netrc`, `~/_netrc`)296297To change `NETRC` environment:Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 298why, one step back298```pyconAdd 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 299–319why, one step back299>>> import os300>>> os.environ["NETRC"] = "my_default_folder/.my_netrc"301```302303.netrc file content example:304```305machine netrcexample.org306login example-username307password example-password308309...310```311312When using `Client` instances, `trust_env` should be set on the client itself, rather that on the request methods:313314```python315client = httpx.Client(trust_env=False)316```317318## HTTP Proxying319Add `proxies` parameter to top-level API functions (#1198)Joebefore adoption84ca201
line 320why, one step back320HTTPX 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=...)`.Add 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
line 321why, one step back321Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 322–332why, one step back322_Note: SOCKS proxies are not supported yet._323324<div align="center">325 <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/27/Open_proxy_h2g2bob.svg/480px-Open_proxy_h2g2bob.svg.png"/>326 <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>327</div>328329### Example330331To route all traffic (HTTP and HTTPS) to a proxy located at `http://localhost:8030`, pass the proxy URL to the client...332Add 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
line 333why, one step back333```pythonRevamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 334–335why, one step back334with httpx.Client(proxies="http://localhost:8030") as client:335 ...Add 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 336–337why, one step back336```337Refine docs phrasing on proxy routing (#1124)Florimond Mancabefore adoption0fb28e8
line 338why, one step back338For 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:Add 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
line 339why, one step back339Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 340–341why, one step back340```python341proxies = {Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4
lines 342–343why, one step back342 "http://": "http://localhost:8030",343 "https://": "http://localhost:8031",Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
line 344why, one step back344}Add 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
line 345why, one step back345Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 346–352why, one step back346with httpx.Client(proxies=proxies) as client:347 ...348```349350For detailed information about proxy routing, see the [Routing](#routing) section.351352!!! tip "Gotcha"Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4
line 353why, one step back353 In most cases, the proxy URL for the `https://` key _should_ use the `http://` scheme (that's not a typo!).Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 354–362why, one step back354355 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.356357 For more information, see [FORWARD vs TUNNEL](#forward-vs-tunnel).358359### Authentication360361Proxy credentials can be passed as the `userinfo` section of the proxy URL. For example:362Add 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
line 363why, one step back363```pythonRevamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
line 364why, one step back364proxies = {Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4
line 365why, one step back365 "http://": "http://username:password@localhost:8030",Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 366–367why, one step back366 # ...367}Add 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 368–369why, one step back368```369Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
line 370why, one step back370### RoutingAdd 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
line 371why, one step back371Refine docs phrasing on proxy routing (#1124)Florimond Mancabefore adoption0fb28e8
line 372why, one step back372HTTPX provides fine-grained controls for deciding which requests should go through a proxy, and which shouldn't. This process is known as proxy routing.Add 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
line 373why, one step back373Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4
line 374why, one step back374The `proxies` dictionary maps URL patterns ("proxy keys") to proxy URLs. HTTPX matches requested URLs against proxy keys to decide which proxy should be used, if any. Matching is done from most specific proxy keys (e.g. `https://<domain>:<port>`) to least specific ones (e.g. `https://`).Refine docs phrasing on proxy routing (#1124)Florimond Mancabefore adoption0fb28e8
lines 375–377why, one step back375376HTTPX supports routing proxies based on **scheme**, **domain**, **port**, or a combination of these.377Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
line 378why, one step back378#### Wildcard routingAdd 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
line 379why, one step back379Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 380–381why, one step back380Route everything through a proxy...381Add 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
line 382why, one step back382```pythonRevamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
line 383why, one step back383proxies = {Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4
line 384why, one step back384 "all://": "http://localhost:8030",Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
line 385why, one step back385}Add 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 386–387why, one step back386```387Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 388–393why, one step back388#### Scheme routing389390Route HTTP requests through one proxy, and HTTPS requests through another...391392```python393proxies = {Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4
lines 394–395why, one step back394 "http://": "http://localhost:8030",395 "https://": "http://localhost:8031",Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 396–459why, one step back396}397```398399#### Domain routing400401Proxy all requests on domain "example.com", let other requests pass through...402403```python404proxies = {405 "all://example.com": "http://localhost:8030",406}407```408409Proxy HTTP requests on domain "example.com", let HTTPS and other requests pass through...410411```python412proxies = {413 "http://example.com": "http://localhost:8030",414}415```416417Proxy all requests to "example.com" and its subdomains, let other requests pass through...418419```python420proxies = {421 "all://*example.com": "http://localhost:8030",422}423```424425Proxy all requests to strict subdomains of "example.com", let "example.com" and other requests pass through...426427```python428proxies = {429 "all://*.example.com": "http://localhost:8030",430}431```432433#### Port routing434435Proxy HTTPS requests on port 1234 to "example.com"...436437```python438proxies = {439 "https://example.com:1234": "http://localhost:8030",440}441```442443Proxy all requests on port 1234...444445```python446proxies = {447 "all://*:1234": "http://localhost:8030",448}449```450451#### No-proxy support452453It is also possible to define requests that _shouldn't_ be routed through proxies.454455To do so, pass `None` as the proxy URL. For example...456457```python458proxies = {459 # Route requests through a proxy by default...Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4
line 460why, one step back460 "all://": "http://localhost:8031",Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 461–472why, one step back461 # Except those for "example.com".462 "all://example.com": None,463}464```465466#### Complex configuration example467468You can combine the routing features outlined above to build complex proxy routing configurations. For example...469470```python471proxies = {472 # Route all traffic through a proxy by default...Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4
line 473why, one step back473 "all://": "http://localhost:8030",Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 474–491why, one step back474 # But don't use proxies for HTTPS requests to "domain.io"...475 "https://domain.io": None,476 # And use another proxy for requests to "example.com" and its subdomains...477 "all://*example.com": "http://localhost:8031",478 # And yet another proxy if HTTP is used,479 # and the "internal" subdomain on port 5550 is requested...480 "http://internal.example.com:5550": "http://localhost:8032",481}482```483484#### Environment variables485486HTTP proxying can also be configured through environment variables, although with less fine-grained control.487488See documentation on [`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`](/environment_variables/#http_proxy-https_proxy-all_proxy) for more information.489490### Proxy mechanisms491Add 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
line 492why, one step back492!!! noteRevamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
line 493why, one step back493 This section describes **advanced** proxy concepts and functionality.Add 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
line 494why, one step back494Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
line 495why, one step back495#### FORWARD vs TUNNELAdd 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
line 496why, one step back496Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 497–532why, one step back497In general, the flow for making an HTTP request through a proxy is as follows:4984991. The client connects to the proxy (initial connection request).5001. The proxy somehow transfers data to the server on your behalf.501502How exactly step 2/ is performed depends on which of two proxying mechanisms is used:503504* **Forwarding**: the proxy makes the request for you, and sends back the response it obtained from the server.505* **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).506507#### Default behavior508509Given the technical definitions above, by default (and regardless of whether you're using an HTTP or HTTPS proxy), HTTPX will:510511* Use forwarding for HTTP requests.512* Use tunneling for HTTPS requests.513514This ensures that you can make HTTP and HTTPS requests in all cases (i.e. regardless of which type of proxy you're using).515516#### Forcing the proxy mechanism517518In most cases, the default behavior should work just fine as well as provide enough security.519520But 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...521522```python523# Route all requests through an HTTPS proxy, using tunneling only.524proxies = httpx.Proxy(525 url="https://localhost:8030",526 mode="TUNNEL_ONLY",527)528529with httpx.Client(proxies=proxies) as client:530 # This HTTP request will be tunneled instead of forwarded.531 r = client.get("http://example.com")532```Add 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 533–582why, one step back533534## Timeout Configuration535536HTTPX is careful to enforce timeouts everywhere by default.537538The default behavior is to raise a `TimeoutException` after 5 seconds of539network inactivity.540541### Setting and disabling timeouts542543You can set timeouts for an individual request:544545```python546# Using the top-level API:547httpx.get('http://example.com/api/v1/example', timeout=10.0)548549# Using a client instance:550with httpx.Client() as client:551 client.get("http://example.com/api/v1/example", timeout=10.0)552```553554Or disable timeouts for an individual request:555556```python557# Using the top-level API:558httpx.get('http://example.com/api/v1/example', timeout=None)559560# Using a client instance:561with httpx.Client() as client:562 client.get("http://example.com/api/v1/example", timeout=None)563```564565### Setting a default timeout on a client566567You can set a timeout on a client instance, which results in the given568`timeout` being used as the default for requests made with this client:569570```python571client = httpx.Client() # Use a default 5s timeout everywhere.572client = httpx.Client(timeout=10.0) # Use a default 10s timeout everywhere.573client = httpx.Client(timeout=None) # Disable all timeouts by default.574```575576### Fine tuning the configuration577578HTTPX also allows you to specify the timeout behavior in more fine grained detail.579580There are four different types of timeouts that may occur. These are **connect**,581**read**, **write**, and **pool** timeouts.582Switch to more concise Timeout parameters (#1111)Florimond Mancabefore adoption26cd4f5
line 583why, one step back583* The **connect** timeout specifies the maximum amount of time to wait untilAdd 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 584–585why, one step back584a connection to the requested host is established. If HTTPX is unable to connect585within this time frame, a `ConnectTimeout` exception is raised.Switch to more concise Timeout parameters (#1111)Florimond Mancabefore adoption26cd4f5
line 586why, one step back586* The **read** timeout specifies the maximum duration to wait for a chunk ofAdd 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 587–588why, one step back587data to be received (for example, a chunk of the response body). If HTTPX is588unable to receive data within this time frame, a `ReadTimeout` exception is raised.Switch to more concise Timeout parameters (#1111)Florimond Mancabefore adoption26cd4f5
line 589why, one step back589* The **write** timeout specifies the maximum duration to wait for a chunk ofAdd 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 590–591why, one step back590data to be sent (for example, a chunk of the request body). If HTTPX is unable591to send data within this time frame, a `WriteTimeout` exception is raised.Switch to more concise Timeout parameters (#1111)Florimond Mancabefore adoption26cd4f5
line 592why, one step back592* The **pool** timeout specifies the maximum duration to wait for acquiringAdd 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 593–601why, one step back593a connection from the connection pool. If HTTPX is unable to acquire a connection594within this time frame, a `PoolTimeout` exception is raised. A related595configuration here is the maximum number of allowable connections in the596connection pool, which is configured by the `pool_limits`.597598You can configure the timeout behavior for any of these values...599600```python601# A client with a 60s timeout for connecting, and a 10s timeout elsewhere.Switch to more concise Timeout parameters (#1111)Florimond Mancabefore adoption26cd4f5
line 602why, one step back602timeout = httpx.Timeout(10.0, connect=60.0)Add 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 603–607why, one step back603client = httpx.Client(timeout=timeout)604605response = client.get('http://example.com/')606```607Document pool_limits and SSL context on verify (#942)Yeray Diaz Diazbefore adoption790a3ea
lines 608–609why, one step back608## Pool limit configuration609Rename PoolLimits to Limits (#1113)Florimond Mancabefore adoptionf67e925
lines 610–611why, one step back610You can control the connection pool size using the `limits` keyword611argument on the client. It takes instances of `httpx.Limits` which define:Document pool_limits and SSL context on verify (#942)Yeray Diaz Diazbefore adoption790a3ea
line 612why, one step back612Rename pool limit options (#968)Tom Christiebefore adoption991915a
line 613why, one step back613- `max_keepalive`, number of allowable keep-alive connections, or `None` to alwaysDocument pool_limits and SSL context on verify (#942)Yeray Diaz Diazbefore adoption790a3ea
line 614why, one step back614allow. (Defaults 10)Rename pool limit options (#968)Tom Christiebefore adoption991915a
line 615why, one step back615- `max_connections`, maximum number of allowable connections, or` None` for no limits.Document pool_limits and SSL context on verify (#942)Yeray Diaz Diazbefore adoption790a3ea
lines 616–619why, one step back616(Default 100)617618619```pythonRename PoolLimits to Limits (#1113)Florimond Mancabefore adoptionf67e925
lines 620–621why, one step back620limits = httpx.Limits(max_keepalive=5, max_connections=10)621client = httpx.Client(limits=limits)Document pool_limits and SSL context on verify (#942)Yeray Diaz Diazbefore adoption790a3ea
lines 622–623why, one step back622```623Add 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 624–629why, one step back624## Multipart file encoding625626As mentioned in the [quickstart](/quickstart#sending-multipart-file-uploads)627multipart file encoding is available by passing a dictionary with the628name of the payloads as keys and either tuple of elements or a file-like object or a string as values.629Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 630why, one step back630```pyconAdd 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 631–654why, one step back631>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}632>>> r = httpx.post("https://httpbin.org/post", files=files)633>>> print(r.text)634{635 ...636 "files": {637 "upload-file": "<... binary content ...>"638 },639 ...640}641```642643More specifically, if a tuple is used as a value, it must have between 2 and 3 elements:644645- The first element is an optional file name which can be set to `None`.646- The second element may be a file-like object or a string which will be automatically647encoded in UTF-8.648- An optional third element can be used to specify the649[MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_Types)650of the file being uploaded. If not specified HTTPX will attempt to guess the MIME type based651on the file name, with unknown file extensions defaulting to "application/octet-stream".652If the file name is explicitly set to `None` then HTTPX will not include a content-type653MIME header field.654Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 655why, one step back655```pyconAdd 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 656–668why, one step back656>>> files = {'upload-file': (None, 'text content', 'text/plain')}657>>> r = httpx.post("https://httpbin.org/post", files=files)658>>> print(r.text)659{660 ...661 "files": {},662 "form": {663 "upload-file": "text-content"664 },665 ...666}667```668Add note on streaming uploads (#973)Florimond Mancabefore adoptiona58be59
lines 669–670why, one step back669!!! tip670 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 671why, one step back671Add note on data fields in multipart form encoding (#1022)Florimond Mancabefore adoption0f7d644
line 672why, one step back672 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 673why, one step back673Add support for multiple files per POST field (#1032)euri10before adoption4d28795
lines 674–675why, one step back674You can also send multiple files in one go with a multiple file field form.675To 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 676why, one step back676For instance this request sends 2 files, `foo.png` and `bar.png` in one request on the `images` form field:Add support for multiple files per POST field (#1032)euri10before adoption4d28795
line 677why, one step back677Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 678why, one step back678```pyconAdd support for multiple files per POST field (#1032)euri10before adoption4d28795
lines 679–682why, one step back679>>> files = [('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),680 ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]681>>> r = httpx.post("https://httpbin.org/post", files=files)682```Add note on data fields in multipart form encoding (#1022)Florimond Mancabefore adoption0f7d644
line 683why, one step back683Add 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 684–781why, one step back684## Customizing authentication685686When 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...687688* A two-tuple of `username`/`password`, to be used with basic authentication.689* An instance of `httpx.BasicAuth()` or `httpx.DigestAuth()`.690* A callable, accepting a request and returning an authenticated request instance.691* A subclass of `httpx.Auth`.692693The 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...694695```python696class MyCustomAuth(httpx.Auth):697 def __init__(self, token):698 self.token = token699700 def auth_flow(self, request):701 # Send the request, with a custom `X-Authentication` header.702 request.headers['X-Authentication'] = self.token703 yield request704```705706If the auth flow requires more that one request, you can issue multiple yields, and obtain the response in each case...707708```python709class MyCustomAuth(httpx.Auth):710 def __init__(self, token):711 self.token = token712713 def auth_flow(self, request):714 response = yield request715 if response.status_code == 401:716 # If the server issues a 401 response then resend the request,717 # with a custom `X-Authentication` header.718 request.headers['X-Authentication'] = self.token719 yield request720```721722Custom 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.723724You will then be able to access `request.content` inside the `.auth_flow()` method.725726```python727class MyCustomAuth(httpx.Auth):728 requires_request_body = True729730 def __init__(self, token):731 self.token = token732733 def auth_flow(self, request):734 response = yield request735 if response.status_code == 401:736 # If the server issues a 401 response then resend the request,737 # with a custom `X-Authentication` header.738 request.headers['X-Authentication'] = self.sign_request(...)739 yield request740741 def sign_request(self, request):742 # Create a request signature, based on `request.method`, `request.url`,743 # `request.headers`, and `request.content`.744 ...745```746747Similarly, 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.748749```python750class MyCustomAuth(httpx.Auth):751 requires_response_body = True752753 def __init__(self, access_token, refresh_token, refresh_url):754 self.access_token = access_token755 self.refresh_token = refresh_token756 self.refresh_url = refresh_url757758 def auth_flow(self, request):759 request.headers["X-Authentication"] = self.access_token760 response = yield request761762 if response.status_code == 401:763 # If the server issues a 401 response, then issue a request to764 # refresh tokens, and resend the request.765 refresh_response = yield self.build_refresh_request()766 self.update_tokens(refresh_response)767768 request.headers["X-Authentication"] = self.access_token769 yield request770771 def build_refresh_request(self):772 # Return an `httpx.Request` for refreshing tokens.773 ...774775 def update_tokens(self, response):776 # Update the `.access_token` and `.refresh_token` tokens777 # based on a refresh response.778 data = response.json()779 ...780```781Add support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee
lines 782–830why, one step back782If 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`.783784```python785import asyncio786import threading787import httpx788789790class MyCustomAuth(httpx.Auth):791 def __init__(self):792 self._sync_lock = threading.RLock()793 self._async_lock = asyncio.Lock()794795 def sync_get_token(self):796 with self._sync_lock:797 ...798799 def sync_auth_flow(self, request):800 token = self.sync_get_token()801 request.headers["Authorization"] = f"Token {token}"802 yield request803804 async def async_get_token(self):805 async with self._async_lock:806 ...807808 async def async_auth_flow(self, request):809 token = await self.async_get_token()810 request.headers["Authorization"] = f"Token {token}"811 yield request812```813814If you only want to support one of the two methods, then you should still override it, but raise an explicit `RuntimeError`.815816```python817import httpx818import sync_only_library819820821class MyCustomAuth(httpx.Auth):822 def sync_auth_flow(self, request):823 token = sync_only_library.get_token(...)824 request.headers["Authorization"] = f"Token {token}"825 yield request826827 async def async_auth_flow(self, request):828 raise RuntimeError("Cannot use a sync authentication class with httpx.AsyncClient")829```830Add 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 831–846why, one step back831## SSL certificates832833When 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).834835### Changing the verification defaults836837By 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.838839If you'd like to use a custom CA bundle, you can use the `verify` parameter.840841```python842import httpx843844r = httpx.get("https://example.org", verify="path/to/client.pem")845```846Document pool_limits and SSL context on verify (#942)Yeray Diaz Diazbefore adoption790a3ea
lines 847–848why, one step back847Alternatively, you can pass a standard library `ssl.SSLContext`.848Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 849why, one step back849```pyconDocument pool_limits and SSL context on verify (#942)Yeray Diaz Diazbefore adoption790a3ea
lines 850–857why, one step back850>>> import ssl851>>> import httpx852>>> context = ssl.create_default_context()853>>> context.load_verify_locations(cafile="/tmp/client.pem")854>>> httpx.get('https://example.org', verify=context)855<Response [200 OK]>856```857Included create_ssl_context function to create the same context with SSLConfig and serve as API (#996)Can Sarıgölbefore adoption926a55a
lines 858–859why, one step back858We also include a helper function for creating properly configured `SSLContext` instances.859Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 860why, one step back860```pyconIncluded create_ssl_context function to create the same context with SSLConfig and serve as API (#996)Can Sarıgölbefore adoption926a55a
lines 861–863why, one step back861>>> context = httpx.create_ssl_context()862```863Advanced transport docs (#1165)Tom Christiebefore adoption477824a
lines 864–865why, one step back864The `create_ssl_context` function accepts the same set of SSL configuration arguments865(`trust_env`, `verify`, `cert` and `http2` arguments)Included create_ssl_context function to create the same context with SSLConfig and serve as API (#996)Can Sarıgölbefore adoption926a55a
lines 866–867why, one step back866as `httpx.Client` or `httpx.AsyncClient`867Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 868why, one step back868```pyconIncluded create_ssl_context function to create the same context with SSLConfig and serve as API (#996)Can Sarıgölbefore adoption926a55a
lines 869–874why, one step back869>>> import httpx870>>> context = httpx.create_ssl_context(verify="/tmp/client.pem")871>>> httpx.get('https://example.org', verify=context)872<Response [200 OK]>873```874Document pool_limits and SSL context on verify (#942)Yeray Diaz Diazbefore adoption790a3ea
line 875why, one step back875Or you can also disable the SSL verification entirely, which is _not_ recommended.Add 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 876–902why, one step back876877```python878import httpx879880r = httpx.get("https://example.org", verify=False)881```882883### SSL configuration on client instances884885If you're using a `Client()` instance, then you should pass any SSL settings when instantiating the client.886887```python888client = httpx.Client(verify=False)889```890891The `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.892893### Making HTTPS requests to a local server894895When making requests to local servers, such as a development server running on `localhost`, you will typically be using unencrypted HTTP connections.896897If 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:8988991. Use [trustme-cli](https://github.com/sethmlarson/trustme-cli/) to generate a pair of server key/cert files, and a client cert file.9001. 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.)9011. Tell HTTPX to use the certificates stored in `client.pem`:902Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 903why, one step back903```pyconAdd 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
lines 904–907why, one step back904>>> import httpx905>>> r = httpx.get("https://localhost:8000", verify="/tmp/client.pem")906>>> r907Response <200 OK>Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
lines 908–915why, one step back908```909910## Custom Transports911912HTTPX's `Client` also accepts a `transport` argument. This argument allows you913to provide a custom Transport object that will be used to perform the actual914sending of the requests.915Drop urllib3 in favor of public gist (#1182)Florimond Mancabefore adoption8fa8765
lines 916–917why, one step back916### Usage917Advanced transport docs (#1165)Tom Christiebefore adoption477824a
lines 918–921why, one step back918For some advanced configuration you might need to instantiate a transport919class directly, and pass it to the client instance. The `httpcore` package920provides a `local_address` configuration that is only available via this921low-level API.Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
line 922why, one step back922Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 923why, one step back923```pyconAdvanced transport docs (#1165)Tom Christiebefore adoption477824a
lines 924–935why, one step back924>>> import httpx, httpcore925>>> ssl_context = httpx.create_ssl_context()926>>> transport = httpcore.SyncConnectionPool(927... ssl_context=ssl_context,928... max_connections=100,929... max_keepalive_connections=20,930... keepalive_expiry=5.0,931... local_address="0.0.0.0"932... ) # Use the standard HTTPX defaults, but with an IPv4 only 'local_address'.933>>> client = httpx.Client(transport=transport)934```935Document Unix Domain Socket usage (#1186)Florimond Mancabefore adoption34ba0e1
lines 936–953why, one step back936Similarly, `httpcore` provides a `uds` option for connecting via a Unix Domain Socket that is only available via this low-level API:937938```python939>>> import httpx, httpcore940>>> ssl_context = httpx.create_ssl_context()941>>> transport = httpcore.SyncConnectionPool(942... ssl_context=ssl_context,943... max_connections=100,944... max_keepalive_connections=20,945... keepalive_expiry=5.0,946... uds="/var/run/docker.sock",947... ) # Connect to the Docker API via a Unix Socket.948>>> client = httpx.Client(transport=transport)949>>> response = client.get("http://docker/info")950>>> response.json()951{"ID": "...", "Containers": 4, "Images": 74, ...}952```953Advanced transport docs (#1165)Tom Christiebefore adoption477824a
lines 954–958why, one step back954Unlike the `httpx.Client()`, the lower-level `httpcore` transport instances955do not include any default values for configuring aspects such as the956connection pooling details, so you'll need to provide more explicit957configuration when using this API.958Drop urllib3 in favor of public gist (#1182)Florimond Mancabefore adoption8fa8765
line 959why, one step back959### urllib3 transportTransport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
line 960why, one step back960Drop urllib3 in favor of public gist (#1182)Florimond Mancabefore adoption8fa8765
lines 961–962why, one step back961This [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`...962Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 963why, one step back963```pyconTransport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
line 964why, one step back964>>> import httpxDrop urllib3 in favor of public gist (#1182)Florimond Mancabefore adoption8fa8765
lines 965–966why, one step back965>>> from urllib3_transport import URLLib3Transport966>>> client = httpx.Client(transport=URLLib3Transport())Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
lines 967–970why, one step back967>>> client.get("https://example.org")968<Response [200 OK]>969```970Drop urllib3 in favor of public gist (#1182)Florimond Mancabefore adoption8fa8765
line 971why, one step back971### Writing custom transportsUpdate dependencies in docs (#969)Tom Christiebefore adoption99a5c78
line 972why, one step back972Advanced transport docs (#1165)Tom Christiebefore adoption477824a
lines 973–978why, one step back973A transport instance must implement the Transport API defined by974[`httpcore`](https://www.encode.io/httpcore/api/). You975should either subclass `httpcore.AsyncHTTPTransport` to implement a transport to976use with `AsyncClient`, or subclass `httpcore.SyncHTTPTransport` to implement a977transport to use with `Client`.978Update dependencies in docs (#969)Tom Christiebefore adoption99a5c78
line 979why, one step back979A complete example of a custom transport implementation would be:Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
lines 980–985why, one step back980981```python982import json983import httpcore984985Advanced transport docs (#1165)Tom Christiebefore adoption477824a
line 986why, one step back986class HelloWorldTransport(httpcore.SyncHTTPTransport):Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
line 987why, one step back987 """Advanced transport docs (#1165)Tom Christiebefore adoption477824a
line 988why, one step back988 A mock transport that always returns a JSON "Hello, world!" response.Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
lines 989–991why, one step back989 """990991 def request(self, method, url, headers=None, stream=None, timeout=None):Advanced transport docs (#1165)Tom Christiebefore adoption477824a
lines 992–994why, one step back992 message = {"text": "Hello, world!"}993 content = json.dumps(message).encode("utf-8")994 stream = httpcore.PlainByteStream(content)Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
lines 995–1000why, one step back995 headers = [(b"content-type", b"application/json")]996 return b"HTTP/1.1", 200, b"OK", headers, stream997```998999Which we can use in the same way:1000Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 1001why, one step back1001```pyconAdvanced transport docs (#1165)Tom Christiebefore adoption477824a
lines 1002–1004why, one step back1002>>> import httpx1003>>> client = httpx.Client(transport=HelloWorldTransport())1004>>> response = client.get("https://example.org/")Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
line 1005why, one step back1005>>> response.json()Advanced transport docs (#1165)Tom Christiebefore adoption477824a
line 1006why, one step back1006{"text": "Hello, world!"}Add 'Third Party Packages' docs page (#876)Florimond Mancabefore adoption21f5337
line 1007why, one step back1007```