advanced.md
This file
Path
docs/advanced.md
485 lines · 16.0 KiB · Markdown
Last changed by
Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
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!!! note13 Starting from `httpx==0.10.0`, the default and recommended Client class is `AsyncClient`. This should help prevent breaking changes once sync support is reintroduced.1415 A `Client` synonym remains for compatibility with `httpx==0.9.*` releases, but you are encouraged to migrate to `AsyncClient` as soon as possible.1617### Usage1819The 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:2021```python22>>> async with httpx.AsyncClient() as client:23... r = await client.get('https://example.com')24...25>>> r26<Response [200 OK]>27```2829Alternatively, you can explicitly close the connection pool without block-usage using `.aclose()`:3031```python32>>> client = httpx.AsyncClient()33>>> try:34... r = await client.get('https://example.com')35... finally:36... await client.aclose()37...38>>> r39<Response [200 OK]>40```4142Once you have a `Client`, you can use all the features documented in the [Quickstart](/quickstart) guide.4344### Configuration4546Clients allow you to apply configuration to all outgoing requests by passing parameters to the `Client` constructor.4748For example, to apply a set of custom headers on every request:4950```python51>>> url = 'http://httpbin.org/headers'52>>> headers = {'user-agent': 'my-app/0.0.1'}53>>> async with httpx.AsyncClient(headers=headers) as client:54... r = await client.get(url)55...56>>> r.json()['headers']['User-Agent']57'my-app/0.0.1'58```5960!!! note61 When you provide a parameter at both the client and request levels, one of two things can happen:6263 - For headers, query parameters and cookies, the values are merged into one.64 - For all other parameters, the request-level value is used.6566Additionally, `Client` accepts some parameters that aren't available at the request level.6768One particularly useful parameter is `base_url`, which allows you to define a base URL to prepend to all outgoing requests:6970```python71>>> async with httpx.AsyncClient(base_url='http://httpbin.org') as client:72... r = await client.get('/headers')73...74>>> r.request.url75URL('http://httpbin.org/headers')76```7778For a list of all available client-level parameters, see the [`AsyncClient` API reference](/api/#async-client).7980## Calling into Python Web Apps8182You can configure an `httpx` client to call directly into a Python web83application using the ASGI protocol.8485This is particularly useful for two main use-cases:8687* Using `httpx` as a client inside test cases.88* Mocking out external services during tests or in dev/staging environments.8990Let's take this Starlette application as an example:9192```python93from starlette.applications import Starlette94from starlette.responses import HTMLResponse95from starlette.routing import Route969798async def hello():99 return HTMLResponse("Hello World!")100101102app = Starlette(routes=[Route("/", hello)])103```104105We can make requests directly against the application, like so:106107```python108>>> import httpx109>>> async with httpx.AsyncClient(app=app) as client:110... r = client.get('http://example/')111... assert r.status_code == 200112... assert r.text == "Hello World!"113```114115For some more complex cases you might need to customise the ASGI dispatch. This allows you to:116117* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.118* Mount the ASGI application at a subpath by setting `root_path`.119* Use a given client address for requests by setting `client`.120121For example:122123```python124# Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",125# on port 123.126dispatch = httpx.dispatch.ASGIDispatch(app=app, client=("1.2.3.4", 123))127async with httpx.AsyncClient(dispatch=dispatch) as client:128 ...129```130131See [the ASGI documentation](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) for more details on the `client` and `root_path`132keys.133134## Build Request135136You can use `Client.build_request()` to build a request and137make modifications before sending the request.138139```python140>>> async with httpx.AsyncClient() as client:141... req = client.build_request("OPTIONS", "https://example.com")142... req.url.full_path = "*" # Build an 'OPTIONS *' request for CORS143... r = await client.send(req)144...145>>> r146<Response [200 OK]>147```148149## .netrc Support150151HTTPX 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.153154!!! note155 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.158159As default `trust_env` is true. To set false:160```python161>>> await 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```181182When using `Client` instances, `trust_env` should be set on the client itself, rather that on the request methods:183184```python185client = httpx.AsyncClient(trust_env=False)186```187188## Unix Domain Sockets189190You 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.191192Here's an example requesting the Docker Engine API:193194```python195import httpx196197198async with httpx.AsyncClient(uds="/var/run/docker.sock") as client:199 # This request will connect through the socket file.200 resp = await client.get("http://localhost/version")201```202203## HTTP Proxying204205HTTPX supports setting up proxies the same way that Requests does via the `proxies` parameter.206For example to forward all HTTP traffic to `http://127.0.0.1:3080` and all HTTPS traffic207to `http://127.0.0.1:3081` your `proxies` config would look like this:208209```python210>>> proxies = {211... "http": "http://127.0.0.1:3080",212... "https": "http://127.0.0.1:3081"213... }214>>> async with httpx.AsyncClient(proxies=proxies) as client:215... ...216```217218Proxies can be configured for a specific scheme and host, all schemes of a host,219all hosts for a scheme, or for all requests. When determining which proxy configuration220to use for a given request this same order is used.221222```python223>>> proxies = {224... "http://example.com": "...", # Host+Scheme225... "all://example.com": "...", # Host226... "http": "...", # Scheme227... "all": "...", # All228... }229>>> async with httpx.AsyncClient(proxies=proxies) as client:230... ...231...232>>> proxy = "..." # Shortcut for {'all': '...'}233>>> async with httpx.AsyncClient(proxies=proxy) as client:234... ...235```236237!!! warning238 To make sure that proxies cannot read your traffic,239 and even if the proxy_url uses HTTPS, it is recommended to240 use HTTPS and tunnel requests if possible.241242By default `HTTPProxy` will operate as a forwarding proxy for `http://...` requests243and will establish a `CONNECT` TCP tunnel for `https://` requests. This doesn't change244regardless of the `proxy_url` being `http` or `https`.245246Proxies can be configured to have different behavior such as forwarding or tunneling all requests:247248```python249proxy = httpx.HTTPProxy(250 proxy_url="https://127.0.0.1",251 proxy_mode="TUNNEL_ONLY" # May be "TUNNEL_ONLY" or "FORWARD_ONLY". Defaults to "DEFAULT".252)253async with httpx.AsyncClient(proxies=proxy) as client:254 # This request will be tunneled instead of forwarded.255 r = await client.get("http://example.com")256```257258!!! note259260 Per request proxy configuration, i.e. `client.get(url, proxies=...)`,261 has not been implemented yet. To use proxies you must pass the proxy262 information at `Client` initialization.263264## Timeout Configuration265266HTTPX is careful to enforce timeouts everywhere by default.267268The default behavior is to raise a `TimeoutException` after 5 seconds of269network inactivity.270271### Setting and disabling timeouts272273You can set timeouts for an individual request:274275```python276# Using the top-level API:277await httpx.get('http://example.com/api/v1/example', timeout=10.0)278279# Using a client instance:280async with httpx.AsyncClient() as client:281 await client.get("http://example.com/api/v1/example", timeout=10.0)282```283284Or disable timeouts for an individual request:285286```python287# Using the top-level API:288await httpx.get('http://example.com/api/v1/example', timeout=None)289290# Using a client instance:291async with httpx.AsyncClient() as client:292 await client.get("http://example.com/api/v1/example", timeout=None)293```294295### Setting a default timeout on a client296297You can set a timeout on a client instance, which results in the given298`timeout` being used as the default for requests made with this client:299300```python301client = httpx.AsyncClient() # Use a default 5s timeout everywhere.302client = httpx.AsyncClient(timeout=10.0) # Use a default 10s timeout everywhere.303client = httpx.AsyncClient(timeout=None) # Disable all timeouts by default.304```305306### Fine tuning the configuration307308HTTPX also allows you to specify the timeout behavior in more fine grained detail.309310There are four different types of timeouts that may occur. These are **connect**,311**read**, **write**, and **pool** timeouts.312313* The **connect timeout** specifies the maximum amount of time to wait until314a connection to the requested host is established. If HTTPX is unable to connect315within this time frame, a `ConnectTimeout` exception is raised.316* The **read timeout** specifies the maximum duration to wait for a chunk of317data to be received (for example, a chunk of the response body). If HTTPX is318unable to receive data within this time frame, a `ReadTimeout` exception is raised.319* The **write timeout** specifies the maximum duration to wait for a chunk of320data to be sent (for example, a chunk of the request body). If HTTPX is unable321to send data within this time frame, a `WriteTimeout` exception is raised.322* The **pool timeout** specifies the maximum duration to wait for acquiring323a connection from the connection pool. If HTTPX is unable to acquire a connection324within this time frame, a `PoolTimeout` exception is raised. A related325configuration here is the maximum number of allowable connections in the326connection pool, which is configured by the `pool_limits`.327328You can configure the timeout behavior for any of these values...329330```python331# A client with a 60s timeout for connecting, and a 10s timeout elsewhere.332timeout = httpx.Timeout(10.0, connect_timeout=60.0)333client = httpx.AsyncClient(timeout=timeout)334335response = await client.get('http://example.com/')336```337338## Multipart file encoding339340As mentioned in the [quickstart](/quickstart#sending-multipart-file-uploads)341multipart file encoding is available by passing a dictionary with the342name of the payloads as keys and either tuple of elements or a file-like object or a string as values.343344```python345>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}346>>> r = await httpx.post("https://httpbin.org/post", files=files)347>>> print(r.text)348{349 ...350 "files": {351 "upload-file": "<... binary content ...>"352 },353 ...354}355```356357More specifically, if a tuple is used as a value, it must have between 2 and 3 elements:358359- The first element is an optional file name which can be set to `None`.360- The second element may be a file-like object or a string which will be automatically361encoded in UTF-8.362- An optional third element can be used to specify the363[MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_Types)364of the file being uploaded. If not specified HTTPX will attempt to guess the MIME type based365on the file name, with unknown file extensions defaulting to "application/octet-stream".366If the file name is explicitly set to `None` then HTTPX will not include a content-type367MIME header field.368369```python370>>> files = {'upload-file': (None, 'text content', 'text/plain')}371>>> r = await httpx.post("https://httpbin.org/post", files=files)372>>> print(r.text)373{374 ...375 "files": {},376 "form": {377 "upload-file": "text-content"378 },379 ...380}381```382383## SSL certificates384385When 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).386387### Changing the verification defaults388389By 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.390391If you'd like to use a custom CA bundle, you can use the `verify` parameter.392393```python394import httpx395396r = await httpx.get("https://example.org", verify="path/to/client.pem")397```398399You can also disable the SSL verification...400401```python402import httpx403404r = await httpx.get("https://example.org", verify=False)405```406407### SSL configuration on client instances408409If you're using a `Client()` instance, then you should pass any SSL settings when instantiating the client.410411```python412client = httpx.AsyncClient(verify=False)413```414415The `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.416417### Making HTTPS requests to a local server418419When making requests to local servers, such as a development server running on `localhost`, you will typically be using unencrypted HTTP connections.420421If 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:4224231. Use [trustme-cli](https://github.com/sethmlarson/trustme-cli/) to generate a pair of server key/cert files, and a client cert file.4241. 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.)4251. Tell HTTPX to use the certificates stored in `client.pem`:426427```python428>>> import httpx429>>> r = await httpx.get("https://localhost:8000", verify="/tmp/client.pem")430>>> r431Response <200 OK>432```433434## Supported async environments435436HTTPX supports either `asyncio` or `trio` as an async environment.437438By default it will auto-detect which of those two to use as the backend439for socket operations and concurrency primitives.440441You can also explicitly select a backend by instantiating a client with the442`backend` argument...443444```python445client = httpx.AsyncClient(backend='auto') # Autodetection. The default case.446client = httpx.AsyncClient(backend='asyncio') # Use asyncio as the backend.447client = httpx.AsyncClient(backend='trio') # Use trio as the backend.448```449450### [AsyncIO](https://docs.python.org/3/library/asyncio.html)451452AsyncIO is Python's [built-in library](https://docs.python.org/3/library/asyncio.html)453for writing concurrent code with the async/await syntax.454455```python456import asyncio457import httpx458459async def main():460 client = httpx.AsyncClient()461 response = await client.get('https://www.example.com/')462 print(response)463464asyncio.run(main())465```466467### [Trio](https://github.com/python-trio/trio)468469Trio is [an alternative async library](https://trio.readthedocs.io/en/stable/),470designed around the [the principles of structured concurrency](https://en.wikipedia.org/wiki/Structured_concurrency).471472```python473import httpx474import trio475476async def main():477 client = httpx.AsyncClient()478 response = await client.get('https://www.example.com/')479 print(response)480481trio.run(main)482```483484!!! important485 The `trio` package must be installed to use the Trio backend.