Debian Codegraph @

docs/advanced/clients.md

raw
1 !!! hint
2 If you are coming from Requests, `httpx.Client()` is what you can use instead of `requests.Session()`.
3
4 ## Why use a Client?
5
6 !!! note "TL;DR"
7 If you do anything more than experimentation, one-off scripts, or prototypes, then you should use a `Client` instance.
8
9 **More efficient usage of network resources**
10
11 When 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.
12
13 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.
14
15 This can bring **significant performance improvements** compared to using the top-level API, including:
16
17 - Reduced latency across requests (no handshaking).
18 - Reduced CPU usage and round-trips.
19 - Reduced network congestion.
20
21 **Extra features**
22
23 `Client` instances also support features that aren't available at the top-level API, such as:
24
25 - Cookie persistence across requests.
26 - Applying configuration across all outgoing requests.
27 - Sending requests through HTTP proxies.
28 - Using [HTTP/2](../http2.md).
29
30 The other sections on this page go into further detail about what you can do with a `Client` instance.
31
32 ## Usage
33
34 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:
35
36 ```python
37 with httpx.Client() as client:
38 ...
39 ```
40
41 Alternatively, you can explicitly close the connection pool without block-usage using `.close()`:
42
43 ```python
44 client = httpx.Client()
45 try:
46 ...
47 finally:
48 client.close()
49 ```
50
51 ## Making requests
52
53 Once you have a `Client`, you can send requests using `.get()`, `.post()`, etc. For example:
54
55 ```pycon
56 >>> with httpx.Client() as client:
57 ... r = client.get('https://example.com')
58 ...
59 >>> r
60 <Response [200 OK]>
61 ```
62
63 These 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.
64
65 For example, to send a request with custom headers:
66
67 ```pycon
68 >>> 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 ```
75
76 ## Sharing configuration across requests
77
78 Clients allow you to apply configuration to all outgoing requests by passing parameters to the `Client` constructor.
79
80 For example, to apply a set of custom headers _on every request_:
81
82 ```pycon
83 >>> 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 ```
91
92 ## Merging of configuration
93
94 When a configuration option is provided at both the client-level and request-level, one of two things can happen:
95
96 - For headers, query parameters and cookies, the values are combined together. For example:
97
98 ```pycon
99 >>> 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.url
107 URL('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 ```
113
114 - For all other parameters, the request-level value takes priority. For example:
115
116 ```pycon
117 >>> 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 base64
122 >>> base64.b64decode(auth)
123 b'alice:ecila123'
124 ```
125
126 If you need finer-grained control on the merging of client-level and request-level parameters, see [Request instances](#request-instances).
127
128 ## Other Client-only configuration options
129
130 Additionally, `Client` accepts some configuration options that aren't available at the request level.
131
132 For example, `base_url` allows you to prepend an URL to all outgoing requests:
133
134 ```pycon
135 >>> with httpx.Client(base_url='http://httpbin.org') as client:
136 ... r = client.get('/headers')
137 ...
138 >>> r.request.url
139 URL('http://httpbin.org/headers')
140 ```
141
142 For a list of all available client parameters, see the [`Client`](../api.md#client) API reference.
143
144 ---
145
146 ## Request instances
147
148 For maximum control on what gets sent over the wire, HTTPX supports building explicit [`Request`](../api.md#request) instances:
149
150 ```python
151 request = httpx.Request("GET", "https://example.com")
152 ```
153
154 To dispatch a `Request` instance across to the network, create a [`Client` instance](#client-instances) and use `.send()`:
155
156 ```python
157 with httpx.Client() as client:
158 response = client.send(request)
159 ...
160 ```
161
162 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:
163
164 ```python
165 headers = {"X-Api-Key": "...", "X-Client-ID": "ABC123"}
166
167 with httpx.Client(headers=headers) as client:
168 request = client.build_request("GET", "https://api.example.com")
169
170 print(request.headers["X-Client-ID"]) # "ABC123"
171
172 # Don't send the API key for this particular request.
173 del request.headers["X-Api-Key"]
174
175 response = client.send(request)
176 ...
177 ```
178
179 ## Monitoring download progress
180
181 If you need to monitor download progress of large responses, you can use response streaming and inspect the `response.num_bytes_downloaded` property.
182
183 This 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.
184
185 For 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…
186
187 ```python
188 import tempfile
189
190 import httpx
191 from tqdm import tqdm
192
193 with 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"])
197
198 with tqdm(total=total, unit_scale=True, unit_divisor=1024, unit="B") as progress:
199 num_bytes_downloaded = response.num_bytes_downloaded
200 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_downloaded
204 ```
205
206 ![tqdm progress bar](../img/tqdm-progress.gif)
207
208 Or an alternate example, this time using the [`rich`](https://github.com/willmcgugan/rich) library…
209
210 ```python
211 import tempfile
212 import httpx
213 import rich.progress
214
215 with 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"])
219
220 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 ```
231
232 ![rich progress bar](../img/rich-progress.gif)
233
234 ## Monitoring upload progress
235
236 If you need to monitor upload progress of large responses, you can use request content generator streaming.
237
238 For example, showing a progress bar using the [`tqdm`](https://github.com/tqdm/tqdm) library.
239
240 ```python
241 import io
242 import random
243
244 import httpx
245 from tqdm import tqdm
246
247
248 def 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 # 32m
254 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 data
258 bar.update(len(data))
259
260
261 httpx.post("https://httpbin.org/post", content=gen())
262 ```
263
264 ![tqdm progress bar](../img/tqdm-progress.gif)
265
266 ## Multipart file encoding
267
268 As mentioned in the [quickstart](../quickstart.md#sending-multipart-file-uploads)
269 multipart file encoding is available by passing a dictionary with the
270 name of the payloads as keys and either tuple of elements or a file-like object or a string as values.
271
272 ```pycon
273 >>> 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 ```
284
285 More specifically, if a tuple is used as a value, it must have between 2 and 3 elements:
286
287 - 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 automatically
289 encoded in UTF-8.
290 - An optional third element can be used to specify the
291 [MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_Types)
292 of the file being uploaded. If not specified HTTPX will attempt to guess the MIME type based
293 on the file name, with unknown file extensions defaulting to "application/octet-stream".
294 If the file name is explicitly set to `None` then HTTPX will not include a content-type
295 MIME header field.
296
297 ```pycon
298 >>> 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 ```
310
311 !!! tip
312 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.
313
314 Non-file data fields can be included in the multipart form using by passing them to `data=...`.
315
316 You can also send multiple files in one go with a multiple file field form.
317 To do that, pass a list of `(field, <file>)` items instead of a dictionary, allowing you to pass multiple items with the same `field`.
318 For instance this request sends 2 files, `foo.png` and `bar.png` in one request on the `images` form field:
319
320 ```pycon
321 >>> 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 ```