Skip to content
Myr

advanced.md

This file

Path

docs/advanced.md

399 lines · 12.4 KiB · Markdown

Last changed by

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

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

lines 181–188why, one step back
181
182## HTTP Proxying183184HTTPX supports setting up proxies the same way that Requests does via the `proxies` parameter.185For example to forward all HTTP traffic to `http://127.0.0.1:3080` and all HTTPS traffic186to `http://127.0.0.1:3081` your `proxies` config would look like this:187188```python

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

lines 189–194why, one step back
189>>> proxies = {
190... "http": "http://127.0.0.1:3080",191... "https": "http://127.0.0.1:3081"192... }193>>> with httpx.Client(proxies=proxies) as client:194... ...

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

lines 195–201why, one step back
195```
196197Proxies can be configured for a specific scheme and host, all schemes of a host,198all hosts for a scheme, or for all requests. When determining which proxy configuration199to use for a given request this same order is used.200201```python

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

lines 202–213why, one step back
202>>> proxies = {
203... "http://example.com": "...", # Host+Scheme204... "all://example.com": "...", # Host205... "http": "...", # Scheme206... "all": "...", # All207... }208>>> with httpx.Client(proxies=proxies) as client:209... ...210... 211>>> proxy = "..." # Shortcut for {'all': '...'}212>>> with httpx.Client(proxies=proxy) as client:213... ...

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

lines 214–231why, one step back
214```
215216!!! warning217 To make sure that proxies cannot read your traffic,218 and even if the proxy_url uses HTTPS, it is recommended to219 use HTTPS and tunnel requests if possible.220221By default `HTTPProxy` will operate as a forwarding proxy for `http://...` requests222and will establish a `CONNECT` TCP tunnel for `https://` requests. This doesn't change223regardless of the `proxy_url` being `http` or `https`.224225Proxies can be configured to have different behavior such as forwarding or tunneling all requests:226227```python228proxy = httpx.HTTPProxy(229 proxy_url="https://127.0.0.1",230 proxy_mode=httpx.HTTPProxyMode.TUNNEL_ONLY231)

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

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

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

line 235why, one step back
235```

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

line 236why, one step back
236

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

lines 237–241why, one step back
237!!! note
238239 Per request proxy configuration, i.e. `client.get(url, proxies=...)`,240 has not been implemented yet. To use proxies you must pass the proxy241 information at `Client` initialization.

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

lines 242–244why, one step back
242
243## Timeout fine-tuning244

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

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

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

line 247why, one step back
247

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

lines 248–257why, one step back
248* The **connect timeout** specifies the maximum amount of time to wait until
249a connection to the requested host is established. If HTTPX is unable to connect250within this time frame, a `ConnectTimeout` exception is raised.251* The **write timeout** specifies the maximum duration to wait for a chunk of252data to be sent (for example, a chunk of the request body). If HTTPX is unable253to send data within this time frame, a `WriteTimeout` exception is raised.254* The **read timeout** specifies the maximum duration to wait for a chunk of255data to be received (for example, a chunk of the response body). If HTTPX is256unable to receive data within this time frame, a `ReadTimeout` exception is raised.257

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

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

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

line 259why, one step back
259

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

lines 260–268why, one step back
260You can set timeouts on two levels:
261262- For a given request:263264```python265# Using top-level API266httpx.get('http://example.com/api/v1/example', timeout=5)267268# Or, with a client:

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

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

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

lines 271–275why, one step back
271```
272273- On a client instance, which results in the given `timeout` being used as a default for requests made with this client:274275```python

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

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

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

lines 278–281why, one step back
278```
279280Besides, you can pass timeouts in two forms:281

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

line 282why, one step back
282- 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 283–286why, one step back
283- A `TimeoutConfig` instance, which allows to define the read, write and connect timeouts independently:
284285```python286timeout = httpx.TimeoutConfig(

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

lines 287–288why, one step back
287 connect_timeout=5,
288 read_timeout=10,

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

lines 289–295why, one step back
289 write_timeout=15
290)291292resp = httpx.get('http://example.com/api/v1/example', timeout=timeout)293```294295### Default timeouts

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

line 296why, one step back
296

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

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

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

line 298why, one step back
298

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

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

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

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

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

lines 302–309why, one step back
302Note that currently this is not supported by the top-level API.
303304```python305url = "http://example.com/api/v1/delay/10"306307httpx.get(url, timeout=None) # Times out after 5s308309

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

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

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

lines 312–314why, one step back
312
313314timeout = httpx.TimeoutConfig(

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

lines 315–316why, one step back
315 connect_timeout=5,
316 read_timeout=None,

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

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

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

lines 320–363why, one step back
320```
321322## Multipart file encoding323324As mentioned in the [quickstart](/quickstart#sending-multipart-file-uploads)325multipart file encoding is available by passing a dictionary with the326name of the payloads as keys and a tuple of elements as values.327328```python329>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}330>>> r = httpx.post("https://httpbin.org/post", files=files)331>>> print(r.text)332{333 ...334 "files": {335 "upload-file": "<... binary content ...>"336 },337 ...338}339```340341More specifically, this tuple must have at least two elements and maximum of three:342- The first one is an optional file name which can be set to `None`.343- The second may be a file-like object or a string which will be automatically344encoded in UTF-8.345- An optional third element can be included with the346[MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_Types)347of the file being uploaded. If not specified HTTPX will attempt to guess the MIME type348based on the file name specified as the first element or the tuple, if that349is set to `None` or it cannot be inferred from it, HTTPX will default to350`applicaction/octet-stream`.351352```python353>>> files = {'upload-file': (None, 'text content', 'text/plain')}354>>> r = httpx.post("https://httpbin.org/post", files=files)355>>> print(r.text)356{357 ...358 "files": {},359 "form": {360 "upload-file": "text-content"361 },362 ...363}

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

line 364why, one step back
364```

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

lines 365–399why, one step back
365
366## SSL certificates367368When 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).369370### Default CA bundle371372By 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.373374### Using a custom CA bundle375376If 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:377378```python379import httpx380381r = httpx.get("https://example.org", verify="path/to/client.pem")382```383384### Making HTTPS requests to a local server385386When making requests to local servers, such as a development server running on `localhost`, you will typically be using unencrypted HTTP connections.387388If 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:3893901. Use [trustme-cli](https://github.com/sethmlarson/trustme-cli/) to generate a pair of server key/cert files, and a client cert file.3911. 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.)3921. Tell HTTPX to use the certificates stored in `client.pem`:393394```python395>>> import httpx396>>> r = httpx.get("https://localhost:8000", verify="/tmp/client.pem")397>>> r398Response <200 OK>399```