clients.md
This file
Path
docs/advanced/clients.md
324 lines · 11.1 KiB · Markdown
Last changed by
Docs restructuring. (#3049)Tom Christiebefore adoption8cd952c
History of this fileTake it
Docs restructuring. (#3049)Tom Christiebefore adoption8cd952c
lines 1–324why, one step back1!!! 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```205206207208Or 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```231232233234## 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```263264265266## 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```