Skip to content
Myr

advanced.md

This file

Path

docs/advanced.md

414 lines · 12.9 KiB · Markdown

Last changed by

Add Unix Domain Sockets section to advanced docs page (#542)Jonas Lundbergbefore adoptionf0e6acb

History of this file

Take it

Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970

lines 1–8why, one step back
1# Advanced Usage
23## 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.8

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 9–10why, one step back
9!!! hint
10 A Client instance is equivalent to a Session instance in `requests`.

Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7

line 11why, one step back
11

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 12–15why, one step back
12### Usage
1314The 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:15

Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970

line 16why, one step back
16```python

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 17–26why, one step back
17>>> with httpx.Client() as client:
18... r = client.get('https://example.com')19... 20>>> r21<Response [200 OK]>22```2324Alternatively, you can explicitly close the connection pool without block-usage using `.close()`:2526```python

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 27why, one step back
27>>> client = httpx.Client()

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 28–32why, one step back
28>>> try:
29... r = client.get('https://example.com')30... finally:31... client.close()32...

Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970

lines 33–36why, one step back
33>>> r
34<Response [200 OK]>35```36

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 37–38why, one step back
37Once you have a `Client`, you can use all the features documented in the [Quickstart](/quickstart) guide.
38

Document client-level configuration (#488)Florimond Mancabefore adoptionad38db8

lines 39–74why, one step back
39### Configuration
4041Clients allow you to apply configuration to all outgoing requests by passing parameters to the `Client` constructor.4243For example, to apply a set of custom headers on every request:4445```python46>>> url = 'http://httpbin.org/headers'47>>> headers = {'user-agent': 'my-app/0.0.1'}48>>> with httpx.Client(headers=headers) as client:49... r = client.get(url)50...51>>> r.json()['headers']['User-Agent']52'my-app/0.0.1'53```5455!!! note56 When you provide a parameter at both the client and request levels, one of two things can happen:57 58 - For headers, query parameters and cookies, the values are merged into one.59 - For all other parameters, the request-level value is used.6061Additionally, `Client` constructor accepts some parameters that aren't available at the request level.6263One particularly useful parameter is `base_url`, which allows you to define a base URL to prepend to all outgoing requests:6465```python66>>> with httpx.Client(base_url='http://httpbin.org') as client:67... r = client.get('/headers')68... 69>>> r.request.url70URL('http://httpbin.org/headers')71```7273For a list of all available client-level parameters, see the [`Client` API reference](/api/#client).74

Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970

lines 75–76why, one step back
75## Calling into Python Web Apps
76

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 77why, one step back
77You can configure an `httpx` client to call directly into a Python web

Fix some grammar in Advanced docs (#461)thebigmunchbefore adoption3917866

line 78why, one step back
78application using either the WSGI or ASGI protocol.

Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970

lines 79–81why, one step back
79
80This is particularly useful for two main use-cases:81

Fix some grammar in Advanced docs (#461)thebigmunchbefore adoption3917866

lines 82–83why, one step back
82* Using `httpx` as a client inside test cases.
83* Mocking out external services during tests or in dev/staging environments.

Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970

lines 84–88why, one step back
84
85Here's an example of integrating against a Flask application:8687```python88from flask import Flask

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 89why, one step back
89import httpx

Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970

lines 90–97why, one step back
90
9192app = Flask(__name__)9394@app.route("/")95def hello():96 return "Hello World!"97

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 98–101why, one step back
98with httpx.Client(app=app) as client:
99 r = client.get('http://example/')100 assert r.status_code == 200101 assert r.text == "Hello World!"

Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970

line 102why, one step back
102```

Documented netrc support (#225)Can Sarıgölbefore adoption21939fd

line 103why, one step back
103

Fix some grammar in Advanced docs (#461)thebigmunchbefore adoption3917866

line 104why, one step back
104For some more complex cases you might need to customize the WSGI or ASGI

Drop `raise_app_exceptions` Client argument. (#238)Tom Christiebefore adoptionef9fc0f

lines 105–106why, one step back
105dispatch. This allows you to:
106

Fix some grammar in Advanced docs (#461)thebigmunchbefore adoption3917866

lines 107–109why, one step back
107* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.
108* Mount the WSGI or ASGI application at a subpath by setting `script_name` (WSGI) or `root_path` (ASGI).109* Use a given client address for requests by setting `remote_addr` (WSGI) or `client` (ASGI).

Drop `raise_app_exceptions` Client argument. (#238)Tom Christiebefore adoptionef9fc0f

lines 110–114why, one step back
110
111For example:112113```python114# Instantiate a client that makes WSGI requests with a client IP of "1.2.3.4".

Expose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b

line 115why, one step back
115dispatch = httpx.dispatch.WSGIDispatch(app=app, remote_addr="1.2.3.4")

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 116–117why, one step back
116with httpx.Client(dispatch=dispatch) as client:
117 ...

Drop `raise_app_exceptions` Client argument. (#238)Tom Christiebefore adoptionef9fc0f

lines 118–119why, one step back
118```
119

Add `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac

lines 120–125why, one step back
120## Build Request
121122You can use `Client.build_request()` to build a request and123make modifications before sending the request.124125```python

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 126–131why, one step back
126>>> with httpx.Client() as client:
127... req = client.build_request("OPTIONS", "https://example.com")128... req.url.full_path = "*" # Build an 'OPTIONS *' request for CORS129... r = client.send(req)130...131>>> r

Add `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac

lines 132–134why, one step back
132<Response [200 OK]>
133```134

Fix typos, spelling issues, and grammar in docs (#426)Kyle Galbraithbefore adoptionb65bce5

line 135why, one step back
135## Specify the version of the HTTP protocol

Add example of specifying HTTP versions (#337)Paul (xobb) Chubatyybefore adoption0c4460e

line 136why, one step back
136

Fix typos, spelling issues, and grammar in docs (#426)Kyle Galbraithbefore adoptionb65bce5

line 137why, one step back
137One can set the version of the HTTP protocol for the client in case you want to make the requests using a specific version.

Add example of specifying HTTP versions (#337)Paul (xobb) Chubatyybefore adoption0c4460e

lines 138–141why, one step back
138
139For example:140141```python

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 142–143why, one step back
142with httpx.Client(http_versions=["HTTP/1.1"]) as h11_client:
143 h11_response = h11_client.get("https://myserver.com")

Add example of specifying HTTP versions (#337)Paul (xobb) Chubatyybefore adoption0c4460e

line 144why, one step back
144

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 145–146why, one step back
145with httpx.Client(http_versions=["HTTP/2"]) as h2_client:
146 h2_response = h2_client.get("https://myserver.com")

Add example of specifying HTTP versions (#337)Paul (xobb) Chubatyybefore adoption0c4460e

lines 147–148why, one step back
147```
148

Documented netrc support (#225)Can Sarıgölbefore adoption21939fd

lines 149–153why, one step back
149## .netrc Support
150151HTTPX supports .netrc file. In `trust_env=True` cases, if auth parameter is152not defined, HTTPX tries to add auth into request's header from .netrc file.153

Cache netrc authentication per-client (#400)Can Sarıgölbefore adoption84731c8

lines 154–158why, one step back
154!!! note
155 The NETRC file is cached across requests made by a client.156 If you need to refresh the cache (e.g. because the NETRC file has changed),157 you should create a new client or restart the interpreter.158

Documented netrc support (#225)Can Sarıgölbefore adoption21939fd

lines 159–180why, one step back
159As default `trust_env` is true. To set false:
160```python161>>> httpx.get('https://example.org/', trust_env=False)162```163164If `NETRC` environment is empty, HTTPX tries to use default files.165(`~/.netrc`, `~/_netrc`)166167To change `NETRC` environment:168```python169>>> import os170>>> os.environ["NETRC"] = "my_default_folder/.my_netrc"171```172173.netrc file content example:174```175machine netrcexample.org176login example-username177password example-password178179...180```

Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085

line 181why, one step back
181

Add Unix Domain Sockets section to advanced docs page (#542)Jonas Lundbergbefore adoptionf0e6acb

lines 182–196why, one step back
182## Unix Domain Sockets
183184You can configure an `httpx` client to connect through a unix domain socket via the `uds` parameter. This is useful when making requests to a server that is bound to a socket file rather than an IP address.185186Here's an example requesting the Docker Engine API:187188```python189import httpx190191192with httpx.Client(uds="/var/run/docker.sock") as client:193 # This request will connect through the socket file.194 resp = client.get("http://localhost/version")195```196

Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085

lines 197–203why, one step back
197## HTTP Proxying
198199HTTPX supports setting up proxies the same way that Requests does via the `proxies` parameter.200For example to forward all HTTP traffic to `http://127.0.0.1:3080` and all HTTPS traffic201to `http://127.0.0.1:3081` your `proxies` config would look like this:202203```python

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 204–209why, one step back
204>>> proxies = {
205... "http": "http://127.0.0.1:3080",206... "https": "http://127.0.0.1:3081"207... }208>>> with httpx.Client(proxies=proxies) as client:209... ...

Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085

lines 210–216why, one step back
210```
211212Proxies can be configured for a specific scheme and host, all schemes of a host,213all hosts for a scheme, or for all requests. When determining which proxy configuration214to use for a given request this same order is used.215216```python

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 217–228why, one step back
217>>> proxies = {
218... "http://example.com": "...", # Host+Scheme219... "all://example.com": "...", # Host220... "http": "...", # Scheme221... "all": "...", # All222... }223>>> with httpx.Client(proxies=proxies) as client:224... ...225... 226>>> proxy = "..." # Shortcut for {'all': '...'}227>>> with httpx.Client(proxies=proxy) as client:228... ...

Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085

lines 229–246why, one step back
229```
230231!!! warning232 To make sure that proxies cannot read your traffic,233 and even if the proxy_url uses HTTPS, it is recommended to234 use HTTPS and tunnel requests if possible.235236By default `HTTPProxy` will operate as a forwarding proxy for `http://...` requests237and will establish a `CONNECT` TCP tunnel for `https://` requests. This doesn't change238regardless of the `proxy_url` being `http` or `https`.239240Proxies can be configured to have different behavior such as forwarding or tunneling all requests:241242```python243proxy = httpx.HTTPProxy(244 proxy_url="https://127.0.0.1",245 proxy_mode=httpx.HTTPProxyMode.TUNNEL_ONLY246)

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 247–249why, one step back
247with httpx.Client(proxies=proxy) as client:
248 # This request will be tunneled instead of forwarded.249 r = client.get("http://example.com")

Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085

line 250why, one step back
250```

Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499

line 251why, one step back
251

Drop proxies parameter from the high level API (#485)Yeray Diaz Diazbefore adoption09db6ec

lines 252–256why, one step back
252!!! note
253254 Per request proxy configuration, i.e. `client.get(url, proxies=...)`,255 has not been implemented yet. To use proxies you must pass the proxy256 information at `Client` initialization.

Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499

lines 257–259why, one step back
257
258## Timeout fine-tuning259

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

lines 260–261why, one step back
260HTTPX offers various request timeout management options. Three types of timeouts
261are available: **connect** timeouts, **write** timeouts and **read** timeouts.

Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499

line 262why, one step back
262

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

lines 263–272why, one step back
263* The **connect timeout** specifies the maximum amount of time to wait until
264a connection to the requested host is established. If HTTPX is unable to connect265within this time frame, a `ConnectTimeout` exception is raised.266* The **write timeout** specifies the maximum duration to wait for a chunk of267data to be sent (for example, a chunk of the request body). If HTTPX is unable268to send data within this time frame, a `WriteTimeout` exception is raised.269* The **read timeout** specifies the maximum duration to wait for a chunk of270data to be received (for example, a chunk of the response body). If HTTPX is271unable to receive data within this time frame, a `ReadTimeout` exception is raised.272

Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499

line 273why, one step back
273### Setting timeouts

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

line 274why, one step back
274

Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499

lines 275–283why, one step back
275You can set timeouts on two levels:
276277- For a given request:278279```python280# Using top-level API281httpx.get('http://example.com/api/v1/example', timeout=5)282283# Or, with a client:

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 284–285why, one step back
284with httpx.Client() as client:
285 client.get("http://example.com/api/v1/example", timeout=5)

Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499

lines 286–290why, one step back
286```
287288- On a client instance, which results in the given `timeout` being used as a default for requests made with this client:289290```python

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 291–292why, one step back
291with httpx.Client(timeout=5) as client:
292 client.get('http://example.com/api/v1/example')

Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499

lines 293–296why, one step back
293```
294295Besides, you can pass timeouts in two forms:296

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

line 297why, one step back
297- A number, which sets the read, write and connect timeouts to the same value, as in the examples above.

Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499

lines 298–301why, one step back
298- A `TimeoutConfig` instance, which allows to define the read, write and connect timeouts independently:
299300```python301timeout = httpx.TimeoutConfig(

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

lines 302–303why, one step back
302 connect_timeout=5,
303 read_timeout=10,

Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499

lines 304–310why, one step back
304 write_timeout=15
305)306307resp = httpx.get('http://example.com/api/v1/example', timeout=timeout)308```309310### Default timeouts

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

line 311why, one step back
311

Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499

line 312why, one step back
312By default all types of timeouts are set to 5 second.

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

line 313why, one step back
313

Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499

line 314why, one step back
314### Disabling timeouts

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

lines 315–316why, one step back
315
316To disable timeouts, you can pass `None` as a timeout parameter.

Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499

lines 317–324why, one step back
317Note that currently this is not supported by the top-level API.
318319```python320url = "http://example.com/api/v1/delay/10"321322httpx.get(url, timeout=None) # Times out after 5s323324

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 325–326why, one step back
325with httpx.Client(timeout=None) as client:
326 client.get(url) # Does not timeout, returns after 10s

Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499

lines 327–329why, one step back
327
328329timeout = httpx.TimeoutConfig(

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

lines 330–331why, one step back
330 connect_timeout=5,
331 read_timeout=None,

Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499

lines 332–334why, one step back
332 write_timeout=5
333)334httpx.get(url, timeout=timeout) # Does not timeout, returns after 10s

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

lines 335–378why, one step back
335```
336337## Multipart file encoding338339As mentioned in the [quickstart](/quickstart#sending-multipart-file-uploads)340multipart file encoding is available by passing a dictionary with the341name of the payloads as keys and a tuple of elements as values.342343```python344>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}345>>> r = httpx.post("https://httpbin.org/post", files=files)346>>> print(r.text)347{348 ...349 "files": {350 "upload-file": "<... binary content ...>"351 },352 ...353}354```355356More specifically, this tuple must have at least two elements and maximum of three:357- The first one is an optional file name which can be set to `None`.358- The second may be a file-like object or a string which will be automatically359encoded in UTF-8.360- An optional third element can be included with the361[MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_Types)362of the file being uploaded. If not specified HTTPX will attempt to guess the MIME type363based on the file name specified as the first element or the tuple, if that364is set to `None` or it cannot be inferred from it, HTTPX will default to365`applicaction/octet-stream`.366367```python368>>> files = {'upload-file': (None, 'text content', 'text/plain')}369>>> r = httpx.post("https://httpbin.org/post", files=files)370>>> print(r.text)371{372 ...373 "files": {},374 "form": {375 "upload-file": "text-content"376 },377 ...378}

Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499

line 379why, one step back
379```

Add docs on SSL certificates (#510)Florimond Mancabefore adoption95b2b24

lines 380–414why, one step back
380
381## SSL certificates382383When 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).384385### Default CA bundle386387By 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.388389### Using a custom CA bundle390391If you'd like to use a custom CA bundle, you can use the `verify` parameter that is available on the high-level API as well as clients. For example:392393```python394import httpx395396r = httpx.get("https://example.org", verify="path/to/client.pem")397```398399### Making HTTPS requests to a local server400401When making requests to local servers, such as a development server running on `localhost`, you will typically be using unencrypted HTTP connections.402403If 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:4044051. Use [trustme-cli](https://github.com/sethmlarson/trustme-cli/) to generate a pair of server key/cert files, and a client cert file.4061. 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.)4071. Tell HTTPX to use the certificates stored in `client.pem`:408409```python410>>> import httpx411>>> r = httpx.get("https://localhost:8000", verify="/tmp/client.pem")412>>> r413Response <200 OK>414```