advanced.md
This file
Path
docs/advanced.md
548 lines · 18.5 KiB · Markdown
Last changed by
Public Auth API (#732)Tom Christiebefore adoption12dd157
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## Customizing authentication384385When issuing requests or instantiating a client, the `auth` argument can be used to pass an authentication scheme to use. The `auth` argument may be one of the following...386387* A two-tuple of `username`/`password`, to be used with basic authentication.388* An instance of `httpx.BasicAuth()` or `httpx.DigestAuth()`.389* A callable, accepting a request and returning an authenticated request instance.390* A subclass of `httpx.Auth`.391392The most involved of these is the last, which allows you to create authentication flows involving one or more requests. A subclass of `httpx.Auth` should implement `def auth_flow(request)`, and yield any requests that need to be made...393394```python395class MyCustomAuth(httpx.Auth):396 def __init__(self, token):397 self.token = token398399 def auth_flow(self, request):400 # Send the request, with a custom `X-Authentication` header.401 request.headers['X-Authentication'] = self.token402 yield request403```404405If the auth flow requires more that one request, you can issue multiple yields, and obtain the response in each case...406407```python408class MyCustomAuth(httpx.Auth):409 def __init__(self, token):410 self.token = token411412 def auth_flow(self, request):413 response = yield request414 if response.status_code == 401:415 # If the server issues a 401 response then resend the request,416 # with a custom `X-Authentication` header.417 request.headers['X-Authentication'] = self.token418 yield request419```420421Custom authentication classes are designed to not perform any I/O, so that they may be used with both sync and async client instances. If you are implementing an authentication scheme that requires the request body, then you need to indicate this on the class using a `requires_request_body` property.422423You will then be able to access `request.content` inside the `.auth_flow()` method.424425```python426class MyCustomAuth(httpx.Auth):427 requires_request_body = True428429 def __init__(self, token):430 self.token = token431432 def auth_flow(self, request):433 response = yield request434 if response.status_code == 401:435 # If the server issues a 401 response then resend the request,436 # with a custom `X-Authentication` header.437 request.headers['X-Authentication'] = self.sign_request(...)438 yield request439440 def sign_request(self, request):441 # Create a request signature, based on `request.method`, `request.url`,442 # `request.headers`, and `request.content`.443 ...444```445446## SSL certificates447448When 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).449450### Changing the verification defaults451452By 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.453454If you'd like to use a custom CA bundle, you can use the `verify` parameter.455456```python457import httpx458459r = await httpx.get("https://example.org", verify="path/to/client.pem")460```461462You can also disable the SSL verification...463464```python465import httpx466467r = await httpx.get("https://example.org", verify=False)468```469470### SSL configuration on client instances471472If you're using a `Client()` instance, then you should pass any SSL settings when instantiating the client.473474```python475client = httpx.AsyncClient(verify=False)476```477478The `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.479480### Making HTTPS requests to a local server481482When making requests to local servers, such as a development server running on `localhost`, you will typically be using unencrypted HTTP connections.483484If 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:4854861. Use [trustme-cli](https://github.com/sethmlarson/trustme-cli/) to generate a pair of server key/cert files, and a client cert file.4871. 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.)4881. Tell HTTPX to use the certificates stored in `client.pem`:489490```python491>>> import httpx492>>> r = await httpx.get("https://localhost:8000", verify="/tmp/client.pem")493>>> r494Response <200 OK>495```496497## Supported async environments498499HTTPX supports either `asyncio` or `trio` as an async environment.500501By default it will auto-detect which of those two to use as the backend502for socket operations and concurrency primitives.503504You can also explicitly select a backend by instantiating a client with the505`backend` argument...506507```python508client = httpx.AsyncClient(backend='auto') # Autodetection. The default case.509client = httpx.AsyncClient(backend='asyncio') # Use asyncio as the backend.510client = httpx.AsyncClient(backend='trio') # Use trio as the backend.511```512513### [AsyncIO](https://docs.python.org/3/library/asyncio.html)514515AsyncIO is Python's [built-in library](https://docs.python.org/3/library/asyncio.html)516for writing concurrent code with the async/await syntax.517518```python519import asyncio520import httpx521522async def main():523 client = httpx.AsyncClient()524 response = await client.get('https://www.example.com/')525 print(response)526527asyncio.run(main())528```529530### [Trio](https://github.com/python-trio/trio)531532Trio is [an alternative async library](https://trio.readthedocs.io/en/stable/),533designed around the [the principles of structured concurrency](https://en.wikipedia.org/wiki/Structured_concurrency).534535```python536import httpx537import trio538539async def main():540 client = httpx.AsyncClient()541 response = await client.get('https://www.example.com/')542 print(response)543544trio.run(main)545```546547!!! important548 The `trio` package must be installed to use the Trio backend.