advanced.md
This file
Path
docs/advanced.md
1,296 lines · 44.6 KiB · Markdown
Last changed by
docs: upload progress (#2725)Trim21before adoptionf115ce4
History of this fileTake it
The walk stopped after 200 commits: lines older than 8088fc7 point at it.
Test under 3.11-dev (#2302)Jobefore adoption8088fc7
lines 1–428why, 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.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.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 persistence across requests.30- Applying configuration across all outgoing requests.31- Sending requests through HTTP proxies.32- Using [HTTP/2](http2.md).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:5859```pycon60>>> 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.md) guide are also available at the client level.6869For 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```145146For a list of all available client parameters, see the [`Client`](api.md#client) API reference.147148---149150## Character set encodings and auto-detection151152When accessing `response.text`, we need to decode the response bytes into a unicode text representation.153154By default `httpx` will use `"charset"` information included in the response `Content-Type` header to determine how the response bytes should be decoded into text.155156In cases where no charset information is included on the response, the default behaviour is to assume "utf-8" encoding, which is by far the most widely used text encoding on the internet.157158### Using the default encoding159160To understand this better let's start by looking at the default behaviour for text decoding...161162```python163import httpx164# Instantiate a client with the default configuration.165client = httpx.Client()166# Using the client...167response = client.get(...)168print(response.encoding) # This will either print the charset given in169 # the Content-Type charset, or else "utf-8".170print(response.text) # The text will either be decoded with the Content-Type171 # charset, or using "utf-8".172```173174This is normally absolutely fine. Most servers will respond with a properly formatted Content-Type header, including a charset encoding. And in most cases where no charset encoding is included, UTF-8 is very likely to be used, since it is so widely adopted.175176### Using an explicit encoding177178In some cases we might be making requests to a site where no character set information is being set explicitly by the server, but we know what the encoding is. In this case it's best to set the default encoding explicitly on the client.179180```python181import httpx182# Instantiate a client with a Japanese character set as the default encoding.183client = httpx.Client(default_encoding="shift-jis")184# Using the client...185response = client.get(...)186print(response.encoding) # This will either print the charset given in187 # the Content-Type charset, or else "shift-jis".188print(response.text) # The text will either be decoded with the Content-Type189 # charset, or using "shift-jis".190```191192### Using character set auto-detection193194In cases where the server is not reliably including character set information, and where we don't know what encoding is being used, we can enable auto-detection to make a best-guess attempt when decoding from bytes to text.195196To use auto-detection you need to set the `default_encoding` argument to a callable instead of a string. This callable should be a function which takes the input bytes as an argument and returns the character set to use for decoding those bytes to text.197198There are two widely used Python packages which both handle this functionality:199200* [`chardet`](https://chardet.readthedocs.io/) - This is a well established package, and is a port of [the auto-detection code in Mozilla](https://www-archive.mozilla.org/projects/intl/chardet.html).201* [`charset-normalizer`](https://charset-normalizer.readthedocs.io/) - A newer package, motivated by `chardet`, with a different approach.202203Let's take a look at installing autodetection using one of these packages...204205 ```shell206$ pip install httpx207$ pip install chardet208 ```209210Once `chardet` is installed, we can configure a client to use character-set autodetection.211212```python213import httpx214import chardet215216def autodetect(content):217 return chardet.detect(content).get("encoding")218219# Using a client with character-set autodetection enabled.220client = httpx.Client(default_encoding=autodetect)221response = client.get(...)222print(response.encoding) # This will either print the charset given in223 # the Content-Type charset, or else the auto-detected224 # character set.225print(response.text)226```227228---229230## Calling into Python Web Apps231232You can configure an `httpx` client to call directly into a Python web application using the WSGI protocol.233234This is particularly useful for two main use-cases:235236* Using `httpx` as a client inside test cases.237* Mocking out external services during tests or in dev/staging environments.238239Here's an example of integrating against a Flask application:240241```python242from flask import Flask243import httpx244245246app = Flask(__name__)247248@app.route("/")249def hello():250 return "Hello World!"251252with httpx.Client(app=app, base_url="http://testserver") as client:253 r = client.get("/")254 assert r.status_code == 200255 assert r.text == "Hello World!"256```257258For some more complex cases you might need to customize the WSGI transport. This allows you to:259260* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.261* Mount the WSGI application at a subpath by setting `script_name` (WSGI).262* Use a given client address for requests by setting `remote_addr` (WSGI).263264For example:265266```python267# Instantiate a client that makes WSGI requests with a client IP of "1.2.3.4".268transport = httpx.WSGITransport(app=app, remote_addr="1.2.3.4")269with httpx.Client(transport=transport, base_url="http://testserver") as client:270 ...271```272273## Request instances274275For maximum control on what gets sent over the wire, HTTPX supports building explicit [`Request`](api.md#request) instances:276277```python278request = httpx.Request("GET", "https://example.com")279```280281To dispatch a `Request` instance across to the network, create a [`Client` instance](#client-instances) and use `.send()`:282283```python284with httpx.Client() as client:285 response = client.send(request)286 ...287```288289If 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:290291```python292headers = {"X-Api-Key": "...", "X-Client-ID": "ABC123"}293294with httpx.Client(headers=headers) as client:295 request = client.build_request("GET", "https://api.example.com")296297 print(request.headers["X-Client-ID"]) # "ABC123"298299 # Don't send the API key for this particular request.300 del request.headers["X-Api-Key"]301302 response = client.send(request)303 ...304```305306## Event Hooks307308HTTPX allows you to register "event hooks" with the client, that are called309every time a particular type of event takes place.310311There are currently two event hooks:312313* `request` - Called after a request is fully prepared, but before it is sent to the network. Passed the `request` instance.314* `response` - Called after the response has been fetched from the network, but before it is returned to the caller. Passed the `response` instance.315316These allow you to install client-wide functionality such as logging, monitoring or tracing.317318```python319def log_request(request):320 print(f"Request event hook: {request.method} {request.url} - Waiting for response")321322def log_response(response):323 request = response.request324 print(f"Response event hook: {request.method} {request.url} - Status {response.status_code}")325326client = httpx.Client(event_hooks={'request': [log_request], 'response': [log_response]})327```328329You can also use these hooks to install response processing code, such as this330example, which creates a client instance that always raises `httpx.HTTPStatusError`331on 4xx and 5xx responses.332333```python334def raise_on_4xx_5xx(response):335 response.raise_for_status()336337client = httpx.Client(event_hooks={'response': [raise_on_4xx_5xx]})338```339340!!! note341 Response event hooks are called before determining if the response body342 should be read or not.343344 If you need access to the response body inside an event hook, you'll345 need to call `response.read()`, or for AsyncClients, `response.aread()`.346347The hooks are also allowed to modify `request` and `response` objects.348349```python350def add_timestamp(request):351 request.headers['x-request-timestamp'] = datetime.now(tz=datetime.utc).isoformat()352353client = httpx.Client(event_hooks={'request': [add_timestamp]})354```355356Event hooks must always be set as a **list of callables**, and you may register357multiple event hooks for each type of event.358359As well as being able to set event hooks on instantiating the client, there360is also an `.event_hooks` property, that allows you to inspect and modify361the installed hooks.362363```python364client = httpx.Client()365client.event_hooks['request'] = [log_request]366client.event_hooks['response'] = [log_response, raise_on_4xx_5xx]367```368369!!! note370 If you are using HTTPX's async support, then you need to be aware that371 hooks registered with `httpx.AsyncClient` MUST be async functions,372 rather than plain functions.373374## Monitoring download progress375376If you need to monitor download progress of large responses, you can use response streaming and inspect the `response.num_bytes_downloaded` property.377378This 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.379380For 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…381382```python383import tempfile384385import httpx386from tqdm import tqdm387388with tempfile.NamedTemporaryFile() as download_file:389 url = "https://speed.hetzner.de/100MB.bin"390 with httpx.stream("GET", url) as response:391 total = int(response.headers["Content-Length"])392393 with tqdm(total=total, unit_scale=True, unit_divisor=1024, unit="B") as progress:394 num_bytes_downloaded = response.num_bytes_downloaded395 for chunk in response.iter_bytes():396 download_file.write(chunk)397 progress.update(response.num_bytes_downloaded - num_bytes_downloaded)398 num_bytes_downloaded = response.num_bytes_downloaded399```400401402403Or an alternate example, this time using the [`rich`](https://github.com/willmcgugan/rich) library…404405```python406import tempfile407import httpx408import rich.progress409410with tempfile.NamedTemporaryFile() as download_file:411 url = "https://speed.hetzner.de/100MB.bin"412 with httpx.stream("GET", url) as response:413 total = int(response.headers["Content-Length"])414415 with rich.progress.Progress(416 "[progress.percentage]{task.percentage:>3.0f}%",417 rich.progress.BarColumn(bar_width=None),418 rich.progress.DownloadColumn(),419 rich.progress.TransferSpeedColumn(),420 ) as progress:421 download_task = progress.add_task("Download", total=total)422 for chunk in response.iter_bytes():423 download_file.write(chunk)424 progress.update(download_task, completed=response.num_bytes_downloaded)425```426427428docs: upload progress (#2725)Trim21before adoptionf115ce4
lines 429–460why, one step back429## Monitoring upload progress430431If you need to monitor upload progress of large responses, you can use request content generator streaming.432433For example, showing a progress bar using the [`tqdm`](https://github.com/tqdm/tqdm) library.434435```python436import io437import random438439import httpx440from tqdm import tqdm441442443def gen():444 """445 this is a complete example with generated random bytes.446 you can replace `io.BytesIO` with real file object.447 """448 total = 32 * 1024 * 1024 # 32m449 with tqdm(ascii=True, unit_scale=True, unit='B', unit_divisor=1024, total=total) as bar:450 with io.BytesIO(random.randbytes(total)) as f:451 while data := f.read(1024):452 yield data453 bar.update(len(data))454455456httpx.post("https://httpbin.org/post", content=gen())457```458459460Test under 3.11-dev (#2302)Jobefore adoption8088fc7
lines 461–462why, one step back461## .netrc Support462Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
line 463why, one step back463HTTPX can be configured to use [a `.netrc` config file](https://everything.curl.dev/usingcurl/netrc) for authentication.Test under 3.11-dev (#2302)Jobefore adoption8088fc7
line 464why, one step back464Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
line 465why, one step back465The `.netrc` config file allows authentication credentials to be associated with specified hosts. When a request is made to a host that is found in the netrc file, the username and password will be included using HTTP basic auth.Test under 3.11-dev (#2302)Jobefore adoption8088fc7
line 466why, one step back466Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
lines 467–468why, one step back467Example `.netrc` file:468Test under 3.11-dev (#2302)Jobefore adoption8088fc7
line 469why, one step back469```Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
lines 470–472why, one step back470machine example.org471login example-username472password example-passwordTest under 3.11-dev (#2302)Jobefore adoption8088fc7
line 473why, one step back473Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
lines 474–477why, one step back474machine python-httpx.org475login other-username476password other-password477```Test under 3.11-dev (#2302)Jobefore adoption8088fc7
line 478why, one step back478Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
lines 479–482why, one step back479Some examples of configuring `.netrc` authentication with `httpx`.480481Use the default `.netrc` file in the users home directory:482Test under 3.11-dev (#2302)Jobefore adoption8088fc7
line 483why, one step back483```pyconAdd `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
lines 484–485why, one step back484>>> auth = httpx.NetRCAuth()485>>> client = httpx.Client(auth=auth)Test under 3.11-dev (#2302)Jobefore adoption8088fc7
lines 486–487why, one step back486```487Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
line 488why, one step back488Use an explicit path to a `.netrc` file:Test under 3.11-dev (#2302)Jobefore adoption8088fc7
line 489why, one step back489Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
lines 490–492why, one step back490```pycon491>>> auth = httpx.NetRCAuth(file="/path/to/.netrc")492>>> client = httpx.Client(auth=auth)Test under 3.11-dev (#2302)Jobefore adoption8088fc7
lines 493–494why, one step back493```494Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
lines 495–496why, one step back495Use the `NETRC` environment variable to configure a path to the `.netrc` file,496or fallback to the default.Test under 3.11-dev (#2302)Jobefore adoption8088fc7
line 497why, one step back497Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
lines 498–500why, one step back498```pycon499>>> auth = httpx.NetRCAuth(file=os.environ.get("NETRC"))500>>> client = httpx.Client(auth=auth)Test under 3.11-dev (#2302)Jobefore adoption8088fc7
lines 501–502why, one step back501```502Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
lines 503–504why, one step back503The `NetRCAuth()` class uses [the `netrc.netrc()` function from the Python standard library](https://docs.python.org/3/library/netrc.html). See the documentation there for more details on exceptions that may be raised if the netrc file is not found, or cannot be parsed.504Test under 3.11-dev (#2302)Jobefore adoption8088fc7
lines 505–867why, one step back505## HTTP Proxying506507HTTPX 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=...)`.508509<div align="center">510 <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/27/Open_proxy_h2g2bob.svg/480px-Open_proxy_h2g2bob.svg.png"/>511 <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>512</div>513514### Example515516To route all traffic (HTTP and HTTPS) to a proxy located at `http://localhost:8030`, pass the proxy URL to the client...517518```python519with httpx.Client(proxies="http://localhost:8030") as client:520 ...521```522523For 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:524525```python526proxies = {527 "http://": "http://localhost:8030",528 "https://": "http://localhost:8031",529}530531with httpx.Client(proxies=proxies) as client:532 ...533```534535For detailed information about proxy routing, see the [Routing](#routing) section.536537!!! tip "Gotcha"538 In most cases, the proxy URL for the `https://` key _should_ use the `http://` scheme (that's not a typo!).539540 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.541542 For more information, see [FORWARD vs TUNNEL](#forward-vs-tunnel).543544### Authentication545546Proxy credentials can be passed as the `userinfo` section of the proxy URL. For example:547548```python549proxies = {550 "http://": "http://username:password@localhost:8030",551 # ...552}553```554555### Routing556557HTTPX provides fine-grained controls for deciding which requests should go through a proxy, and which shouldn't. This process is known as proxy routing.558559The `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://`).560561HTTPX supports routing proxies based on **scheme**, **domain**, **port**, or a combination of these.562563#### Wildcard routing564565Route everything through a proxy...566567```python568proxies = {569 "all://": "http://localhost:8030",570}571```572573#### Scheme routing574575Route HTTP requests through one proxy, and HTTPS requests through another...576577```python578proxies = {579 "http://": "http://localhost:8030",580 "https://": "http://localhost:8031",581}582```583584#### Domain routing585586Proxy all requests on domain "example.com", let other requests pass through...587588```python589proxies = {590 "all://example.com": "http://localhost:8030",591}592```593594Proxy HTTP requests on domain "example.com", let HTTPS and other requests pass through...595596```python597proxies = {598 "http://example.com": "http://localhost:8030",599}600```601602Proxy all requests to "example.com" and its subdomains, let other requests pass through...603604```python605proxies = {606 "all://*example.com": "http://localhost:8030",607}608```609610Proxy all requests to strict subdomains of "example.com", let "example.com" and other requests pass through...611612```python613proxies = {614 "all://*.example.com": "http://localhost:8030",615}616```617618#### Port routing619620Proxy HTTPS requests on port 1234 to "example.com"...621622```python623proxies = {624 "https://example.com:1234": "http://localhost:8030",625}626```627628Proxy all requests on port 1234...629630```python631proxies = {632 "all://*:1234": "http://localhost:8030",633}634```635636#### No-proxy support637638It is also possible to define requests that _shouldn't_ be routed through proxies.639640To do so, pass `None` as the proxy URL. For example...641642```python643proxies = {644 # Route requests through a proxy by default...645 "all://": "http://localhost:8031",646 # Except those for "example.com".647 "all://example.com": None,648}649```650651#### Complex configuration example652653You can combine the routing features outlined above to build complex proxy routing configurations. For example...654655```python656proxies = {657 # Route all traffic through a proxy by default...658 "all://": "http://localhost:8030",659 # But don't use proxies for HTTPS requests to "domain.io"...660 "https://domain.io": None,661 # And use another proxy for requests to "example.com" and its subdomains...662 "all://*example.com": "http://localhost:8031",663 # And yet another proxy if HTTP is used,664 # and the "internal" subdomain on port 5550 is requested...665 "http://internal.example.com:5550": "http://localhost:8032",666}667```668669#### Environment variables670671HTTP proxying can also be configured through environment variables, although with less fine-grained control.672673See documentation on [`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`](environment_variables.md#http_proxy-https_proxy-all_proxy) for more information.674675### Proxy mechanisms676677!!! note678 This section describes **advanced** proxy concepts and functionality.679680#### FORWARD vs TUNNEL681682In general, the flow for making an HTTP request through a proxy is as follows:6836841. The client connects to the proxy (initial connection request).6852. The proxy transfers data to the server on your behalf.686687How exactly step 2/ is performed depends on which of two proxying mechanisms is used:688689* **Forwarding**: the proxy makes the request for you, and sends back the response it obtained from the server.690* **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).691692### Troubleshooting proxies693694If you encounter issues when setting up proxies, please refer to our [Troubleshooting guide](troubleshooting.md#proxies).695696## SOCKS697698In addition to HTTP proxies, `httpcore` also supports proxies using the SOCKS protocol.699This is an optional feature that requires an additional third-party library be installed before use.700701You can install SOCKS support using `pip`:702703```shell704$ pip install httpx[socks]705```706707You can now configure a client to make requests via a proxy using the SOCKS protocol:708709```python710httpx.Client(proxies='socks5://user:pass@host:port')711```712713## Timeout Configuration714715HTTPX is careful to enforce timeouts everywhere by default.716717The default behavior is to raise a `TimeoutException` after 5 seconds of718network inactivity.719720### Setting and disabling timeouts721722You can set timeouts for an individual request:723724```python725# Using the top-level API:726httpx.get('http://example.com/api/v1/example', timeout=10.0)727728# Using a client instance:729with httpx.Client() as client:730 client.get("http://example.com/api/v1/example", timeout=10.0)731```732733Or disable timeouts for an individual request:734735```python736# Using the top-level API:737httpx.get('http://example.com/api/v1/example', timeout=None)738739# Using a client instance:740with httpx.Client() as client:741 client.get("http://example.com/api/v1/example", timeout=None)742```743744### Setting a default timeout on a client745746You can set a timeout on a client instance, which results in the given747`timeout` being used as the default for requests made with this client:748749```python750client = httpx.Client() # Use a default 5s timeout everywhere.751client = httpx.Client(timeout=10.0) # Use a default 10s timeout everywhere.752client = httpx.Client(timeout=None) # Disable all timeouts by default.753```754755### Fine tuning the configuration756757HTTPX also allows you to specify the timeout behavior in more fine grained detail.758759There are four different types of timeouts that may occur. These are **connect**,760**read**, **write**, and **pool** timeouts.761762* The **connect** timeout specifies the maximum amount of time to wait until763a socket connection to the requested host is established. If HTTPX is unable to connect764within this time frame, a `ConnectTimeout` exception is raised.765* The **read** timeout specifies the maximum duration to wait for a chunk of766data to be received (for example, a chunk of the response body). If HTTPX is767unable to receive data within this time frame, a `ReadTimeout` exception is raised.768* The **write** timeout specifies the maximum duration to wait for a chunk of769data to be sent (for example, a chunk of the request body). If HTTPX is unable770to send data within this time frame, a `WriteTimeout` exception is raised.771* The **pool** timeout specifies the maximum duration to wait for acquiring772a connection from the connection pool. If HTTPX is unable to acquire a connection773within this time frame, a `PoolTimeout` exception is raised. A related774configuration here is the maximum number of allowable connections in the775connection pool, which is configured by the `limits` argument.776777You can configure the timeout behavior for any of these values...778779```python780# A client with a 60s timeout for connecting, and a 10s timeout elsewhere.781timeout = httpx.Timeout(10.0, connect=60.0)782client = httpx.Client(timeout=timeout)783784response = client.get('http://example.com/')785```786787## Pool limit configuration788789You can control the connection pool size using the `limits` keyword790argument on the client. It takes instances of `httpx.Limits` which define:791792- `max_keepalive_connections`, number of allowable keep-alive connections, or `None` to always793allow. (Defaults 20)794- `max_connections`, maximum number of allowable connections, or `None` for no limits.795(Default 100)796- `keepalive_expiry`, time limit on idle keep-alive connections in seconds, or `None` for no limits. (Default 5)797798```python799limits = httpx.Limits(max_keepalive_connections=5, max_connections=10)800client = httpx.Client(limits=limits)801```802803## Multipart file encoding804805As mentioned in the [quickstart](quickstart.md#sending-multipart-file-uploads)806multipart file encoding is available by passing a dictionary with the807name of the payloads as keys and either tuple of elements or a file-like object or a string as values.808809```pycon810>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}811>>> r = httpx.post("https://httpbin.org/post", files=files)812>>> print(r.text)813{814 ...815 "files": {816 "upload-file": "<... binary content ...>"817 },818 ...819}820```821822More specifically, if a tuple is used as a value, it must have between 2 and 3 elements:823824- The first element is an optional file name which can be set to `None`.825- The second element may be a file-like object or a string which will be automatically826encoded in UTF-8.827- An optional third element can be used to specify the828[MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_Types)829of the file being uploaded. If not specified HTTPX will attempt to guess the MIME type based830on the file name, with unknown file extensions defaulting to "application/octet-stream".831If the file name is explicitly set to `None` then HTTPX will not include a content-type832MIME header field.833834```pycon835>>> files = {'upload-file': (None, 'text content', 'text/plain')}836>>> r = httpx.post("https://httpbin.org/post", files=files)837>>> print(r.text)838{839 ...840 "files": {},841 "form": {842 "upload-file": "text-content"843 },844 ...845}846```847848!!! tip849 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.850851 Non-file data fields can be included in the multipart form using by passing them to `data=...`.852853You can also send multiple files in one go with a multiple file field form.854To do that, pass a list of `(field, <file>)` items instead of a dictionary, allowing you to pass multiple items with the same `field`.855For instance this request sends 2 files, `foo.png` and `bar.png` in one request on the `images` form field:856857```pycon858>>> files = [('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),859 ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]860>>> r = httpx.post("https://httpbin.org/post", files=files)861```862863## Customizing authentication864865When 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...866867* A two-tuple of `username`/`password`, to be used with basic authentication.Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7
line 868why, one step back868* An instance of `httpx.BasicAuth()`, `httpx.DigestAuth()`, or `httpx.NetRCAuth()`.Test under 3.11-dev (#2302)Jobefore adoption8088fc7
lines 869–1296why, one step back869* A callable, accepting a request and returning an authenticated request instance.870* An instance of subclasses of `httpx.Auth`.871872The 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...873874```python875class MyCustomAuth(httpx.Auth):876 def __init__(self, token):877 self.token = token878879 def auth_flow(self, request):880 # Send the request, with a custom `X-Authentication` header.881 request.headers['X-Authentication'] = self.token882 yield request883```884885If the auth flow requires more than one request, you can issue multiple yields, and obtain the response in each case...886887```python888class MyCustomAuth(httpx.Auth):889 def __init__(self, token):890 self.token = token891892 def auth_flow(self, request):893 response = yield request894 if response.status_code == 401:895 # If the server issues a 401 response then resend the request,896 # with a custom `X-Authentication` header.897 request.headers['X-Authentication'] = self.token898 yield request899```900901Custom 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.902903You will then be able to access `request.content` inside the `.auth_flow()` method.904905```python906class MyCustomAuth(httpx.Auth):907 requires_request_body = True908909 def __init__(self, token):910 self.token = token911912 def auth_flow(self, request):913 response = yield request914 if response.status_code == 401:915 # If the server issues a 401 response then resend the request,916 # with a custom `X-Authentication` header.917 request.headers['X-Authentication'] = self.sign_request(...)918 yield request919920 def sign_request(self, request):921 # Create a request signature, based on `request.method`, `request.url`,922 # `request.headers`, and `request.content`.923 ...924```925926Similarly, 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.927928```python929class MyCustomAuth(httpx.Auth):930 requires_response_body = True931932 def __init__(self, access_token, refresh_token, refresh_url):933 self.access_token = access_token934 self.refresh_token = refresh_token935 self.refresh_url = refresh_url936937 def auth_flow(self, request):938 request.headers["X-Authentication"] = self.access_token939 response = yield request940941 if response.status_code == 401:942 # If the server issues a 401 response, then issue a request to943 # refresh tokens, and resend the request.944 refresh_response = yield self.build_refresh_request()945 self.update_tokens(refresh_response)946947 request.headers["X-Authentication"] = self.access_token948 yield request949950 def build_refresh_request(self):951 # Return an `httpx.Request` for refreshing tokens.952 ...953954 def update_tokens(self, response):955 # Update the `.access_token` and `.refresh_token` tokens956 # based on a refresh response.957 data = response.json()958 ...959```960961If 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`.962963```python964import asyncio965import threading966import httpx967968969class MyCustomAuth(httpx.Auth):970 def __init__(self):971 self._sync_lock = threading.RLock()972 self._async_lock = asyncio.Lock()973974 def sync_get_token(self):975 with self._sync_lock:976 ...977978 def sync_auth_flow(self, request):979 token = self.sync_get_token()980 request.headers["Authorization"] = f"Token {token}"981 yield request982983 async def async_get_token(self):984 async with self._async_lock:985 ...986987 async def async_auth_flow(self, request):988 token = await self.async_get_token()989 request.headers["Authorization"] = f"Token {token}"990 yield request991```992993If you only want to support one of the two methods, then you should still override it, but raise an explicit `RuntimeError`.994995```python996import httpx997import sync_only_library9989991000class MyCustomAuth(httpx.Auth):1001 def sync_auth_flow(self, request):1002 token = sync_only_library.get_token(...)1003 request.headers["Authorization"] = f"Token {token}"1004 yield request10051006 async def async_auth_flow(self, request):1007 raise RuntimeError("Cannot use a sync authentication class with httpx.AsyncClient")1008```10091010## SSL certificates10111012When 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).10131014### Changing the verification defaults10151016By 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.10171018If you'd like to use a custom CA bundle, you can use the `verify` parameter.10191020```python1021import httpx10221023r = httpx.get("https://example.org", verify="path/to/client.pem")1024```10251026Alternatively, you can pass a standard library `ssl.SSLContext`.10271028```pycon1029>>> import ssl1030>>> import httpx1031>>> context = ssl.create_default_context()1032>>> context.load_verify_locations(cafile="/tmp/client.pem")1033>>> httpx.get('https://example.org', verify=context)1034<Response [200 OK]>1035```10361037We also include a helper function for creating properly configured `SSLContext` instances.10381039```pycon1040>>> context = httpx.create_ssl_context()1041```10421043The `create_ssl_context` function accepts the same set of SSL configuration arguments1044(`trust_env`, `verify`, `cert` and `http2` arguments)1045as `httpx.Client` or `httpx.AsyncClient`10461047```pycon1048>>> import httpx1049>>> context = httpx.create_ssl_context(verify="/tmp/client.pem")1050>>> httpx.get('https://example.org', verify=context)1051<Response [200 OK]>1052```10531054Or you can also disable the SSL verification entirely, which is _not_ recommended.10551056```python1057import httpx10581059r = httpx.get("https://example.org", verify=False)1060```10611062### SSL configuration on client instances10631064If you're using a `Client()` instance, then you should pass any SSL settings when instantiating the client.10651066```python1067client = httpx.Client(verify=False)1068```10691070The `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.10711072### Client Side Certificates10731074You 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)10751076```python1077import httpx10781079r = httpx.get("https://example.org", cert="path/to/client.pem")1080```10811082Alternatively,10831084```pycon1085>>> cert = ("path/to/client.pem", "path/to/client.key")1086>>> httpx.get("https://example.org", cert=cert)1087<Response [200 OK]>1088```10891090or10911092```pycon1093>>> cert = ("path/to/client.pem", "path/to/client.key", "password")1094>>> httpx.get("https://example.org", cert=cert)1095<Response [200 OK]>1096```10971098### Making HTTPS requests to a local server10991100When making requests to local servers, such as a development server running on `localhost`, you will typically be using unencrypted HTTP connections.11011102If 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:110311041. Use [trustme](https://github.com/python-trio/trustme) to generate a pair of server key/cert files, and a client cert file.11051. 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.)11061. Tell HTTPX to use the certificates stored in `client.pem`:11071108```pycon1109>>> import httpx1110>>> r = httpx.get("https://localhost:8000", verify="/tmp/client.pem")1111>>> r1112Response <200 OK>1113```11141115## Custom Transports11161117HTTPX's `Client` also accepts a `transport` argument. This argument allows you1118to provide a custom Transport object that will be used to perform the actual1119sending of the requests.11201121### Usage11221123For some advanced configuration you might need to instantiate a transport1124class directly, and pass it to the client instance. One example is the1125`local_address` configuration which is only available via this low-level API.11261127```pycon1128>>> import httpx1129>>> transport = httpx.HTTPTransport(local_address="0.0.0.0")1130>>> client = httpx.Client(transport=transport)1131```11321133Connection retries are also available via this interface. Requests will be retried the given number of times in case an `httpx.ConnectError` or an `httpx.ConnectTimeout` occurs, allowing smoother operation under flaky networks. If you need other forms of retry behaviors, such as handling read/write errors or reacting to `503 Service Unavailable`, consider general-purpose tools such as [tenacity](https://github.com/jd/tenacity).11341135```pycon1136>>> import httpx1137>>> transport = httpx.HTTPTransport(retries=1)1138>>> client = httpx.Client(transport=transport)1139```11401141Similarly, instantiating a transport directly provides a `uds` option for1142connecting via a Unix Domain Socket that is only available via this low-level API:11431144```pycon1145>>> import httpx1146>>> # Connect to the Docker API via a Unix Socket.1147>>> transport = httpx.HTTPTransport(uds="/var/run/docker.sock")1148>>> client = httpx.Client(transport=transport)1149>>> response = client.get("http://docker/info")1150>>> response.json()1151{"ID": "...", "Containers": 4, "Images": 74, ...}1152```11531154### urllib3 transport11551156This [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`...11571158```pycon1159>>> import httpx1160>>> from urllib3_transport import URLLib3Transport1161>>> client = httpx.Client(transport=URLLib3Transport())1162>>> client.get("https://example.org")1163<Response [200 OK]>1164```11651166### Writing custom transports11671168A transport instance must implement the low-level Transport API, which deals1169with sending a single request, and returning a response. You should either1170subclass `httpx.BaseTransport` to implement a transport to use with `Client`,1171or subclass `httpx.AsyncBaseTransport` to implement a transport to1172use with `AsyncClient`.11731174At the layer of the transport API we're using the familiar `Request` and1175`Response` models.11761177See the `handle_request` and `handle_async_request` docstrings for more details1178on the specifics of the Transport API.11791180A complete example of a custom transport implementation would be:11811182```python1183import json1184import httpx118511861187class HelloWorldTransport(httpx.BaseTransport):1188 """1189 A mock transport that always returns a JSON "Hello, world!" response.1190 """11911192 def handle_request(self, request):1193 message = {"text": "Hello, world!"}1194 content = json.dumps(message).encode("utf-8")1195 stream = httpx.ByteStream(content)1196 headers = [(b"content-type", b"application/json")]1197 return httpx.Response(200, headers=headers, stream=stream)1198```11991200Which we can use in the same way:12011202```pycon1203>>> import httpx1204>>> client = httpx.Client(transport=HelloWorldTransport())1205>>> response = client.get("https://example.org/")1206>>> response.json()1207{"text": "Hello, world!"}1208```12091210### Mock transports12111212During testing it can often be useful to be able to mock out a transport,1213and return pre-determined responses, rather than making actual network requests.12141215The `httpx.MockTransport` class accepts a handler function, which can be used1216to map requests onto pre-determined responses:12171218```python1219def handler(request):1220 return httpx.Response(200, json={"text": "Hello, world!"})122112221223# Switch to a mock transport, if the TESTING environment variable is set.1224if os.environ.get('TESTING', '').upper() == "TRUE":1225 transport = httpx.MockTransport(handler)1226else:1227 transport = httpx.HTTPTransport()12281229client = httpx.Client(transport=transport)1230```12311232For more advanced use-cases you might want to take a look at either [the third-party1233mocking library, RESPX](https://lundberg.github.io/respx/), or the [pytest-httpx library](https://github.com/Colin-b/pytest_httpx).12341235### Mounting transports12361237You can also mount transports against given schemes or domains, to control1238which transport an outgoing request should be routed via, with [the same style1239used for specifying proxy routing](#routing).12401241```python1242import httpx12431244class HTTPSRedirectTransport(httpx.BaseTransport):1245 """1246 A transport that always redirects to HTTPS.1247 """12481249 def handle_request(self, method, url, headers, stream, extensions):1250 scheme, host, port, path = url1251 if port is None:1252 location = b"https://%s%s" % (host, path)1253 else:1254 location = b"https://%s:%d%s" % (host, port, path)1255 stream = httpx.ByteStream(b"")1256 headers = [(b"location", location)]1257 extensions = {}1258 return 303, headers, stream, extensions125912601261# A client where any `http` requests are always redirected to `https`1262mounts = {'http://': HTTPSRedirectTransport()}1263client = httpx.Client(mounts=mounts)1264```12651266A couple of other sketches of how you might take advantage of mounted transports...12671268Disabling HTTP/2 on a single given domain...12691270```python1271mounts = {1272 "all://": httpx.HTTPTransport(http2=True),1273 "all://*example.org": httpx.HTTPTransport()1274}1275client = httpx.Client(mounts=mounts)1276```12771278Mocking requests to a given domain:12791280```python1281# All requests to "example.org" should be mocked out.1282# Other requests occur as usual.1283def handler(request):1284 return httpx.Response(200, json={"text": "Hello, World!"})12851286mounts = {"all://example.org": httpx.MockTransport(handler)}1287client = httpx.Client(mounts=mounts)1288```12891290Adding support for custom schemes:12911292```python1293# Support URLs like "file:///Users/sylvia_green/websites/new_client/index.html"1294mounts = {"file://": FileSystemTransport()}1295client = httpx.Client(mounts=mounts)1296```