Skip to content
Myr

Docs restructuring. (#3049)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Tweak docs layout * Move client docs into folder * Add clients/authentication section * Client authentication docs * Fix authentication example * SSL Context * Timeouts * Event hooks * Proxies, Transports * Text encodings * Resource limits * 'Clients' -> 'Advanced' * 'Clients' -> 'Advanced' * Add client docs ---------

authored by Tom Christie · committed by GitHub · parent ab720d3 · Browse files · 11 files+1318 added−1301 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Kar Petrosyan <92274156+karpetrosyan@users.noreply.github.com>

Diff stats

11 files+1318 added−1301 removed

  • other:+1318 added−1301 removed

11 files+1318 added−1301 removed

added:docs/advanced/authentication.md+232 added
1Authentication can either be included on a per-request basis...23```pycon4>>> auth = httpx.BasicAuthentication(username="username", password="secret")5>>> client = httpx.Client()6>>> response = client.get("https://www.example.com/", auth=auth)7```89Or configured on the client instance, ensuring that all outgoing requests will include authentication credentials...1011```pycon12>>> auth = httpx.BasicAuthentication(username="username", password="secret")13>>> client = httpx.Client(auth=auth)14>>> response = client.get("https://www.example.com/")15```1617## Basic authentication1819HTTP basic authentication is an unencrypted authentication scheme that uses a simple encoding of the username and password in the request `Authorization` header. Since it is unencrypted it should typically only be used over `https`, although this is not strictly enforced.2021```pycon22>>> auth = httpx.BasicAuthentication(username="finley", password="secret")23>>> client = httpx.Client(auth=auth)24>>> response = client.get("https://httpbin.org/basic-auth/finley/secret")25>>> response26<Response [200 OK]>27```2829## Digest authentication3031HTTP digest authentication is a challenge-response authentication scheme. Unlike basic authentication it provides encryption, and can be used over unencrypted `http` connections. It requires an additional round-trip in order to negotiate the authentication. 3233```pycon34>>> auth = httpx.DigestAuth(username="olivia", password="secret")35>>> client = httpx.Client(auth=auth)36>>> response = client.get("https://httpbin.org/digest-auth/auth/olivia/secret")37>>> response38<Response [200 OK]>39>>> response.history40[<Response [401 UNAUTHORIZED]>]41```4243## NetRC authentication4445HTTPX can be configured to use [a `.netrc` config file](https://everything.curl.dev/usingcurl/netrc) for authentication.4647The `.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 authentication.4849Example `.netrc` file:5051```52machine example.org53login example-username54password example-password5556machine python-httpx.org57login other-username58password other-password59```6061Some examples of configuring `.netrc` authentication with `httpx`.6263Use the default `.netrc` file in the users home directory:6465```pycon66>>> auth = httpx.NetRCAuth()67>>> client = httpx.Client(auth=auth)68```6970Use an explicit path to a `.netrc` file:7172```pycon73>>> auth = httpx.NetRCAuth(file="/path/to/.netrc")74>>> client = httpx.Client(auth=auth)75```7677Use the `NETRC` environment variable to configure a path to the `.netrc` file,78or fallback to the default.7980```pycon81>>> auth = httpx.NetRCAuth(file=os.environ.get("NETRC"))82>>> client = httpx.Client(auth=auth)83```8485The `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.8687## Custom authentication schemes8889When 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...9091* A two-tuple of `username`/`password`, to be used with basic authentication.92* An instance of `httpx.BasicAuth()`, `httpx.DigestAuth()`, or `httpx.NetRCAuth()`.93* A callable, accepting a request and returning an authenticated request instance.94* An instance of subclasses of `httpx.Auth`.9596The 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...9798```python99class MyCustomAuth(httpx.Auth):100 def __init__(self, token):101 self.token = token102103 def auth_flow(self, request):104 # Send the request, with a custom `X-Authentication` header.105 request.headers['X-Authentication'] = self.token106 yield request107```108109If the auth flow requires more than one request, you can issue multiple yields, and obtain the response in each case...110111```python112class MyCustomAuth(httpx.Auth):113 def __init__(self, token):114 self.token = token115116 def auth_flow(self, request):117 response = yield request118 if response.status_code == 401:119 # If the server issues a 401 response then resend the request,120 # with a custom `X-Authentication` header.121 request.headers['X-Authentication'] = self.token122 yield request123```124125Custom 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.126127You will then be able to access `request.content` inside the `.auth_flow()` method.128129```python130class MyCustomAuth(httpx.Auth):131 requires_request_body = True132133 def __init__(self, token):134 self.token = token135136 def auth_flow(self, request):137 response = yield request138 if response.status_code == 401:139 # If the server issues a 401 response then resend the request,140 # with a custom `X-Authentication` header.141 request.headers['X-Authentication'] = self.sign_request(...)142 yield request143144 def sign_request(self, request):145 # Create a request signature, based on `request.method`, `request.url`,146 # `request.headers`, and `request.content`.147 ...148```149150Similarly, 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.151152```python153class MyCustomAuth(httpx.Auth):154 requires_response_body = True155156 def __init__(self, access_token, refresh_token, refresh_url):157 self.access_token = access_token158 self.refresh_token = refresh_token159 self.refresh_url = refresh_url160161 def auth_flow(self, request):162 request.headers["X-Authentication"] = self.access_token163 response = yield request164165 if response.status_code == 401:166 # If the server issues a 401 response, then issue a request to167 # refresh tokens, and resend the request.168 refresh_response = yield self.build_refresh_request()169 self.update_tokens(refresh_response)170171 request.headers["X-Authentication"] = self.access_token172 yield request173174 def build_refresh_request(self):175 # Return an `httpx.Request` for refreshing tokens.176 ...177178 def update_tokens(self, response):179 # Update the `.access_token` and `.refresh_token` tokens180 # based on a refresh response.181 data = response.json()182 ...183```184185If 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`.186187```python188import asyncio189import threading190import httpx191192193class MyCustomAuth(httpx.Auth):194 def __init__(self):195 self._sync_lock = threading.RLock()196 self._async_lock = asyncio.Lock()197198 def sync_get_token(self):199 with self._sync_lock:200 ...201202 def sync_auth_flow(self, request):203 token = self.sync_get_token()204 request.headers["Authorization"] = f"Token {token}"205 yield request206207 async def async_get_token(self):208 async with self._async_lock:209 ...210211 async def async_auth_flow(self, request):212 token = await self.async_get_token()213 request.headers["Authorization"] = f"Token {token}"214 yield request215```216217If you only want to support one of the two methods, then you should still override it, but raise an explicit `RuntimeError`.218219```python220import httpx221import sync_only_library222223224class MyCustomAuth(httpx.Auth):225 def sync_auth_flow(self, request):226 token = sync_only_library.get_token(...)227 request.headers["Authorization"] = f"Token {token}"228 yield request229230 async def async_auth_flow(self, request):231 raise RuntimeError("Cannot use a sync authentication class with httpx.AsyncClient")232```
added:docs/advanced/clients.md+324 added
1!!! hint2 If you are coming from Requests, `httpx.Client()` is what you can use instead of `requests.Session()`.34## Why use a Client?56!!! note "TL;DR"7 If you do anything more than experimentation, one-off scripts, or prototypes, then you should use a `Client` instance.89**More efficient usage of network resources**1011When 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.1213On 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.1415This can bring **significant performance improvements** compared to using the top-level API, including:1617- Reduced latency across requests (no handshaking).18- Reduced CPU usage and round-trips.19- Reduced network congestion.2021**Extra features**2223`Client` instances also support features that aren't available at the top-level API, such as:2425- Cookie persistence across requests.26- Applying configuration across all outgoing requests.27- Sending requests through HTTP proxies.28- Using [HTTP/2](http2.md).2930The other sections on this page go into further detail about what you can do with a `Client` instance.3132## Usage3334The 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:3536```python37with httpx.Client() as client:38 ...39```4041Alternatively, you can explicitly close the connection pool without block-usage using `.close()`:4243```python44client = httpx.Client()45try:46 ...47finally:48 client.close()49```5051## Making requests5253Once you have a `Client`, you can send requests using `.get()`, `.post()`, etc. For example:5455```pycon56>>> with httpx.Client() as client:57... r = client.get('https://example.com')58...59>>> r60<Response [200 OK]>61```6263These 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.6465For example, to send a request with custom headers:6667```pycon68>>> with httpx.Client() as client:69... headers = {'X-Custom': 'value'}70... r = client.get('https://example.com', headers=headers)71...72>>> r.request.headers['X-Custom']73'value'74```7576## Sharing configuration across requests7778Clients allow you to apply configuration to all outgoing requests by passing parameters to the `Client` constructor.7980For example, to apply a set of custom headers _on every request_:8182```pycon83>>> url = 'http://httpbin.org/headers'84>>> headers = {'user-agent': 'my-app/0.0.1'}85>>> with httpx.Client(headers=headers) as client:86... r = client.get(url)87...88>>> r.json()['headers']['User-Agent']89'my-app/0.0.1'90```9192## Merging of configuration9394When a configuration option is provided at both the client-level and request-level, one of two things can happen:9596- For headers, query parameters and cookies, the values are combined together. For example:9798```pycon99>>> headers = {'X-Auth': 'from-client'}100>>> params = {'client_id': 'client1'}101>>> with httpx.Client(headers=headers, params=params) as client:102... headers = {'X-Custom': 'from-request'}103... params = {'request_id': 'request1'}104... r = client.get('https://example.com', headers=headers, params=params)105...106>>> r.request.url107URL('https://example.com?client_id=client1&request_id=request1')108>>> r.request.headers['X-Auth']109'from-client'110>>> r.request.headers['X-Custom']111'from-request'112```113114- For all other parameters, the request-level value takes priority. For example:115116```pycon117>>> with httpx.Client(auth=('tom', 'mot123')) as client:118... r = client.get('https://example.com', auth=('alice', 'ecila123'))119...120>>> _, _, auth = r.request.headers['Authorization'].partition(' ')121>>> import base64122>>> base64.b64decode(auth)123b'alice:ecila123'124```125126If you need finer-grained control on the merging of client-level and request-level parameters, see [Request instances](#request-instances).127128## Other Client-only configuration options129130Additionally, `Client` accepts some configuration options that aren't available at the request level.131132For example, `base_url` allows you to prepend an URL to all outgoing requests:133134```pycon135>>> with httpx.Client(base_url='http://httpbin.org') as client:136... r = client.get('/headers')137...138>>> r.request.url139URL('http://httpbin.org/headers')140```141142For a list of all available client parameters, see the [`Client`](api.md#client) API reference.143144---145146## Request instances147148For maximum control on what gets sent over the wire, HTTPX supports building explicit [`Request`](api.md#request) instances:149150```python151request = httpx.Request("GET", "https://example.com")152```153154To dispatch a `Request` instance across to the network, create a [`Client` instance](#client-instances) and use `.send()`:155156```python157with httpx.Client() as client:158 response = client.send(request)159 ...160```161162If 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:163164```python165headers = {"X-Api-Key": "...", "X-Client-ID": "ABC123"}166167with httpx.Client(headers=headers) as client:168 request = client.build_request("GET", "https://api.example.com")169170 print(request.headers["X-Client-ID"]) # "ABC123"171172 # Don't send the API key for this particular request.173 del request.headers["X-Api-Key"]174175 response = client.send(request)176 ...177```178179## Monitoring download progress180181If you need to monitor download progress of large responses, you can use response streaming and inspect the `response.num_bytes_downloaded` property.182183This 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.184185For 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…186187```python188import tempfile189190import httpx191from tqdm import tqdm192193with tempfile.NamedTemporaryFile() as download_file:194 url = "https://speed.hetzner.de/100MB.bin"195 with httpx.stream("GET", url) as response:196 total = int(response.headers["Content-Length"])197198 with tqdm(total=total, unit_scale=True, unit_divisor=1024, unit="B") as progress:199 num_bytes_downloaded = response.num_bytes_downloaded200 for chunk in response.iter_bytes():201 download_file.write(chunk)202 progress.update(response.num_bytes_downloaded - num_bytes_downloaded)203 num_bytes_downloaded = response.num_bytes_downloaded204```205206![tqdm progress bar](img/tqdm-progress.gif)207208Or an alternate example, this time using the [`rich`](https://github.com/willmcgugan/rich) library…209210```python211import tempfile212import httpx213import rich.progress214215with tempfile.NamedTemporaryFile() as download_file:216 url = "https://speed.hetzner.de/100MB.bin"217 with httpx.stream("GET", url) as response:218 total = int(response.headers["Content-Length"])219220 with rich.progress.Progress(221 "[progress.percentage]{task.percentage:>3.0f}%",222 rich.progress.BarColumn(bar_width=None),223 rich.progress.DownloadColumn(),224 rich.progress.TransferSpeedColumn(),225 ) as progress:226 download_task = progress.add_task("Download", total=total)227 for chunk in response.iter_bytes():228 download_file.write(chunk)229 progress.update(download_task, completed=response.num_bytes_downloaded)230```231232![rich progress bar](../img/rich-progress.gif)233234## Monitoring upload progress235236If you need to monitor upload progress of large responses, you can use request content generator streaming.237238For example, showing a progress bar using the [`tqdm`](https://github.com/tqdm/tqdm) library.239240```python241import io242import random243244import httpx245from tqdm import tqdm246247248def gen():249 """250 this is a complete example with generated random bytes.251 you can replace `io.BytesIO` with real file object.252 """253 total = 32 * 1024 * 1024 # 32m254 with tqdm(ascii=True, unit_scale=True, unit='B', unit_divisor=1024, total=total) as bar:255 with io.BytesIO(random.randbytes(total)) as f:256 while data := f.read(1024):257 yield data258 bar.update(len(data))259260261httpx.post("https://httpbin.org/post", content=gen())262```263264![tqdm progress bar](../img/tqdm-progress.gif)265266## Multipart file encoding267268As mentioned in the [quickstart](quickstart.md#sending-multipart-file-uploads)269multipart file encoding is available by passing a dictionary with the270name of the payloads as keys and either tuple of elements or a file-like object or a string as values.271272```pycon273>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}274>>> r = httpx.post("https://httpbin.org/post", files=files)275>>> print(r.text)276{277 ...278 "files": {279 "upload-file": "<... binary content ...>"280 },281 ...282}283```284285More specifically, if a tuple is used as a value, it must have between 2 and 3 elements:286287- The first element is an optional file name which can be set to `None`.288- The second element may be a file-like object or a string which will be automatically289encoded in UTF-8.290- An optional third element can be used to specify the291[MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_Types)292of the file being uploaded. If not specified HTTPX will attempt to guess the MIME type based293on the file name, with unknown file extensions defaulting to "application/octet-stream".294If the file name is explicitly set to `None` then HTTPX will not include a content-type295MIME header field.296297```pycon298>>> files = {'upload-file': (None, 'text content', 'text/plain')}299>>> r = httpx.post("https://httpbin.org/post", files=files)300>>> print(r.text)301{302 ...303 "files": {},304 "form": {305 "upload-file": "text-content"306 },307 ...308}309```310311!!! tip312 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.313314 Non-file data fields can be included in the multipart form using by passing them to `data=...`.315316You can also send multiple files in one go with a multiple file field form.317To do that, pass a list of `(field, <file>)` items instead of a dictionary, allowing you to pass multiple items with the same `field`.318For instance this request sends 2 files, `foo.png` and `bar.png` in one request on the `images` form field:319320```pycon321>>> files = [('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),322 ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]323>>> r = httpx.post("https://httpbin.org/post", files=files)324```
added:docs/advanced/event-hooks.md+65 added
added:docs/advanced/proxies.md+83 added
1HTTPX supports setting up [HTTP proxies](https://en.wikipedia.org/wiki/Proxy_server#Web_proxy_servers) via the `proxy` parameter to be passed on client initialization or top-level API functions like `httpx.get(..., proxy=...)`.23<div align="center">4 <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/27/Open_proxy_h2g2bob.svg/480px-Open_proxy_h2g2bob.svg.png"/>5 <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>6</div>78## HTTP Proxies910To route all traffic (HTTP and HTTPS) to a proxy located at `http://localhost:8030`, pass the proxy URL to the client...1112```python13with httpx.Client(proxy="http://localhost:8030") as client:14 ...15```1617For more advanced use cases, pass a mounts `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:1819```python20proxy_mounts = {21 "http://": httpx.HTTPTransport(proxy="http://localhost:8030"),22 "https://": httpx.HTTPTransport(proxy="http://localhost:8031"),23}2425with httpx.Client(mounts=proxy_mounts) as client:26 ...27```2829For detailed information about proxy routing, see the [Routing](#routing) section.3031!!! tip "Gotcha"32 In most cases, the proxy URL for the `https://` key _should_ use the `http://` scheme (that's not a typo!).3334 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.3536 For more information, see [FORWARD vs TUNNEL](#forward-vs-tunnel).3738## Authentication3940Proxy credentials can be passed as the `userinfo` section of the proxy URL. For example:4142```python43with httpx.Client(proxy="http://username:password@localhost:8030") as client:44 ...45```4647## Proxy mechanisms4849!!! note50 This section describes **advanced** proxy concepts and functionality.5152### FORWARD vs TUNNEL5354In general, the flow for making an HTTP request through a proxy is as follows:55561. The client connects to the proxy (initial connection request).572. The proxy transfers data to the server on your behalf.5859How exactly step 2/ is performed depends on which of two proxying mechanisms is used:6061* **Forwarding**: the proxy makes the request for you, and sends back the response it obtained from the server.62* **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).6364### Troubleshooting proxies6566If you encounter issues when setting up proxies, please refer to our [Troubleshooting guide](troubleshooting.md#proxies).6768## SOCKS6970In addition to HTTP proxies, `httpcore` also supports proxies using the SOCKS protocol.71This is an optional feature that requires an additional third-party library be installed before use.7273You can install SOCKS support using `pip`:7475```shell76$ pip install httpx[socks]77```7879You can now configure a client to make requests via a proxy using the SOCKS protocol:8081```python82httpx.Client(proxy='socks5://user:pass@host:port')83```
added:docs/advanced/resource-limits.md+13 added
added:docs/advanced/ssl.md+100 added
1When 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).23## Changing the verification defaults45By 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.67If you'd like to use a custom CA bundle, you can use the `verify` parameter.89```python10import httpx1112r = httpx.get("https://example.org", verify="path/to/client.pem")13```1415Alternatively, you can pass a standard library `ssl.SSLContext`.1617```pycon18>>> import ssl19>>> import httpx20>>> context = ssl.create_default_context()21>>> context.load_verify_locations(cafile="/tmp/client.pem")22>>> httpx.get('https://example.org', verify=context)23<Response [200 OK]>24```2526We also include a helper function for creating properly configured `SSLContext` instances.2728```pycon29>>> context = httpx.create_ssl_context()30```3132The `create_ssl_context` function accepts the same set of SSL configuration arguments33(`trust_env`, `verify`, `cert` and `http2` arguments)34as `httpx.Client` or `httpx.AsyncClient`3536```pycon37>>> import httpx38>>> context = httpx.create_ssl_context(verify="/tmp/client.pem")39>>> httpx.get('https://example.org', verify=context)40<Response [200 OK]>41```4243Or you can also disable the SSL verification entirely, which is _not_ recommended.4445```python46import httpx4748r = httpx.get("https://example.org", verify=False)49```5051## SSL configuration on client instances5253If you're using a `Client()` instance, then you should pass any SSL settings when instantiating the client.5455```python56client = httpx.Client(verify=False)57```5859The `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.6061## Client Side Certificates6263You 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)6465```python66cert = "path/to/client.pem"67client = httpx.Client(cert=cert)68response = client.get("https://example.org")69```7071Alternatively...7273```python74cert = ("path/to/client.pem", "path/to/client.key")75client = httpx.Client(cert=cert)76response = client.get("https://example.org")77```7879Or...8081```python82cert = ("path/to/client.pem", "path/to/client.key", "password")83client = httpx.Client(cert=cert)84response = client.get("https://example.org")85```8687## Making HTTPS requests to a local server8889When making requests to local servers, such as a development server running on `localhost`, you will typically be using unencrypted HTTP connections.9091If 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:92931. Use [trustme](https://github.com/python-trio/trustme) to generate a pair of server key/cert files, and a client cert file.941. 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.)951. Tell HTTPX to use the certificates stored in `client.pem`:9697```python98client = httpx.Client(verify="/tmp/client.pem")99response = client.get("https://localhost:8000")100```
added:docs/advanced/text-encodings.md+75 added
added:docs/advanced/timeouts.md+71 added
added:docs/advanced/transports.md+344 added
1HTTPX's `Client` also accepts a `transport` argument. This argument allows you2to provide a custom Transport object that will be used to perform the actual3sending of the requests.45## HTTPTransport67For some advanced configuration you might need to instantiate a transport8class directly, and pass it to the client instance. One example is the9`local_address` configuration which is only available via this low-level API.1011```pycon12>>> import httpx13>>> transport = httpx.HTTPTransport(local_address="0.0.0.0")14>>> client = httpx.Client(transport=transport)15```1617Connection 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).1819```pycon20>>> import httpx21>>> transport = httpx.HTTPTransport(retries=1)22>>> client = httpx.Client(transport=transport)23```2425Similarly, instantiating a transport directly provides a `uds` option for26connecting via a Unix Domain Socket that is only available via this low-level API:2728```pycon29>>> import httpx30>>> # Connect to the Docker API via a Unix Socket.31>>> transport = httpx.HTTPTransport(uds="/var/run/docker.sock")32>>> client = httpx.Client(transport=transport)33>>> response = client.get("http://docker/info")34>>> response.json()35{"ID": "...", "Containers": 4, "Images": 74, ...}36```3738## WSGI Transport3940You can configure an `httpx` client to call directly into a Python web application using the WSGI protocol.4142This is particularly useful for two main use-cases:4344* Using `httpx` as a client inside test cases.45* Mocking out external services during tests or in dev/staging environments.4647Here's an example of integrating against a Flask application:4849```python50from flask import Flask51import httpx525354app = Flask(__name__)5556@app.route("/")57def hello():58 return "Hello World!"5960with httpx.Client(app=app, base_url="http://testserver") as client:61 r = client.get("/")62 assert r.status_code == 20063 assert r.text == "Hello World!"64```6566For some more complex cases you might need to customize the WSGI transport. This allows you to:6768* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.69* Mount the WSGI application at a subpath by setting `script_name` (WSGI).70* Use a given client address for requests by setting `remote_addr` (WSGI).7172For example:7374```python75# Instantiate a client that makes WSGI requests with a client IP of "1.2.3.4".76transport = httpx.WSGITransport(app=app, remote_addr="1.2.3.4")77with httpx.Client(transport=transport, base_url="http://testserver") as client:78 ...79```8081## urllib3 transport8283This [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`...8485```pycon86>>> import httpx87>>> from urllib3_transport import URLLib3Transport88>>> client = httpx.Client(transport=URLLib3Transport())89>>> client.get("https://example.org")90<Response [200 OK]>91```9293## Custom transports9495A transport instance must implement the low-level Transport API, which deals96with sending a single request, and returning a response. You should either97subclass `httpx.BaseTransport` to implement a transport to use with `Client`,98or subclass `httpx.AsyncBaseTransport` to implement a transport to99use with `AsyncClient`.100101At the layer of the transport API we're using the familiar `Request` and102`Response` models.103104See the `handle_request` and `handle_async_request` docstrings for more details105on the specifics of the Transport API.106107A complete example of a custom transport implementation would be:108109```python110import json111import httpx112113114class HelloWorldTransport(httpx.BaseTransport):115 """116 A mock transport that always returns a JSON "Hello, world!" response.117 """118119 def handle_request(self, request):120 message = {"text": "Hello, world!"}121 content = json.dumps(message).encode("utf-8")122 stream = httpx.ByteStream(content)123 headers = [(b"content-type", b"application/json")]124 return httpx.Response(200, headers=headers, stream=stream)125```126127Which we can use in the same way:128129```pycon130>>> import httpx131>>> client = httpx.Client(transport=HelloWorldTransport())132>>> response = client.get("https://example.org/")133>>> response.json()134{"text": "Hello, world!"}135```136137## Mock transports138139During testing it can often be useful to be able to mock out a transport,140and return pre-determined responses, rather than making actual network requests.141142The `httpx.MockTransport` class accepts a handler function, which can be used143to map requests onto pre-determined responses:144145```python146def handler(request):147 return httpx.Response(200, json={"text": "Hello, world!"})148149150# Switch to a mock transport, if the TESTING environment variable is set.151if os.environ.get('TESTING', '').upper() == "TRUE":152 transport = httpx.MockTransport(handler)153else:154 transport = httpx.HTTPTransport()155156client = httpx.Client(transport=transport)157```158159For more advanced use-cases you might want to take a look at either [the third-party160mocking library, RESPX](https://lundberg.github.io/respx/), or the [pytest-httpx library](https://github.com/Colin-b/pytest_httpx).161162## Mounting transports163164You can also mount transports against given schemes or domains, to control165which transport an outgoing request should be routed via, with [the same style166used for specifying proxy routing](#routing).167168```python169import httpx170171class HTTPSRedirectTransport(httpx.BaseTransport):172 """173 A transport that always redirects to HTTPS.174 """175176 def handle_request(self, method, url, headers, stream, extensions):177 scheme, host, port, path = url178 if port is None:179 location = b"https://%s%s" % (host, path)180 else:181 location = b"https://%s:%d%s" % (host, port, path)182 stream = httpx.ByteStream(b"")183 headers = [(b"location", location)]184 extensions = {}185 return 303, headers, stream, extensions186187188# A client where any `http` requests are always redirected to `https`189mounts = {'http://': HTTPSRedirectTransport()}190client = httpx.Client(mounts=mounts)191```192193A couple of other sketches of how you might take advantage of mounted transports...194195Disabling HTTP/2 on a single given domain...196197```python198mounts = {199 "all://": httpx.HTTPTransport(http2=True),200 "all://*example.org": httpx.HTTPTransport()201}202client = httpx.Client(mounts=mounts)203```204205Mocking requests to a given domain:206207```python208# All requests to "example.org" should be mocked out.209# Other requests occur as usual.210def handler(request):211 return httpx.Response(200, json={"text": "Hello, World!"})212213mounts = {"all://example.org": httpx.MockTransport(handler)}214client = httpx.Client(mounts=mounts)215```216217Adding support for custom schemes:218219```python220# Support URLs like "file:///Users/sylvia_green/websites/new_client/index.html"221mounts = {"file://": FileSystemTransport()}222client = httpx.Client(mounts=mounts)223```224225### Routing226227HTTPX provides a powerful mechanism for routing requests, allowing you to write complex rules that specify which transport should be used for each request.228229The `mounts` dictionary maps URL patterns to HTTP transports. HTTPX matches requested URLs against URL patterns to decide which transport should be used, if any. Matching is done from most specific URL patterns (e.g. `https://<domain>:<port>`) to least specific ones (e.g. `https://`).230231HTTPX supports routing requests based on **scheme**, **domain**, **port**, or a combination of these.232233### Wildcard routing234235Route everything through a transport...236237```python238mounts = {239 "all://": httpx.HTTPTransport(proxy="http://localhost:8030"),240}241```242243### Scheme routing244245Route HTTP requests through one transport, and HTTPS requests through another...246247```python248mounts = {249 "http://": httpx.HTTPTransport(proxy="http://localhost:8030"),250 "https://": httpx.HTTPTransport(proxy="http://localhost:8031"),251}252```253254### Domain routing255256Proxy all requests on domain "example.com", let other requests pass through...257258```python259mounts = {260 "all://example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),261}262```263264Proxy HTTP requests on domain "example.com", let HTTPS and other requests pass through...265266```python267mounts = {268 "http://example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),269}270```271272Proxy all requests to "example.com" and its subdomains, let other requests pass through...273274```python275mounts = {276 "all://*example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),277}278```279280Proxy all requests to strict subdomains of "example.com", let "example.com" and other requests pass through...281282```python283mounts = {284 "all://*.example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),285}286```287288### Port routing289290Proxy HTTPS requests on port 1234 to "example.com"...291292```python293mounts = {294 "https://example.com:1234": httpx.HTTPTransport(proxy="http://localhost:8030"),295}296```297298Proxy all requests on port 1234...299300```python301mounts = {302 "all://*:1234": httpx.HTTPTransport(proxy="http://localhost:8030"),303}304```305306### No-proxy support307308It is also possible to define requests that _shouldn't_ be routed through the transport.309310To do so, pass `None` as the proxy URL. For example...311312```python313mounts = {314 # Route requests through a proxy by default...315 "all://": httpx.HTTPTransport(proxy="http://localhost:8031"),316 # Except those for "example.com".317 "all://example.com": None,318}319```320321### Complex configuration example322323You can combine the routing features outlined above to build complex proxy routing configurations. For example...324325```python326mounts = {327 # Route all traffic through a proxy by default...328 "all://": httpx.HTTPTransport(proxy="http://localhost:8030"),329 # But don't use proxies for HTTPS requests to "domain.io"...330 "https://domain.io": None,331 # And use another proxy for requests to "example.com" and its subdomains...332 "all://*example.com": httpx.HTTPTransport(proxy="http://localhost:8031"),333 # And yet another proxy if HTTP is used,334 # and the "internal" subdomain on port 5550 is requested...335 "http://internal.example.com:5550": httpx.HTTPTransport(proxy="http://localhost:8032"),336}337```338339### Environment variables340341There are also environment variables that can be used to control the dictionary of the client mounts. 342They can be used to configure HTTP proxying for clients.343344See documentation on [`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`](environment_variables.md#http_proxy-https_proxy-all_proxy) for more information.
deleted:docs/advanced.md-1296 removed
1# 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```400401![tqdm progress bar](img/tqdm-progress.gif)402403Or 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```426427![rich progress bar](img/rich-progress.gif)428429## 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```458459![tqdm progress bar](img/tqdm-progress.gif)460461## .netrc Support462463HTTPX can be configured to use [a `.netrc` config file](https://everything.curl.dev/usingcurl/netrc) for authentication.464465The `.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.466467Example `.netrc` file:468469```470machine example.org471login example-username472password example-password473474machine python-httpx.org475login other-username476password other-password477```478479Some examples of configuring `.netrc` authentication with `httpx`.480481Use the default `.netrc` file in the users home directory:482483```pycon484>>> auth = httpx.NetRCAuth()485>>> client = httpx.Client(auth=auth)486```487488Use an explicit path to a `.netrc` file:489490```pycon491>>> auth = httpx.NetRCAuth(file="/path/to/.netrc")492>>> client = httpx.Client(auth=auth)493```494495Use the `NETRC` environment variable to configure a path to the `.netrc` file,496or fallback to the default.497498```pycon499>>> auth = httpx.NetRCAuth(file=os.environ.get("NETRC"))500>>> client = httpx.Client(auth=auth)501```502503The `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.504505## HTTP Proxying506507HTTPX supports setting up [HTTP proxies](https://en.wikipedia.org/wiki/Proxy_server#Web_proxy_servers) via the `proxy` parameter to be passed on client initialization or top-level API functions like `httpx.get(..., proxy=...)`.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(proxy="http://localhost:8030") as client:520 ...521```522523For more advanced use cases, pass a mounts `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```python526proxy_mounts = {527 "http://": httpx.HTTPTransport(proxy="http://localhost:8030"),528 "https://": httpx.HTTPTransport(proxy="http://localhost:8031"),529}530531with httpx.Client(mounts=proxy_mounts) 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```python549with httpx.Client(proxy="http://username:password@localhost:8030") as client:550 ...551```552553### Proxy mechanisms554555!!! note556 This section describes **advanced** proxy concepts and functionality.557558#### FORWARD vs TUNNEL559560In general, the flow for making an HTTP request through a proxy is as follows:5615621. The client connects to the proxy (initial connection request).5632. The proxy transfers data to the server on your behalf.564565How exactly step 2/ is performed depends on which of two proxying mechanisms is used:566567* **Forwarding**: the proxy makes the request for you, and sends back the response it obtained from the server.568* **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).569570### Troubleshooting proxies571572If you encounter issues when setting up proxies, please refer to our [Troubleshooting guide](troubleshooting.md#proxies).573574## SOCKS575576In addition to HTTP proxies, `httpcore` also supports proxies using the SOCKS protocol.577This is an optional feature that requires an additional third-party library be installed before use.578579You can install SOCKS support using `pip`:580581```shell582$ pip install httpx[socks]583```584585You can now configure a client to make requests via a proxy using the SOCKS protocol:586587```python588httpx.Client(proxy='socks5://user:pass@host:port')589```590591## Timeout Configuration592593HTTPX is careful to enforce timeouts everywhere by default.594595The default behavior is to raise a `TimeoutException` after 5 seconds of596network inactivity.597598### Setting and disabling timeouts599600You can set timeouts for an individual request:601602```python603# Using the top-level API:604httpx.get('http://example.com/api/v1/example', timeout=10.0)605606# Using a client instance:607with httpx.Client() as client:608 client.get("http://example.com/api/v1/example", timeout=10.0)609```610611Or disable timeouts for an individual request:612613```python614# Using the top-level API:615httpx.get('http://example.com/api/v1/example', timeout=None)616617# Using a client instance:618with httpx.Client() as client:619 client.get("http://example.com/api/v1/example", timeout=None)620```621622### Setting a default timeout on a client623624You can set a timeout on a client instance, which results in the given625`timeout` being used as the default for requests made with this client:626627```python628client = httpx.Client() # Use a default 5s timeout everywhere.629client = httpx.Client(timeout=10.0) # Use a default 10s timeout everywhere.630client = httpx.Client(timeout=None) # Disable all timeouts by default.631```632633### Fine tuning the configuration634635HTTPX also allows you to specify the timeout behavior in more fine grained detail.636637There are four different types of timeouts that may occur. These are **connect**,638**read**, **write**, and **pool** timeouts.639640* The **connect** timeout specifies the maximum amount of time to wait until641a socket connection to the requested host is established. If HTTPX is unable to connect642within this time frame, a `ConnectTimeout` exception is raised.643* The **read** timeout specifies the maximum duration to wait for a chunk of644data to be received (for example, a chunk of the response body). If HTTPX is645unable to receive data within this time frame, a `ReadTimeout` exception is raised.646* The **write** timeout specifies the maximum duration to wait for a chunk of647data to be sent (for example, a chunk of the request body). If HTTPX is unable648to send data within this time frame, a `WriteTimeout` exception is raised.649* The **pool** timeout specifies the maximum duration to wait for acquiring650a connection from the connection pool. If HTTPX is unable to acquire a connection651within this time frame, a `PoolTimeout` exception is raised. A related652configuration here is the maximum number of allowable connections in the653connection pool, which is configured by the `limits` argument.654655You can configure the timeout behavior for any of these values...656657```python658# A client with a 60s timeout for connecting, and a 10s timeout elsewhere.659timeout = httpx.Timeout(10.0, connect=60.0)660client = httpx.Client(timeout=timeout)661662response = client.get('http://example.com/')663```664665## Pool limit configuration666667You can control the connection pool size using the `limits` keyword668argument on the client. It takes instances of `httpx.Limits` which define:669670- `max_keepalive_connections`, number of allowable keep-alive connections, or `None` to always671allow. (Defaults 20)672- `max_connections`, maximum number of allowable connections, or `None` for no limits.673(Default 100)674- `keepalive_expiry`, time limit on idle keep-alive connections in seconds, or `None` for no limits. (Default 5)675676```python677limits = httpx.Limits(max_keepalive_connections=5, max_connections=10)678client = httpx.Client(limits=limits)679```680681## Multipart file encoding682683As mentioned in the [quickstart](quickstart.md#sending-multipart-file-uploads)684multipart file encoding is available by passing a dictionary with the685name of the payloads as keys and either tuple of elements or a file-like object or a string as values.686687```pycon688>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}689>>> r = httpx.post("https://httpbin.org/post", files=files)690>>> print(r.text)691{692 ...693 "files": {694 "upload-file": "<... binary content ...>"695 },696 ...697}698```699700More specifically, if a tuple is used as a value, it must have between 2 and 3 elements:701702- The first element is an optional file name which can be set to `None`.703- The second element may be a file-like object or a string which will be automatically704encoded in UTF-8.705- An optional third element can be used to specify the706[MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_Types)707of the file being uploaded. If not specified HTTPX will attempt to guess the MIME type based708on the file name, with unknown file extensions defaulting to "application/octet-stream".709If the file name is explicitly set to `None` then HTTPX will not include a content-type710MIME header field.711712```pycon713>>> files = {'upload-file': (None, 'text content', 'text/plain')}714>>> r = httpx.post("https://httpbin.org/post", files=files)715>>> print(r.text)716{717 ...718 "files": {},719 "form": {720 "upload-file": "text-content"721 },722 ...723}724```725726!!! tip727 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.728729 Non-file data fields can be included in the multipart form using by passing them to `data=...`.730731You can also send multiple files in one go with a multiple file field form.732To do that, pass a list of `(field, <file>)` items instead of a dictionary, allowing you to pass multiple items with the same `field`.733For instance this request sends 2 files, `foo.png` and `bar.png` in one request on the `images` form field:734735```pycon736>>> files = [('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),737 ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]738>>> r = httpx.post("https://httpbin.org/post", files=files)739```740741## Customizing authentication742743When 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...744745* A two-tuple of `username`/`password`, to be used with basic authentication.746* An instance of `httpx.BasicAuth()`, `httpx.DigestAuth()`, or `httpx.NetRCAuth()`.747* A callable, accepting a request and returning an authenticated request instance.748* An instance of subclasses of `httpx.Auth`.749750The 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...751752```python753class MyCustomAuth(httpx.Auth):754 def __init__(self, token):755 self.token = token756757 def auth_flow(self, request):758 # Send the request, with a custom `X-Authentication` header.759 request.headers['X-Authentication'] = self.token760 yield request761```762763If the auth flow requires more than one request, you can issue multiple yields, and obtain the response in each case...764765```python766class MyCustomAuth(httpx.Auth):767 def __init__(self, token):768 self.token = token769770 def auth_flow(self, request):771 response = yield request772 if response.status_code == 401:773 # If the server issues a 401 response then resend the request,774 # with a custom `X-Authentication` header.775 request.headers['X-Authentication'] = self.token776 yield request777```778779Custom 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.780781You will then be able to access `request.content` inside the `.auth_flow()` method.782783```python784class MyCustomAuth(httpx.Auth):785 requires_request_body = True786787 def __init__(self, token):788 self.token = token789790 def auth_flow(self, request):791 response = yield request792 if response.status_code == 401:793 # If the server issues a 401 response then resend the request,794 # with a custom `X-Authentication` header.795 request.headers['X-Authentication'] = self.sign_request(...)796 yield request797798 def sign_request(self, request):799 # Create a request signature, based on `request.method`, `request.url`,800 # `request.headers`, and `request.content`.801 ...802```803804Similarly, 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.805806```python807class MyCustomAuth(httpx.Auth):808 requires_response_body = True809810 def __init__(self, access_token, refresh_token, refresh_url):811 self.access_token = access_token812 self.refresh_token = refresh_token813 self.refresh_url = refresh_url814815 def auth_flow(self, request):816 request.headers["X-Authentication"] = self.access_token817 response = yield request818819 if response.status_code == 401:820 # If the server issues a 401 response, then issue a request to821 # refresh tokens, and resend the request.822 refresh_response = yield self.build_refresh_request()823 self.update_tokens(refresh_response)824825 request.headers["X-Authentication"] = self.access_token826 yield request827828 def build_refresh_request(self):829 # Return an `httpx.Request` for refreshing tokens.830 ...831832 def update_tokens(self, response):833 # Update the `.access_token` and `.refresh_token` tokens834 # based on a refresh response.835 data = response.json()836 ...837```838839If 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`.840841```python842import asyncio843import threading844import httpx845846847class MyCustomAuth(httpx.Auth):848 def __init__(self):849 self._sync_lock = threading.RLock()850 self._async_lock = asyncio.Lock()851852 def sync_get_token(self):853 with self._sync_lock:854 ...855856 def sync_auth_flow(self, request):857 token = self.sync_get_token()858 request.headers["Authorization"] = f"Token {token}"859 yield request860861 async def async_get_token(self):862 async with self._async_lock:863 ...864865 async def async_auth_flow(self, request):866 token = await self.async_get_token()867 request.headers["Authorization"] = f"Token {token}"868 yield request869```870871If you only want to support one of the two methods, then you should still override it, but raise an explicit `RuntimeError`.872873```python874import httpx875import sync_only_library876877878class MyCustomAuth(httpx.Auth):879 def sync_auth_flow(self, request):880 token = sync_only_library.get_token(...)881 request.headers["Authorization"] = f"Token {token}"882 yield request883884 async def async_auth_flow(self, request):885 raise RuntimeError("Cannot use a sync authentication class with httpx.AsyncClient")886```887888## SSL certificates889890When 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).891892### Changing the verification defaults893894By 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.895896If you'd like to use a custom CA bundle, you can use the `verify` parameter.897898```python899import httpx900901r = httpx.get("https://example.org", verify="path/to/client.pem")902```903904Alternatively, you can pass a standard library `ssl.SSLContext`.905906```pycon907>>> import ssl908>>> import httpx909>>> context = ssl.create_default_context()910>>> context.load_verify_locations(cafile="/tmp/client.pem")911>>> httpx.get('https://example.org', verify=context)912<Response [200 OK]>913```914915We also include a helper function for creating properly configured `SSLContext` instances.916917```pycon918>>> context = httpx.create_ssl_context()919```920921The `create_ssl_context` function accepts the same set of SSL configuration arguments922(`trust_env`, `verify`, `cert` and `http2` arguments)923as `httpx.Client` or `httpx.AsyncClient`924925```pycon926>>> import httpx927>>> context = httpx.create_ssl_context(verify="/tmp/client.pem")928>>> httpx.get('https://example.org', verify=context)929<Response [200 OK]>930```931932Or you can also disable the SSL verification entirely, which is _not_ recommended.933934```python935import httpx936937r = httpx.get("https://example.org", verify=False)938```939940### SSL configuration on client instances941942If you're using a `Client()` instance, then you should pass any SSL settings when instantiating the client.943944```python945client = httpx.Client(verify=False)946```947948The `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.949950### Client Side Certificates951952You 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)953954```python955import httpx956957r = httpx.get("https://example.org", cert="path/to/client.pem")958```959960Alternatively,961962```pycon963>>> cert = ("path/to/client.pem", "path/to/client.key")964>>> httpx.get("https://example.org", cert=cert)965<Response [200 OK]>966```967968or969970```pycon971>>> cert = ("path/to/client.pem", "path/to/client.key", "password")972>>> httpx.get("https://example.org", cert=cert)973<Response [200 OK]>974```975976### Making HTTPS requests to a local server977978When making requests to local servers, such as a development server running on `localhost`, you will typically be using unencrypted HTTP connections.979980If 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:9819821. Use [trustme](https://github.com/python-trio/trustme) to generate a pair of server key/cert files, and a client cert file.9831. 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.)9841. Tell HTTPX to use the certificates stored in `client.pem`:985986```pycon987>>> import httpx988>>> r = httpx.get("https://localhost:8000", verify="/tmp/client.pem")989>>> r990Response <200 OK>991```992993## Custom Transports994995HTTPX's `Client` also accepts a `transport` argument. This argument allows you996to provide a custom Transport object that will be used to perform the actual997sending of the requests.998999### Usage10001001For some advanced configuration you might need to instantiate a transport1002class directly, and pass it to the client instance. One example is the1003`local_address` configuration which is only available via this low-level API.10041005```pycon1006>>> import httpx1007>>> transport = httpx.HTTPTransport(local_address="0.0.0.0")1008>>> client = httpx.Client(transport=transport)1009```10101011Connection 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).10121013```pycon1014>>> import httpx1015>>> transport = httpx.HTTPTransport(retries=1)1016>>> client = httpx.Client(transport=transport)1017```10181019Similarly, instantiating a transport directly provides a `uds` option for1020connecting via a Unix Domain Socket that is only available via this low-level API:10211022```pycon1023>>> import httpx1024>>> # Connect to the Docker API via a Unix Socket.1025>>> transport = httpx.HTTPTransport(uds="/var/run/docker.sock")1026>>> client = httpx.Client(transport=transport)1027>>> response = client.get("http://docker/info")1028>>> response.json()1029{"ID": "...", "Containers": 4, "Images": 74, ...}1030```10311032### urllib3 transport10331034This [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`...10351036```pycon1037>>> import httpx1038>>> from urllib3_transport import URLLib3Transport1039>>> client = httpx.Client(transport=URLLib3Transport())1040>>> client.get("https://example.org")1041<Response [200 OK]>1042```10431044### Writing custom transports10451046A transport instance must implement the low-level Transport API, which deals1047with sending a single request, and returning a response. You should either1048subclass `httpx.BaseTransport` to implement a transport to use with `Client`,1049or subclass `httpx.AsyncBaseTransport` to implement a transport to1050use with `AsyncClient`.10511052At the layer of the transport API we're using the familiar `Request` and1053`Response` models.10541055See the `handle_request` and `handle_async_request` docstrings for more details1056on the specifics of the Transport API.10571058A complete example of a custom transport implementation would be:10591060```python1061import json1062import httpx106310641065class HelloWorldTransport(httpx.BaseTransport):1066 """1067 A mock transport that always returns a JSON "Hello, world!" response.1068 """10691070 def handle_request(self, request):1071 message = {"text": "Hello, world!"}1072 content = json.dumps(message).encode("utf-8")1073 stream = httpx.ByteStream(content)1074 headers = [(b"content-type", b"application/json")]1075 return httpx.Response(200, headers=headers, stream=stream)1076```10771078Which we can use in the same way:10791080```pycon1081>>> import httpx1082>>> client = httpx.Client(transport=HelloWorldTransport())1083>>> response = client.get("https://example.org/")1084>>> response.json()1085{"text": "Hello, world!"}1086```10871088### Mock transports10891090During testing it can often be useful to be able to mock out a transport,1091and return pre-determined responses, rather than making actual network requests.10921093The `httpx.MockTransport` class accepts a handler function, which can be used1094to map requests onto pre-determined responses:10951096```python1097def handler(request):1098 return httpx.Response(200, json={"text": "Hello, world!"})109911001101# Switch to a mock transport, if the TESTING environment variable is set.1102if os.environ.get('TESTING', '').upper() == "TRUE":1103 transport = httpx.MockTransport(handler)1104else:1105 transport = httpx.HTTPTransport()11061107client = httpx.Client(transport=transport)1108```11091110For more advanced use-cases you might want to take a look at either [the third-party1111mocking library, RESPX](https://lundberg.github.io/respx/), or the [pytest-httpx library](https://github.com/Colin-b/pytest_httpx).11121113### Mounting transports11141115You can also mount transports against given schemes or domains, to control1116which transport an outgoing request should be routed via, with [the same style1117used for specifying proxy routing](#routing).11181119```python1120import httpx11211122class HTTPSRedirectTransport(httpx.BaseTransport):1123 """1124 A transport that always redirects to HTTPS.1125 """11261127 def handle_request(self, method, url, headers, stream, extensions):1128 scheme, host, port, path = url1129 if port is None:1130 location = b"https://%s%s" % (host, path)1131 else:1132 location = b"https://%s:%d%s" % (host, port, path)1133 stream = httpx.ByteStream(b"")1134 headers = [(b"location", location)]1135 extensions = {}1136 return 303, headers, stream, extensions113711381139# A client where any `http` requests are always redirected to `https`1140mounts = {'http://': HTTPSRedirectTransport()}1141client = httpx.Client(mounts=mounts)1142```11431144A couple of other sketches of how you might take advantage of mounted transports...11451146Disabling HTTP/2 on a single given domain...11471148```python1149mounts = {1150 "all://": httpx.HTTPTransport(http2=True),1151 "all://*example.org": httpx.HTTPTransport()1152}1153client = httpx.Client(mounts=mounts)1154```11551156Mocking requests to a given domain:11571158```python1159# All requests to "example.org" should be mocked out.1160# Other requests occur as usual.1161def handler(request):1162 return httpx.Response(200, json={"text": "Hello, World!"})11631164mounts = {"all://example.org": httpx.MockTransport(handler)}1165client = httpx.Client(mounts=mounts)1166```11671168Adding support for custom schemes:11691170```python1171# Support URLs like "file:///Users/sylvia_green/websites/new_client/index.html"1172mounts = {"file://": FileSystemTransport()}1173client = httpx.Client(mounts=mounts)1174```11751176### Routing11771178HTTPX provides a powerful mechanism for routing requests, allowing you to write complex rules that specify which transport should be used for each request.11791180The `mounts` dictionary maps URL patterns to HTTP transports. HTTPX matches requested URLs against URL patterns to decide which transport should be used, if any. Matching is done from most specific URL patterns (e.g. `https://<domain>:<port>`) to least specific ones (e.g. `https://`).11811182HTTPX supports routing requests based on **scheme**, **domain**, **port**, or a combination of these.11831184#### Wildcard routing11851186Route everything through a transport...11871188```python1189mounts = {1190 "all://": httpx.HTTPTransport(proxy="http://localhost:8030"),1191}1192```11931194#### Scheme routing11951196Route HTTP requests through one transport, and HTTPS requests through another...11971198```python1199mounts = {1200 "http://": httpx.HTTPTransport(proxy="http://localhost:8030"),1201 "https://": httpx.HTTPTransport(proxy="http://localhost:8031"),1202}1203```12041205#### Domain routing12061207Proxy all requests on domain "example.com", let other requests pass through...12081209```python1210mounts = {1211 "all://example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),1212}1213```12141215Proxy HTTP requests on domain "example.com", let HTTPS and other requests pass through...12161217```python1218mounts = {1219 "http://example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),1220}1221```12221223Proxy all requests to "example.com" and its subdomains, let other requests pass through...12241225```python1226mounts = {1227 "all://*example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),1228}1229```12301231Proxy all requests to strict subdomains of "example.com", let "example.com" and other requests pass through...12321233```python1234mounts = {1235 "all://*.example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),1236}1237```12381239#### Port routing12401241Proxy HTTPS requests on port 1234 to "example.com"...12421243```python1244mounts = {1245 "https://example.com:1234": httpx.HTTPTransport(proxy="http://localhost:8030"),1246}1247```12481249Proxy all requests on port 1234...12501251```python1252mounts = {1253 "all://*:1234": httpx.HTTPTransport(proxy="http://localhost:8030"),1254}1255```12561257#### No-proxy support12581259It is also possible to define requests that _shouldn't_ be routed through the transport.12601261To do so, pass `None` as the proxy URL. For example...12621263```python1264mounts = {1265 # Route requests through a proxy by default...1266 "all://": httpx.HTTPTransport(proxy="http://localhost:8031"),1267 # Except those for "example.com".1268 "all://example.com": None,1269}1270```12711272#### Complex configuration example12731274You can combine the routing features outlined above to build complex proxy routing configurations. For example...12751276```python1277mounts = {1278 # Route all traffic through a proxy by default...1279 "all://": httpx.HTTPTransport(proxy="http://localhost:8030"),1280 # But don't use proxies for HTTPS requests to "domain.io"...1281 "https://domain.io": None,1282 # And use another proxy for requests to "example.com" and its subdomains...1283 "all://*example.com": httpx.HTTPTransport(proxy="http://localhost:8031"),1284 # And yet another proxy if HTTP is used,1285 # and the "internal" subdomain on port 5550 is requested...1286 "http://internal.example.com:5550": httpx.HTTPTransport(proxy="http://localhost:8032"),1287}1288```12891290#### Environment variables12911292There are also environment variables that can be used to control the dictionary of the client mounts. 1293They can be used to configure HTTP proxying for clients.12941295See documentation on [`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`](environment_variables.md#http_proxy-https_proxy-all_proxy) for more information.1296
modified:mkdocs.yml+11 added-5 removed