advanced.md
This file
Path
docs/advanced.md
952 lines · 32.2 KiB · Markdown
Last changed by
Add support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee
History of this fileTake it
The walk stopped after 200 commits: lines older than a82adcc point at it.
Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 1–58why, one step back1# Advanced Usage23## Client Instances45!!! hint6 If you are coming from Requests, `httpx.Client()` is what you can use instead of `requests.Session()`.78### Why use a Client?910!!! note "TL;DR"11 If you do anything more than experimentation, one-off scripts, or prototypes, then you should use a `Client` instance.1213#### More efficient usage of network resources1415When you make requests using the top-level API as documented in the [Quickstart](/quickstart) guide, HTTPX has to establish a new connection _for every single request_ (connections are not reused). As the number of requests to a host increases, this quickly becomes inefficient.1617On the other hand, a `Client` instance uses [HTTP connection pooling](https://en.wikipedia.org/wiki/HTTP_persistent_connection). This means that when you make several requests to the same host, the `Client` will reuse the underlying TCP connection, instead of recreating one for every single request.1819This can bring **significant performance improvements** compared to using the top-level API, including:2021- Reduced latency across requests (no handshaking).22- Reduced CPU usage and round-trips.23- Reduced network congestion.2425#### Extra features2627`Client` instances also support features that aren't available at the top-level API, such as:2829- Cookie persistance across requests.30- Applying configuration across all outgoing requests.31- Sending requests through HTTP proxies.32- Using [HTTP/2](/http2).3334The other sections on this page go into further detail about what you can do with a `Client` instance.3536### Usage3738The recommended way to use a `Client` is as a context manager. This will ensure that connections are properly cleaned up when leaving the `with` block:3940```python41with httpx.Client() as client:42 ...43```4445Alternatively, you can explicitly close the connection pool without block-usage using `.close()`:4647```python48client = httpx.Client()49try:50 ...51finally:52 client.close()53```5455### Making requests5657Once you have a `Client`, you can send requests using `.get()`, `.post()`, etc. For example:58Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 59why, one step back59```pyconUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 60–70why, one step back60>>> with httpx.Client() as client:61... r = client.get('https://example.com')62...63>>> r64<Response [200 OK]>65```6667These methods accept the same arguments as `httpx.get()`, `httpx.post()`, etc. This means that all features documented in the [Quickstart](/quickstart) guide are also available at the client level.6869For example, to send a request with custom headers:70Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 71why, one step back71```pyconUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 72–85why, one step back72>>> with httpx.Client() as client:73... headers = {'X-Custom': 'value'}74... r = client.get('https://example.com', headers=headers)75...76>>> r.request.headers['X-Custom']77'value'78```7980### Sharing configuration across requests8182Clients allow you to apply configuration to all outgoing requests by passing parameters to the `Client` constructor.8384For example, to apply a set of custom headers _on every request_:85Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 86why, one step back86```pyconUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 87–101why, one step back87>>> url = 'http://httpbin.org/headers'88>>> headers = {'user-agent': 'my-app/0.0.1'}89>>> with httpx.Client(headers=headers) as client:90... r = client.get(url)91...92>>> r.json()['headers']['User-Agent']93'my-app/0.0.1'94```9596### Merging of configuration9798When a configuration option is provided at both the client-level and request-level, one of two things can happen:99100- For headers, query parameters and cookies, the values are combined together. For example:101Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 102why, one step back102```pyconUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 103–119why, one step back103>>> headers = {'X-Auth': 'from-client'}104>>> params = {'client_id': 'client1'}105>>> with httpx.Client(headers=headers, params=params) as client:106... headers = {'X-Custom': 'from-request'}107... params = {'request_id': 'request1'}108... r = client.get('https://example.com', headers=headers, params=params)109...110>>> r.request.url111URL('https://example.com?client_id=client1&request_id=request1')112>>> r.request.headers['X-Auth']113'from-client'114>>> r.request.headers['X-Custom']115'from-request'116```117118- For all other parameters, the request-level value takes priority. For example:119Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 120why, one step back120```pyconUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 121–137why, one step back121>>> with httpx.Client(auth=('tom', 'mot123')) as client:122... r = client.get('https://example.com', auth=('alice', 'ecila123'))123...124>>> _, _, auth = r.request.headers['Authorization'].partition(' ')125>>> import base64126>>> base64.b64decode(auth)127b'alice:ecila123'128```129130If you need finer-grained control on the merging of client-level and request-level parameters, see [Request instances](#request-instances).131132### Other Client-only configuration options133134Additionally, `Client` accepts some configuration options that aren't available at the request level.135136For example, `base_url` allows you to prepend an URL to all outgoing requests:137Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 138why, one step back138```pyconUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 139–175why, one step back139>>> with httpx.Client(base_url='http://httpbin.org') as client:140... r = client.get('/headers')141...142>>> r.request.url143URL('http://httpbin.org/headers')144```145146For a list of all available client parameters, see the [`Client`](/api/#client) API reference.147148## Calling into Python Web Apps149150You can configure an `httpx` client to call directly into a Python web application using the WSGI protocol.151152This is particularly useful for two main use-cases:153154* Using `httpx` as a client inside test cases.155* Mocking out external services during tests or in dev/staging environments.156157Here's an example of integrating against a Flask application:158159```python160from flask import Flask161import httpx162163164app = Flask(__name__)165166@app.route("/")167def hello():168 return "Hello World!"169170with httpx.Client(app=app, base_url="http://testserver") as client:171 r = client.get("/")172 assert r.status_code == 200173 assert r.text == "Hello World!"174```175Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
line 176why, one step back176For some more complex cases you might need to customize the WSGI transport. This allows you to:Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 177–185why, one step back177178* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.179* Mount the WSGI application at a subpath by setting `script_name` (WSGI).180* Use a given client address for requests by setting `remote_addr` (WSGI).181182For example:183184```python185# Instantiate a client that makes WSGI requests with a client IP of "1.2.3.4".Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
lines 186–187why, one step back186transport = httpx.WSGITransport(app=app, remote_addr="1.2.3.4")187with httpx.Client(transport=transport, base_url="http://testserver") as client:Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 188–234why, one step back188 ...189```190191## Request instances192193For maximum control on what gets sent over the wire, HTTPX supports building explicit [`Request`](/api#request) instances:194195```python196request = httpx.Request("GET", "https://example.com")197```198199To dispatch a `Request` instance across to the network, create a [`Client` instance](#client-instances) and use `.send()`:200201```python202with httpx.Client() as client:203 response = client.send(request)204 ...205```206207If you need to mix client-level and request-level options in a way that is not supported by the default [Merging of parameters](#merging-of-parameters), you can use `.build_request()` and then make arbitrary modifications to the `Request` instance. For example:208209```python210headers = {"X-Api-Key": "...", "X-Client-ID": "ABC123"}211212with httpx.Client(headers=headers) as client:213 request = client.build_request("GET", "https://api.example.com")214215 print(request.headers["X-Client-ID"]) # "ABC123"216217 # Don't send the API key for this particular request.218 del request.headers["X-Api-Key"]219220 response = client.send(request)221 ...222```223224## .netrc Support225226HTTPX supports .netrc file. In `trust_env=True` cases, if auth parameter is227not defined, HTTPX tries to add auth into request's header from .netrc file.228229!!! note230 The NETRC file is cached across requests made by a client.231 If you need to refresh the cache (e.g. because the NETRC file has changed),232 you should create a new client or restart the interpreter.233234As default `trust_env` is true. To set false:Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 235why, one step back235```pyconUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 236–242why, one step back236>>> httpx.get('https://example.org/', trust_env=False)237```238239If `NETRC` environment is empty, HTTPX tries to use default files.240(`~/.netrc`, `~/_netrc`)241242To change `NETRC` environment:Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 243why, one step back243```pyconUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 244–264why, one step back244>>> import os245>>> os.environ["NETRC"] = "my_default_folder/.my_netrc"246```247248.netrc file content example:249```250machine netrcexample.org251login example-username252password example-password253254...255```256257When using `Client` instances, `trust_env` should be set on the client itself, rather that on the request methods:258259```python260client = httpx.Client(trust_env=False)261```262263## HTTP Proxying264Add `proxies` parameter to top-level API functions (#1198)Joebefore adoption84ca201
line 265why, one step back265HTTPX 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=...)`.Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 266why, one step back266Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 267–277why, one step back267_Note: SOCKS proxies are not supported yet._268269<div align="center">270 <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/27/Open_proxy_h2g2bob.svg/480px-Open_proxy_h2g2bob.svg.png"/>271 <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>272</div>273274### Example275276To route all traffic (HTTP and HTTPS) to a proxy located at `http://localhost:8030`, pass the proxy URL to the client...277Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 278why, one step back278```pythonRevamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 279–280why, one step back279with httpx.Client(proxies="http://localhost:8030") as client:280 ...Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 281–282why, one step back281```282Refine docs phrasing on proxy routing (#1124)Florimond Mancabefore adoption0fb28e8
line 283why, one step back283For 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:Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 284why, one step back284Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 285–286why, one step back285```python286proxies = {Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4
lines 287–288why, one step back287 "http://": "http://localhost:8030",288 "https://": "http://localhost:8031",Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
line 289why, one step back289}Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 290why, one step back290Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 291–297why, one step back291with httpx.Client(proxies=proxies) as client:292 ...293```294295For detailed information about proxy routing, see the [Routing](#routing) section.296297!!! tip "Gotcha"Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4
line 298why, one step back298 In most cases, the proxy URL for the `https://` key _should_ use the `http://` scheme (that's not a typo!).Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 299–307why, one step back299300 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.301302 For more information, see [FORWARD vs TUNNEL](#forward-vs-tunnel).303304### Authentication305306Proxy credentials can be passed as the `userinfo` section of the proxy URL. For example:307Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 308why, one step back308```pythonRevamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
line 309why, one step back309proxies = {Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4
line 310why, one step back310 "http://": "http://username:password@localhost:8030",Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 311–312why, one step back311 # ...312}Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 313–314why, one step back313```314Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
line 315why, one step back315### RoutingUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 316why, one step back316Refine docs phrasing on proxy routing (#1124)Florimond Mancabefore adoption0fb28e8
line 317why, one step back317HTTPX provides fine-grained controls for deciding which requests should go through a proxy, and which shouldn't. This process is known as proxy routing.Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 318why, one step back318Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4
line 319why, one step back319The `proxies` dictionary maps URL patterns ("proxy keys") to proxy URLs. HTTPX matches requested URLs against proxy keys to decide which proxy should be used, if any. Matching is done from most specific proxy keys (e.g. `https://<domain>:<port>`) to least specific ones (e.g. `https://`).Refine docs phrasing on proxy routing (#1124)Florimond Mancabefore adoption0fb28e8
lines 320–322why, one step back320321HTTPX supports routing proxies based on **scheme**, **domain**, **port**, or a combination of these.322Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
line 323why, one step back323#### Wildcard routingUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 324why, one step back324Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 325–326why, one step back325Route everything through a proxy...326Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 327why, one step back327```pythonRevamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
line 328why, one step back328proxies = {Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4
line 329why, one step back329 "all://": "http://localhost:8030",Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
line 330why, one step back330}Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 331–332why, one step back331```332Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 333–338why, one step back333#### Scheme routing334335Route HTTP requests through one proxy, and HTTPS requests through another...336337```python338proxies = {Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4
lines 339–340why, one step back339 "http://": "http://localhost:8030",340 "https://": "http://localhost:8031",Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 341–404why, one step back341}342```343344#### Domain routing345346Proxy all requests on domain "example.com", let other requests pass through...347348```python349proxies = {350 "all://example.com": "http://localhost:8030",351}352```353354Proxy HTTP requests on domain "example.com", let HTTPS and other requests pass through...355356```python357proxies = {358 "http://example.com": "http://localhost:8030",359}360```361362Proxy all requests to "example.com" and its subdomains, let other requests pass through...363364```python365proxies = {366 "all://*example.com": "http://localhost:8030",367}368```369370Proxy all requests to strict subdomains of "example.com", let "example.com" and other requests pass through...371372```python373proxies = {374 "all://*.example.com": "http://localhost:8030",375}376```377378#### Port routing379380Proxy HTTPS requests on port 1234 to "example.com"...381382```python383proxies = {384 "https://example.com:1234": "http://localhost:8030",385}386```387388Proxy all requests on port 1234...389390```python391proxies = {392 "all://*:1234": "http://localhost:8030",393}394```395396#### No-proxy support397398It is also possible to define requests that _shouldn't_ be routed through proxies.399400To do so, pass `None` as the proxy URL. For example...401402```python403proxies = {404 # Route requests through a proxy by default...Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4
line 405why, one step back405 "all://": "http://localhost:8031",Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 406–417why, one step back406 # Except those for "example.com".407 "all://example.com": None,408}409```410411#### Complex configuration example412413You can combine the routing features outlined above to build complex proxy routing configurations. For example...414415```python416proxies = {417 # Route all traffic through a proxy by default...Raise warning if proxy key is eg. "all" instead of "all://". (#1127)cdelerbefore adoption7279ed4
line 418why, one step back418 "all://": "http://localhost:8030",Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 419–436why, one step back419 # But don't use proxies for HTTPS requests to "domain.io"...420 "https://domain.io": None,421 # And use another proxy for requests to "example.com" and its subdomains...422 "all://*example.com": "http://localhost:8031",423 # And yet another proxy if HTTP is used,424 # and the "internal" subdomain on port 5550 is requested...425 "http://internal.example.com:5550": "http://localhost:8032",426}427```428429#### Environment variables430431HTTP proxying can also be configured through environment variables, although with less fine-grained control.432433See documentation on [`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`](/environment_variables/#http_proxy-https_proxy-all_proxy) for more information.434435### Proxy mechanisms436Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 437why, one step back437!!! noteRevamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
line 438why, one step back438 This section describes **advanced** proxy concepts and functionality.Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 439why, one step back439Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
line 440why, one step back440#### FORWARD vs TUNNELUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 441why, one step back441Revamp proxies documentation (#1123)Florimond Mancabefore adoption70cdd95
lines 442–477why, one step back442In general, the flow for making an HTTP request through a proxy is as follows:4434441. The client connects to the proxy (initial connection request).4451. The proxy somehow transfers data to the server on your behalf.446447How exactly step 2/ is performed depends on which of two proxying mechanisms is used:448449* **Forwarding**: the proxy makes the request for you, and sends back the response it obtained from the server.450* **Tunneling**: the proxy establishes a TCP connection to the server on your behalf, and the client reuses this connection to send the request and receive the response. This is known as an [HTTP Tunnel](https://en.wikipedia.org/wiki/HTTP_tunnel). This mechanism is how you can access websites that use HTTPS from an HTTP proxy (the client "upgrades" the connection to HTTPS by performing the TLS handshake with the server over the TCP connection provided by the proxy).451452#### Default behavior453454Given the technical definitions above, by default (and regardless of whether you're using an HTTP or HTTPS proxy), HTTPX will:455456* Use forwarding for HTTP requests.457* Use tunneling for HTTPS requests.458459This ensures that you can make HTTP and HTTPS requests in all cases (i.e. regardless of which type of proxy you're using).460461#### Forcing the proxy mechanism462463In most cases, the default behavior should work just fine as well as provide enough security.464465But if you know what you're doing and you want to force which mechanism to use, you can do so by passing an `httpx.Proxy()` instance, setting the `mode` to either `FORWARD_ONLY` or `TUNNEL_ONLY`. For example...466467```python468# Route all requests through an HTTPS proxy, using tunneling only.469proxies = httpx.Proxy(470 url="https://localhost:8030",471 mode="TUNNEL_ONLY",472)473474with httpx.Client(proxies=proxies) as client:475 # This HTTP request will be tunneled instead of forwarded.476 r = client.get("http://example.com")477```Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 478–527why, one step back478479## Timeout Configuration480481HTTPX is careful to enforce timeouts everywhere by default.482483The default behavior is to raise a `TimeoutException` after 5 seconds of484network inactivity.485486### Setting and disabling timeouts487488You can set timeouts for an individual request:489490```python491# Using the top-level API:492httpx.get('http://example.com/api/v1/example', timeout=10.0)493494# Using a client instance:495with httpx.Client() as client:496 client.get("http://example.com/api/v1/example", timeout=10.0)497```498499Or disable timeouts for an individual request:500501```python502# Using the top-level API:503httpx.get('http://example.com/api/v1/example', timeout=None)504505# Using a client instance:506with httpx.Client() as client:507 client.get("http://example.com/api/v1/example", timeout=None)508```509510### Setting a default timeout on a client511512You can set a timeout on a client instance, which results in the given513`timeout` being used as the default for requests made with this client:514515```python516client = httpx.Client() # Use a default 5s timeout everywhere.517client = httpx.Client(timeout=10.0) # Use a default 10s timeout everywhere.518client = httpx.Client(timeout=None) # Disable all timeouts by default.519```520521### Fine tuning the configuration522523HTTPX also allows you to specify the timeout behavior in more fine grained detail.524525There are four different types of timeouts that may occur. These are **connect**,526**read**, **write**, and **pool** timeouts.527Switch to more concise Timeout parameters (#1111)Florimond Mancabefore adoption26cd4f5
line 528why, one step back528* The **connect** timeout specifies the maximum amount of time to wait untilUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 529–530why, one step back529a connection to the requested host is established. If HTTPX is unable to connect530within this time frame, a `ConnectTimeout` exception is raised.Switch to more concise Timeout parameters (#1111)Florimond Mancabefore adoption26cd4f5
line 531why, one step back531* The **read** timeout specifies the maximum duration to wait for a chunk ofUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 532–533why, one step back532data to be received (for example, a chunk of the response body). If HTTPX is533unable to receive data within this time frame, a `ReadTimeout` exception is raised.Switch to more concise Timeout parameters (#1111)Florimond Mancabefore adoption26cd4f5
line 534why, one step back534* The **write** timeout specifies the maximum duration to wait for a chunk ofUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 535–536why, one step back535data to be sent (for example, a chunk of the request body). If HTTPX is unable536to send data within this time frame, a `WriteTimeout` exception is raised.Switch to more concise Timeout parameters (#1111)Florimond Mancabefore adoption26cd4f5
line 537why, one step back537* The **pool** timeout specifies the maximum duration to wait for acquiringUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 538–546why, one step back538a connection from the connection pool. If HTTPX is unable to acquire a connection539within this time frame, a `PoolTimeout` exception is raised. A related540configuration here is the maximum number of allowable connections in the541connection pool, which is configured by the `pool_limits`.542543You can configure the timeout behavior for any of these values...544545```python546# A client with a 60s timeout for connecting, and a 10s timeout elsewhere.Switch to more concise Timeout parameters (#1111)Florimond Mancabefore adoption26cd4f5
line 547why, one step back547timeout = httpx.Timeout(10.0, connect=60.0)Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 548–552why, one step back548client = httpx.Client(timeout=timeout)549550response = client.get('http://example.com/')551```552Document pool_limits and SSL context on verify (#942)Yeray Diaz Diazbefore adoption790a3ea
lines 553–554why, one step back553## Pool limit configuration554Rename PoolLimits to Limits (#1113)Florimond Mancabefore adoptionf67e925
lines 555–556why, one step back555You can control the connection pool size using the `limits` keyword556argument on the client. It takes instances of `httpx.Limits` which define:Document pool_limits and SSL context on verify (#942)Yeray Diaz Diazbefore adoption790a3ea
line 557why, one step back557Rename pool limit options (#968)Tom Christiebefore adoption991915a
line 558why, one step back558- `max_keepalive`, number of allowable keep-alive connections, or `None` to alwaysDocument pool_limits and SSL context on verify (#942)Yeray Diaz Diazbefore adoption790a3ea
line 559why, one step back559allow. (Defaults 10)Rename pool limit options (#968)Tom Christiebefore adoption991915a
line 560why, one step back560- `max_connections`, maximum number of allowable connections, or` None` for no limits.Document pool_limits and SSL context on verify (#942)Yeray Diaz Diazbefore adoption790a3ea
lines 561–564why, one step back561(Default 100)562563564```pythonRename PoolLimits to Limits (#1113)Florimond Mancabefore adoptionf67e925
lines 565–566why, one step back565limits = httpx.Limits(max_keepalive=5, max_connections=10)566client = httpx.Client(limits=limits)Document pool_limits and SSL context on verify (#942)Yeray Diaz Diazbefore adoption790a3ea
lines 567–568why, one step back567```568Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 569–574why, one step back569## Multipart file encoding570571As mentioned in the [quickstart](/quickstart#sending-multipart-file-uploads)572multipart file encoding is available by passing a dictionary with the573name of the payloads as keys and either tuple of elements or a file-like object or a string as values.574Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 575why, one step back575```pyconUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 576–599why, one step back576>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}577>>> r = httpx.post("https://httpbin.org/post", files=files)578>>> print(r.text)579{580 ...581 "files": {582 "upload-file": "<... binary content ...>"583 },584 ...585}586```587588More specifically, if a tuple is used as a value, it must have between 2 and 3 elements:589590- The first element is an optional file name which can be set to `None`.591- The second element may be a file-like object or a string which will be automatically592encoded in UTF-8.593- An optional third element can be used to specify the594[MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_Types)595of the file being uploaded. If not specified HTTPX will attempt to guess the MIME type based596on the file name, with unknown file extensions defaulting to "application/octet-stream".597If the file name is explicitly set to `None` then HTTPX will not include a content-type598MIME header field.599Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 600why, one step back600```pyconUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 601–613why, one step back601>>> files = {'upload-file': (None, 'text content', 'text/plain')}602>>> r = httpx.post("https://httpbin.org/post", files=files)603>>> print(r.text)604{605 ...606 "files": {},607 "form": {608 "upload-file": "text-content"609 },610 ...611}612```613Add note on streaming uploads (#973)Florimond Mancabefore adoptiona58be59
lines 614–615why, one step back614!!! tip615 It is safe to upload large files this way. File uploads are streaming by default, meaning that only one chunk will be loaded into memory at a time.Advanced transport docs (#1165)Tom Christiebefore adoption477824a
line 616why, one step back616Add note on data fields in multipart form encoding (#1022)Florimond Mancabefore adoption0f7d644
line 617why, one step back617 Non-file data fields can be included in the multipart form using by passing them to `data=...`.Advanced transport docs (#1165)Tom Christiebefore adoption477824a
line 618why, one step back618Add support for multiple files per POST field (#1032)euri10before adoption4d28795
lines 619–620why, one step back619You can also send multiple files in one go with a multiple file field form.620To do that, pass a list of `(field, <file>)` items instead of a dictionary, allowing you to pass multiple items with the same `field`.Advanced transport docs (#1165)Tom Christiebefore adoption477824a
line 621why, one step back621For instance this request sends 2 files, `foo.png` and `bar.png` in one request on the `images` form field:Add support for multiple files per POST field (#1032)euri10before adoption4d28795
line 622why, one step back622Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 623why, one step back623```pyconAdd support for multiple files per POST field (#1032)euri10before adoption4d28795
lines 624–627why, one step back624>>> files = [('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),625 ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]626>>> r = httpx.post("https://httpbin.org/post", files=files)627```Add note on data fields in multipart form encoding (#1022)Florimond Mancabefore adoption0f7d644
line 628why, one step back628Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 629–726why, one step back629## Customizing authentication630631When 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...632633* A two-tuple of `username`/`password`, to be used with basic authentication.634* An instance of `httpx.BasicAuth()` or `httpx.DigestAuth()`.635* A callable, accepting a request and returning an authenticated request instance.636* A subclass of `httpx.Auth`.637638The 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...639640```python641class MyCustomAuth(httpx.Auth):642 def __init__(self, token):643 self.token = token644645 def auth_flow(self, request):646 # Send the request, with a custom `X-Authentication` header.647 request.headers['X-Authentication'] = self.token648 yield request649```650651If the auth flow requires more that one request, you can issue multiple yields, and obtain the response in each case...652653```python654class MyCustomAuth(httpx.Auth):655 def __init__(self, token):656 self.token = token657658 def auth_flow(self, request):659 response = yield request660 if response.status_code == 401:661 # If the server issues a 401 response then resend the request,662 # with a custom `X-Authentication` header.663 request.headers['X-Authentication'] = self.token664 yield request665```666667Custom 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.668669You will then be able to access `request.content` inside the `.auth_flow()` method.670671```python672class MyCustomAuth(httpx.Auth):673 requires_request_body = True674675 def __init__(self, token):676 self.token = token677678 def auth_flow(self, request):679 response = yield request680 if response.status_code == 401:681 # If the server issues a 401 response then resend the request,682 # with a custom `X-Authentication` header.683 request.headers['X-Authentication'] = self.sign_request(...)684 yield request685686 def sign_request(self, request):687 # Create a request signature, based on `request.method`, `request.url`,688 # `request.headers`, and `request.content`.689 ...690```691692Similarly, 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.693694```python695class MyCustomAuth(httpx.Auth):696 requires_response_body = True697698 def __init__(self, access_token, refresh_token, refresh_url):699 self.access_token = access_token700 self.refresh_token = refresh_token701 self.refresh_url = refresh_url702703 def auth_flow(self, request):704 request.headers["X-Authentication"] = self.access_token705 response = yield request706707 if response.status_code == 401:708 # If the server issues a 401 response, then issue a request to709 # refresh tokens, and resend the request.710 refresh_response = yield self.build_refresh_request()711 self.update_tokens(refresh_response)712713 request.headers["X-Authentication"] = self.access_token714 yield request715716 def build_refresh_request(self):717 # Return an `httpx.Request` for refreshing tokens.718 ...719720 def update_tokens(self, response):721 # Update the `.access_token` and `.refresh_token` tokens722 # based on a refresh response.723 data = response.json()724 ...725```726Add support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee
lines 727–775why, one step back727If 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`.728729```python730import asyncio731import threading732import httpx733734735class MyCustomAuth(httpx.Auth):736 def __init__(self):737 self._sync_lock = threading.RLock()738 self._async_lock = asyncio.Lock()739740 def sync_get_token(self):741 with self._sync_lock:742 ...743744 def sync_auth_flow(self, request):745 token = self.sync_get_token()746 request.headers["Authorization"] = f"Token {token}"747 yield request748749 async def async_get_token(self):750 async with self._async_lock:751 ...752753 async def async_auth_flow(self, request):754 token = await self.async_get_token()755 request.headers["Authorization"] = f"Token {token}"756 yield request757```758759If you only want to support one of the two methods, then you should still override it, but raise an explicit `RuntimeError`.760761```python762import httpx763import sync_only_library764765766class MyCustomAuth(httpx.Auth):767 def sync_auth_flow(self, request):768 token = sync_only_library.get_token(...)769 request.headers["Authorization"] = f"Token {token}"770 yield request771772 async def async_auth_flow(self, request):773 raise RuntimeError("Cannot use a sync authentication class with httpx.AsyncClient")774```775Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 776–791why, one step back776## SSL certificates777778When 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).779780### Changing the verification defaults781782By 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.783784If you'd like to use a custom CA bundle, you can use the `verify` parameter.785786```python787import httpx788789r = httpx.get("https://example.org", verify="path/to/client.pem")790```791Document pool_limits and SSL context on verify (#942)Yeray Diaz Diazbefore adoption790a3ea
lines 792–793why, one step back792Alternatively, you can pass a standard library `ssl.SSLContext`.793Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 794why, one step back794```pyconDocument pool_limits and SSL context on verify (#942)Yeray Diaz Diazbefore adoption790a3ea
lines 795–802why, one step back795>>> import ssl796>>> import httpx797>>> context = ssl.create_default_context()798>>> context.load_verify_locations(cafile="/tmp/client.pem")799>>> httpx.get('https://example.org', verify=context)800<Response [200 OK]>801```802Included create_ssl_context function to create the same context with SSLConfig and serve as API (#996)Can Sarıgölbefore adoption926a55a
lines 803–804why, one step back803We also include a helper function for creating properly configured `SSLContext` instances.804Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 805why, one step back805```pyconIncluded create_ssl_context function to create the same context with SSLConfig and serve as API (#996)Can Sarıgölbefore adoption926a55a
lines 806–808why, one step back806>>> context = httpx.create_ssl_context()807```808Advanced transport docs (#1165)Tom Christiebefore adoption477824a
lines 809–810why, one step back809The `create_ssl_context` function accepts the same set of SSL configuration arguments810(`trust_env`, `verify`, `cert` and `http2` arguments)Included create_ssl_context function to create the same context with SSLConfig and serve as API (#996)Can Sarıgölbefore adoption926a55a
lines 811–812why, one step back811as `httpx.Client` or `httpx.AsyncClient`812Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 813why, one step back813```pyconIncluded create_ssl_context function to create the same context with SSLConfig and serve as API (#996)Can Sarıgölbefore adoption926a55a
lines 814–819why, one step back814>>> import httpx815>>> context = httpx.create_ssl_context(verify="/tmp/client.pem")816>>> httpx.get('https://example.org', verify=context)817<Response [200 OK]>818```819Document pool_limits and SSL context on verify (#942)Yeray Diaz Diazbefore adoption790a3ea
line 820why, one step back820Or you can also disable the SSL verification entirely, which is _not_ recommended.Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 821–847why, one step back821822```python823import httpx824825r = httpx.get("https://example.org", verify=False)826```827828### SSL configuration on client instances829830If you're using a `Client()` instance, then you should pass any SSL settings when instantiating the client.831832```python833client = httpx.Client(verify=False)834```835836The `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.837838### Making HTTPS requests to a local server839840When making requests to local servers, such as a development server running on `localhost`, you will typically be using unencrypted HTTP connections.841842If 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:8438441. Use [trustme-cli](https://github.com/sethmlarson/trustme-cli/) to generate a pair of server key/cert files, and a client cert file.8451. 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.)8461. Tell HTTPX to use the certificates stored in `client.pem`:847Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 848why, one step back848```pyconUpdate CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
lines 849–852why, one step back849>>> import httpx850>>> r = httpx.get("https://localhost:8000", verify="/tmp/client.pem")851>>> r852Response <200 OK>Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
lines 853–860why, one step back853```854855## Custom Transports856857HTTPX's `Client` also accepts a `transport` argument. This argument allows you858to provide a custom Transport object that will be used to perform the actual859sending of the requests.860Drop urllib3 in favor of public gist (#1182)Florimond Mancabefore adoption8fa8765
lines 861–862why, one step back861### Usage862Advanced transport docs (#1165)Tom Christiebefore adoption477824a
lines 863–866why, one step back863For some advanced configuration you might need to instantiate a transport864class directly, and pass it to the client instance. The `httpcore` package865provides a `local_address` configuration that is only available via this866low-level API.Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
line 867why, one step back867Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 868why, one step back868```pyconAdvanced transport docs (#1165)Tom Christiebefore adoption477824a
lines 869–880why, one step back869>>> import httpx, httpcore870>>> ssl_context = httpx.create_ssl_context()871>>> transport = httpcore.SyncConnectionPool(872... ssl_context=ssl_context,873... max_connections=100,874... max_keepalive_connections=20,875... keepalive_expiry=5.0,876... local_address="0.0.0.0"877... ) # Use the standard HTTPX defaults, but with an IPv4 only 'local_address'.878>>> client = httpx.Client(transport=transport)879```880Document Unix Domain Socket usage (#1186)Florimond Mancabefore adoption34ba0e1
lines 881–898why, one step back881Similarly, `httpcore` provides a `uds` option for connecting via a Unix Domain Socket that is only available via this low-level API:882883```python884>>> import httpx, httpcore885>>> ssl_context = httpx.create_ssl_context()886>>> transport = httpcore.SyncConnectionPool(887... ssl_context=ssl_context,888... max_connections=100,889... max_keepalive_connections=20,890... keepalive_expiry=5.0,891... uds="/var/run/docker.sock",892... ) # Connect to the Docker API via a Unix Socket.893>>> client = httpx.Client(transport=transport)894>>> response = client.get("http://docker/info")895>>> response.json()896{"ID": "...", "Containers": 4, "Images": 74, ...}897```898Advanced transport docs (#1165)Tom Christiebefore adoption477824a
lines 899–903why, one step back899Unlike the `httpx.Client()`, the lower-level `httpcore` transport instances900do not include any default values for configuring aspects such as the901connection pooling details, so you'll need to provide more explicit902configuration when using this API.903Drop urllib3 in favor of public gist (#1182)Florimond Mancabefore adoption8fa8765
line 904why, one step back904### urllib3 transportTransport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
line 905why, one step back905Drop urllib3 in favor of public gist (#1182)Florimond Mancabefore adoption8fa8765
lines 906–907why, one step back906This [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`...907Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 908why, one step back908```pyconTransport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
line 909why, one step back909>>> import httpxDrop urllib3 in favor of public gist (#1182)Florimond Mancabefore adoption8fa8765
lines 910–911why, one step back910>>> from urllib3_transport import URLLib3Transport911>>> client = httpx.Client(transport=URLLib3Transport())Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
lines 912–915why, one step back912>>> client.get("https://example.org")913<Response [200 OK]>914```915Drop urllib3 in favor of public gist (#1182)Florimond Mancabefore adoption8fa8765
line 916why, one step back916### Writing custom transportsUpdate dependencies in docs (#969)Tom Christiebefore adoption99a5c78
line 917why, one step back917Advanced transport docs (#1165)Tom Christiebefore adoption477824a
lines 918–923why, one step back918A transport instance must implement the Transport API defined by919[`httpcore`](https://www.encode.io/httpcore/api/). You920should either subclass `httpcore.AsyncHTTPTransport` to implement a transport to921use with `AsyncClient`, or subclass `httpcore.SyncHTTPTransport` to implement a922transport to use with `Client`.923Update dependencies in docs (#969)Tom Christiebefore adoption99a5c78
line 924why, one step back924A complete example of a custom transport implementation would be:Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
lines 925–930why, one step back925926```python927import json928import httpcore929930Advanced transport docs (#1165)Tom Christiebefore adoption477824a
line 931why, one step back931class HelloWorldTransport(httpcore.SyncHTTPTransport):Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
line 932why, one step back932 """Advanced transport docs (#1165)Tom Christiebefore adoption477824a
line 933why, one step back933 A mock transport that always returns a JSON "Hello, world!" response.Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
lines 934–936why, one step back934 """935936 def request(self, method, url, headers=None, stream=None, timeout=None):Advanced transport docs (#1165)Tom Christiebefore adoption477824a
lines 937–939why, one step back937 message = {"text": "Hello, world!"}938 content = json.dumps(message).encode("utf-8")939 stream = httpcore.PlainByteStream(content)Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
lines 940–945why, one step back940 headers = [(b"content-type", b"application/json")]941 return b"HTTP/1.1", 200, b"OK", headers, stream942```943944Which we can use in the same way:945Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 946why, one step back946```pyconAdvanced transport docs (#1165)Tom Christiebefore adoption477824a
lines 947–949why, one step back947>>> import httpx948>>> client = httpx.Client(transport=HelloWorldTransport())949>>> response = client.get("https://example.org/")Transport API (#963)Yeray Diaz Diazbefore adoptiond2816c9
line 950why, one step back950>>> response.json()Advanced transport docs (#1165)Tom Christiebefore adoption477824a
line 951why, one step back951{"text": "Hello, world!"}Update CHANGELOG.md (#854)Tom Christiebefore adoptiona82adcc
line 952why, one step back952```