advanced.md
This file
Path
docs/advanced.md
480 lines · 15.6 KiB · Markdown
Last changed by
Tighten up top-level API to only expose public API (#608)Tom Christiebefore adoptiond15dc0b
History of this fileTake it
1# Advanced Usage23## 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.89!!! hint10 A Client instance is equivalent to a Session instance in `requests`.1112### Usage1314The 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:1516```python17>>> async with httpx.Client() as client:18... r = await 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```python27>>> client = httpx.Client()28>>> try:29... r = await client.get('https://example.com')30... finally:31... await client.close()32...33>>> r34<Response [200 OK]>35```3637Once you have a `Client`, you can use all the features documented in the [Quickstart](/quickstart) guide.3839### Configuration4041Clients 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>>> async with httpx.Client(headers=headers) as client:49... r = await 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:5758 - 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>>> async with httpx.Client(base_url='http://httpbin.org') as client:67... r = await 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).7475## Calling into Python Web Apps7677You can configure an `httpx` client to call directly into a Python web78application using the ASGI protocol.7980This is particularly useful for two main use-cases:8182* Using `httpx` as a client inside test cases.83* Mocking out external services during tests or in dev/staging environments.8485Let's take this Starlette application as an example:8687```python88from starlette.applications import Starlette89from starlette.responses import HTMLResponse90from starlette.routing import Route919293async def hello():94 return HTMLResponse("Hello World!")959697app = Starlette(routes=[Route("/", hello)])98```99100We can make requests directly against the application, like so:101102```python103>>> import httpx104>>> async with httpx.Client(app=app) as client:105... r = client.get('http://example/')106... assert r.status_code == 200107... assert r.text == "Hello World!"108```109110For some more complex cases you might need to customise the ASGI dispatch. This allows you to:111112* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.113* Mount the ASGI application at a subpath by setting `root_path`.114* Use a given client address for requests by setting `client`.115116For example:117118```python119# Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",120# on port 123.121dispatch = httpx.dispatch.ASGIDispatch(app=app, client=("1.2.3.4", 123))122async with httpx.Client(dispatch=dispatch) as client:123 ...124```125126See [the ASGI documentation](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) for more details on the `client` and `root_path`127keys.128129## Build Request130131You can use `Client.build_request()` to build a request and132make modifications before sending the request.133134```python135>>> async with httpx.Client() as client:136... req = client.build_request("OPTIONS", "https://example.com")137... req.url.full_path = "*" # Build an 'OPTIONS *' request for CORS138... r = await client.send(req)139...140>>> r141<Response [200 OK]>142```143144## .netrc Support145146HTTPX supports .netrc file. In `trust_env=True` cases, if auth parameter is147not defined, HTTPX tries to add auth into request's header from .netrc file.148149!!! note150 The NETRC file is cached across requests made by a client.151 If you need to refresh the cache (e.g. because the NETRC file has changed),152 you should create a new client or restart the interpreter.153154As default `trust_env` is true. To set false:155```python156>>> await httpx.get('https://example.org/', trust_env=False)157```158159If `NETRC` environment is empty, HTTPX tries to use default files.160(`~/.netrc`, `~/_netrc`)161162To change `NETRC` environment:163```python164>>> import os165>>> os.environ["NETRC"] = "my_default_folder/.my_netrc"166```167168.netrc file content example:169```170machine netrcexample.org171login example-username172password example-password173174...175```176177When using `Client` instances, `trust_env` should be set on the client itself, rather that on the request methods:178179```python180client = httpx.Client(trust_env=False)181```182183## Unix Domain Sockets184185You 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.186187Here's an example requesting the Docker Engine API:188189```python190import httpx191192193async with httpx.Client(uds="/var/run/docker.sock") as client:194 # This request will connect through the socket file.195 resp = await client.get("http://localhost/version")196```197198## HTTP Proxying199200HTTPX supports setting up proxies the same way that Requests does via the `proxies` parameter.201For example to forward all HTTP traffic to `http://127.0.0.1:3080` and all HTTPS traffic202to `http://127.0.0.1:3081` your `proxies` config would look like this:203204```python205>>> proxies = {206... "http": "http://127.0.0.1:3080",207... "https": "http://127.0.0.1:3081"208... }209>>> async with httpx.Client(proxies=proxies) as client:210... ...211```212213Proxies can be configured for a specific scheme and host, all schemes of a host,214all hosts for a scheme, or for all requests. When determining which proxy configuration215to use for a given request this same order is used.216217```python218>>> proxies = {219... "http://example.com": "...", # Host+Scheme220... "all://example.com": "...", # Host221... "http": "...", # Scheme222... "all": "...", # All223... }224>>> async with httpx.Client(proxies=proxies) as client:225... ...226...227>>> proxy = "..." # Shortcut for {'all': '...'}228>>> async with httpx.Client(proxies=proxy) as client:229... ...230```231232!!! warning233 To make sure that proxies cannot read your traffic,234 and even if the proxy_url uses HTTPS, it is recommended to235 use HTTPS and tunnel requests if possible.236237By default `HTTPProxy` will operate as a forwarding proxy for `http://...` requests238and will establish a `CONNECT` TCP tunnel for `https://` requests. This doesn't change239regardless of the `proxy_url` being `http` or `https`.240241Proxies can be configured to have different behavior such as forwarding or tunneling all requests:242243```python244proxy = httpx.HTTPProxy(245 proxy_url="https://127.0.0.1",246 proxy_mode="TUNNEL_ONLY" # May be "TUNNEL_ONLY" or "FORWARD_ONLY". Defaults to "DEFAULT".247)248async with httpx.Client(proxies=proxy) as client:249 # This request will be tunneled instead of forwarded.250 r = await client.get("http://example.com")251```252253!!! note254255 Per request proxy configuration, i.e. `client.get(url, proxies=...)`,256 has not been implemented yet. To use proxies you must pass the proxy257 information at `Client` initialization.258259## Timeout Configuration260261HTTPX is careful to enforce timeouts everywhere by default.262263The default behavior is to raise a `TimeoutException` after 5 seconds of264network inactivity.265266### Setting and disabling timeouts267268You can set timeouts for an individual request:269270```python271# Using the top-level API:272await httpx.get('http://example.com/api/v1/example', timeout=10.0)273274# Using a client instance:275async with httpx.Client() as client:276 await client.get("http://example.com/api/v1/example", timeout=10.0)277```278279Or disable timeouts for an individual request:280281```python282# Using the top-level API:283await httpx.get('http://example.com/api/v1/example', timeout=None)284285# Using a client instance:286async with httpx.Client() as client:287 await client.get("http://example.com/api/v1/example", timeout=None)288```289290### Setting a default timeout on a client291292You can set a timeout on a client instance, which results in the given293`timeout` being used as the default for requests made with this client:294295```python296client = httpx.Client() # Use a default 5s timeout everywhere.297client = httpx.Client(timeout=10.0) # Use a default 10s timeout everywhere.298client = httpx.Client(timeout=None) # Disable all timeouts by default.299```300301### Fine tuning the configuration302303HTTPX also allows you to specify the timeout behavior in more fine grained detail.304305There are four different types of timeouts that may occur. These are **connect**,306**read**, **write**, and **pool** timeouts.307308* The **connect timeout** specifies the maximum amount of time to wait until309a connection to the requested host is established. If HTTPX is unable to connect310within this time frame, a `ConnectTimeout` exception is raised.311* The **read timeout** specifies the maximum duration to wait for a chunk of312data to be received (for example, a chunk of the response body). If HTTPX is313unable to receive data within this time frame, a `ReadTimeout` exception is raised.314* The **write timeout** specifies the maximum duration to wait for a chunk of315data to be sent (for example, a chunk of the request body). If HTTPX is unable316to send data within this time frame, a `WriteTimeout` exception is raised.317* The **pool timeout** specifies the maximum duration to wait for acquiring318a connection from the connection pool. If HTTPX is unable to acquire a connection319within this time frame, a `PoolTimeout` exception is raised. A related320configuration here is the maximum number of allowable connections in the321connection pool, which is configured by the `pool_limits`.322323You can configure the timeout behavior for any of these values...324325```python326# A client with a 60s timeout for connecting, and a 10s timeout elsewhere.327timeout = httpx.Timeout(10.0, connect_timeout=60.0)328client = httpx.Client(timeout=timeout)329330response = await client.get('http://example.com/')331```332333## Multipart file encoding334335As mentioned in the [quickstart](/quickstart#sending-multipart-file-uploads)336multipart file encoding is available by passing a dictionary with the337name of the payloads as keys and either tuple of elements or a file-like object or a string as values.338339```python340>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}341>>> r = await httpx.post("https://httpbin.org/post", files=files)342>>> print(r.text)343{344 ...345 "files": {346 "upload-file": "<... binary content ...>"347 },348 ...349}350```351352More specifically, if a tuple is used as a value, it must have between 2 and 3 elements:353354- The first element is an optional file name which can be set to `None`.355- The second element may be a file-like object or a string which will be automatically356encoded in UTF-8.357- An optional third element can be used to specify the358[MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_Types)359of the file being uploaded. If not specified HTTPX will attempt to guess the MIME type based360on the file name, with unknown file extensions defaulting to "application/octet-stream".361If the file name is explicitly set to `None` then HTTPX will not include a content-type362MIME header field.363364```python365>>> files = {'upload-file': (None, 'text content', 'text/plain')}366>>> r = await httpx.post("https://httpbin.org/post", files=files)367>>> print(r.text)368{369 ...370 "files": {},371 "form": {372 "upload-file": "text-content"373 },374 ...375}376```377378## SSL certificates379380When 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).381382### Changing the verification defaults383384By 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.385386If you'd like to use a custom CA bundle, you can use the `verify` parameter.387388```python389import httpx390391r = await httpx.get("https://example.org", verify="path/to/client.pem")392```393394You can also disable the SSL verification...395396```python397import httpx398399r = await httpx.get("https://example.org", verify=False)400```401402### SSL configuration on client instances403404If you're using a `Client()` instance, then you should pass any SSL settings when instantiating the client.405406```python407client = httpx.Client(verify=False)408```409410The `client.get(...)` method and other request methods *do not* support changing the SSL settings on a per-request basis. If you need different SSL settings in different cases you should use more that one client instance, with different settings on each. Each client will then be using an isolated connection pool with a specific fixed SSL configuration on all connections within that pool.411412### Making HTTPS requests to a local server413414When making requests to local servers, such as a development server running on `localhost`, you will typically be using unencrypted HTTP connections.415416If 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:4174181. Use [trustme-cli](https://github.com/sethmlarson/trustme-cli/) to generate a pair of server key/cert files, and a client cert file.4191. 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.)4201. Tell HTTPX to use the certificates stored in `client.pem`:421422```python423>>> import httpx424>>> r = await httpx.get("https://localhost:8000", verify="/tmp/client.pem")425>>> r426Response <200 OK>427```428429## Supported async environments430431HTTPX supports either `asyncio` or `trio` as an async environment.432433By default it will auto-detect which of those two to use as the backend434for socket operations and concurrency primitives.435436You can also explicitly select a backend by instantiating a client with the437`backend` argument...438439```python440client = httpx.Client(backend='auto') # Autodetection. The default case.441client = httpx.Client(backend='asyncio') # Use asyncio as the backend.442client = httpx.Client(backend='trio') # Use trio as the backend.443```444445### [AsyncIO](https://docs.python.org/3/library/asyncio.html)446447AsyncIO is Python's [built-in library](https://docs.python.org/3/library/asyncio.html)448for writing concurrent code with the async/await syntax.449450```python451import asyncio452import httpx453454async def main():455 client = httpx.Client()456 response = await client.get('https://www.example.com/')457 print(response)458459asyncio.run(main())460```461462### [Trio](https://github.com/python-trio/trio)463464Trio is [an alternative async library](https://trio.readthedocs.io/en/stable/),465designed around the [the principles of structured concurrency](https://en.wikipedia.org/wiki/Structured_concurrency).466467```python468import httpx469import trio470471async def main():472 client = httpx.Client()473 response = await client.get('https://www.example.com/')474 print(response)475476trio.run(main)477```478479!!! important480 The `trio` package must be installed to use the Trio backend.