Skip to content
Myr

Revamp docs on Client instances (#836)

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

* Revamp docs on Client instances * Apply suggestions from code review Co-Authored-By: Hugo van Kemenade <hugovk@users.noreply.github.com> * Reword 'Why use a Client?' section * Apply suggestions from code review Co-Authored-By: Hugo van Kemenade <hugovk@users.noreply.github.com>

authored by Florimond Manca · committed by GitHub · parent 112fb9c · Browse files · 1 file+123 added−37 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: Hugo van Kemenade <hugovk@users.noreply.github.com>

Diff stats

1 file+123 added−37 removed

  • other:+123 added−37 removed

1 file+123 added−37 removed

modified:docs/advanced.md+123 added-37 removed
1# Advanced Usage23## Client Instances45Using a Client instance to make requests will give you HTTP connection pooling,6will provide cookie persistence, and allows you to apply configuration across7all outgoing requests.85!!! hint10 A Client instance is equivalent to a Session instance in `requests`.6 If you are coming from Requests, `httpx.Client()` is what you can use instead of `requests.Session()`.712!!! note13 Starting from `httpx==0.10.0`, the default and recommended Client class is `AsyncClient`. This should help prevent breaking changes once sync support is reintroduced.8### Why use a Client?915 A `Client` synonym remains for compatibility with `httpx==0.9.*` releases, but you are encouraged to migrate to `AsyncClient` as soon as possible.10!!! 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```python22>>> with httpx.Client() as client:23... r = client.get('https://example.com')24...25>>> r26<Response [200 OK]>41with httpx.Client() as client:42 ...43```4445Alternatively, you can explicitly close the connection pool without block-usage using `.close()`:4647```python32>>> client = httpx.Client()33>>> try:48client = 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```python60>>> with httpx.Client() as client:61... r = client.get('https://example.com')35... finally:36... client.close()62...63>>> r64<Response [200 OK]>65```6642Once you have a `Client`, you can use all the features documented in the [Quickstart](/quickstart) guide.67These 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.6844### Configuration69For example, to send a request with custom headers:7071```python72>>> 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.8348For example, to apply a set of custom headers on every request:84For example, to apply a set of custom headers _on every request_:8586```python87>>> url = 'http://httpbin.org/headers'88>>> headers = {'user-agent': 'my-app/0.0.1'}
3 unmodified lines
92>>> r.json()['headers']['User-Agent']93'my-app/0.0.1'94```9560!!! note61 When you provide a parameter at both the client and request levels, one of two things can happen:96### Merging of configuration9763 - For headers, query parameters and cookies, the values are merged into one.64 - For all other parameters, the request-level value is used.98When a configuration option is provided at both the client-level and request-level, one of two things can happen:9966Additionally, `Client` accepts some parameters that aren't available at the request level.100- For headers, query parameters and cookies, the values are combined together. For example:10168One particularly useful parameter is `base_url`, which allows you to define a base URL to prepend to all outgoing requests:102```python103>>> 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```python121>>> 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```python139>>> 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```14578For a list of all available client-level parameters, see the [`Client` API reference](/api/#client).146For 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.
36 unmodified lines
187with httpx.Client(dispatch=dispatch, base_url="http://testserver") as client:188 ...189```190123## Build Request191## Request instances192125You can use `Client.build_request()` to build a request and126make modifications before sending the request.193For maximum control on what gets sent over the wire, HTTPX supports building explicit [`Request`](/api#request) instances:194195```python129>>> with httpx.Client() as client:130... req = client.build_request("OPTIONS", "https://example.com")131... req.url.full_path = "*" # Build an 'OPTIONS *' request for CORS132... r = client.send(req)133...134>>> r135<Response [200 OK]>196request = 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.
367 unmodified lines