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
Provenance
- Commit
7256366- Tree
b7a9bd9- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
112fb9c
1 file changed+123 added−37 removed
modified:docs/advanced.md+123 added-37 removed
1 # Advanced Usage2 3 ## Client Instances4 5-Using a Client instance to make requests will give you HTTP connection pooling,6-will provide cookie persistence, and allows you to apply configuration across7-all outgoing requests.8-5 !!! 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()`.7 12-!!! 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?9 15- 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.12 13+#### More efficient usage of network resources14+15+When 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.16+17+On 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.18+19+This can bring **significant performance improvements** compared to using the top-level API, including:20+21+- Reduced latency across requests (no handshaking).22+- Reduced CPU usage and round-trips.23+- Reduced network congestion.24+25+#### Extra features26+27+`Client` instances also support features that aren't available at the top-level API, such as:28+29+- Cookie persistance across requests.30+- Applying configuration across all outgoing requests.31+- Sending requests through HTTP proxies.32+- Using [HTTP/2](/http2).33+34+The other sections on this page go into further detail about what you can do with a `Client` instance.35+36 ### Usage37 38 The 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:39 40 ```python22->>> with httpx.Client() as client:23-... r = client.get('https://example.com')24-...25->>> r26-<Response [200 OK]>41+with httpx.Client() as client:42+ ...43 ```44 45 Alternatively, you can explicitly close the connection pool without block-usage using `.close()`:46 47 ```python32->>> client = httpx.Client()33->>> try:48+client = httpx.Client()49+try:50+ ...51+finally:52+ client.close()53+```54+55+### Making requests56+57+Once you have a `Client`, you can send requests using `.get()`, `.post()`, etc. For example:58+59+```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 ```66 42-Once you have a `Client`, you can use all the features documented in the [Quickstart](/quickstart) guide.67+These 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.68 44-### Configuration69+For example, to send a request with custom headers:70 71+```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+```79+80+### Sharing configuration across requests81+82 Clients allow you to apply configuration to all outgoing requests by passing parameters to the `Client` constructor.83 48-For example, to apply a set of custom headers on every request:84+For example, to apply a set of custom headers _on every request_:85 86 ```python87 >>> url = 'http://httpbin.org/headers'88 >>> headers = {'user-agent': 'my-app/0.0.1'}3 unmodified lines92 >>> r.json()['headers']['User-Agent']93 'my-app/0.0.1'94 ```95 60-!!! note61- When you provide a parameter at both the client and request levels, one of two things can happen:96+### Merging of configuration97 63- - For headers, query parameters and cookies, the values are merged into one.64- - For all other parameters, the request-level value is used.98+When a configuration option is provided at both the client-level and request-level, one of two things can happen:99 66-Additionally, `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:101 68-One 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.url111+URL('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+```117 118+- For all other parameters, the request-level value takes priority. For example:119+120 ```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)127+b'alice:ecila123'128+```129+130+If you need finer-grained control on the merging of client-level and request-level parameters, see [Request instances](#request-instances).131+132+### Other Client-only configuration options133+134+Additionally, `Client` accepts some configuration options that aren't available at the request level.135+136+For example, `base_url` allows you to prepend an URL to all outgoing requests:137+138+```python139 >>> with httpx.Client(base_url='http://httpbin.org') as client:140 ... r = client.get('/headers')141 ...142 >>> r.request.url143 URL('http://httpbin.org/headers')144 ```145 78-For a list of all available client-level parameters, see the [`Client` API reference](/api/#client).146+For a list of all available client parameters, see the [`Client`](/api/#client) API reference.147 148 ## Calling into Python Web Apps149 150 You can configure an `httpx` client to call directly into a Python web application using the WSGI protocol.36 unmodified lines187 with httpx.Client(dispatch=dispatch, base_url="http://testserver") as client:188 ...189 ```190 123-## Build Request191+## Request instances192 125-You can use `Client.build_request()` to build a request and126-make modifications before sending the request.193+For maximum control on what gets sent over the wire, HTTPX supports building explicit [`Request`](/api#request) instances:194 195 ```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]>196+request = httpx.Request("GET", "https://example.com")197 ```198 199+To dispatch a `Request` instance across to the network, create a [`Client` instance](#client-instances) and use `.send()`:200+201+```python202+with httpx.Client() as client:203+ response = client.send(request)204+ ...205+```206+207+If 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:208+209+```python210+headers = {"X-Api-Key": "...", "X-Client-ID": "ABC123"}211+212+with httpx.Client(headers=headers) as client:213+ request = client.build_request("GET", "https://api.example.com")214+215+ print(request.headers["X-Client-ID"]) # "ABC123"216+217+ # Don't send the API key for this particular request.218+ del request.headers["X-Api-Key"]219+220+ response = client.send(request)221+ ...222+```223+224 ## .netrc Support225 226 HTTPX supports .netrc file. In `trust_env=True` cases, if auth parameter is227 not defined, HTTPX tries to add auth into request's header from .netrc file.367 unmodified lines