Skip to content
Myr

Proposed 0.11 docs (#727)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Proposed 0.11 docs * Add async section and link in * Update docs/advanced.md Co-Authored-By: Florimond Manca <florimond.manca@gmail.com> * Update docs/async.md Co-Authored-By: Florimond Manca <florimond.manca@gmail.com> * Update docs/async.md Co-Authored-By: Florimond Manca <florimond.manca@gmail.com> * Update docs/quickstart.md Co-Authored-By: Florimond Manca <florimond.manca@gmail.com> * Update docs/async.md Co-Authored-By: Florimond Manca <florimond.manca@gmail.com> * Update docs/async.md Co-Authored-By: Florimond Manca <florimond.manca@gmail.com> * Update docs/async.md Co-Authored-By: Florimond Manca <florimond.manca@gmail.com> * Docs updates * Use context-managed client instances in examples * Update README with links to docs site, rather than to .md documents * "99% test coverage" * Update docs/async.md Co-Authored-By: Florimond Manca <florimond.manca@gmail.com> * Update docs/async.md Co-Authored-By: Florimond Manca <florimond.manca@gmail.com> * Add Client.close method to API docs * Update docs/async.md Co-Authored-By: Florimond Manca <florimond.manca@gmail.com>

authored by Tom Christie · committed by GitHub · parent eac4b9b · Browse files · 10 files+366 added−262 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Florimond Manca <florimond.manca@gmail.com>

Diff stats

10 files+366 added−262 removed

  • other:+366 added−262 removed

10 files+366 added−262 removed

modified:docs/advanced.md+62 added-142 removed
17 unmodified lines
1819The 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')22>>> with httpx.Client() as client:23... r = 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()`:29Alternatively, you can explicitly close the connection pool without block-usage using `.close()`:3031```python32>>> client = httpx.AsyncClient()32>>> client = httpx.Client()33>>> try:34... r = await client.get('https://example.com')34... r = client.get('https://example.com')35... finally:36... await client.aclose()36... client.close()37...38>>> r39<Response [200 OK]>40```
8 unmodified lines
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)53>>> with httpx.Client(headers=headers) as client:54... r = client.get(url)55...56>>> r.json()['headers']['User-Agent']57'my-app/0.0.1'58```
8 unmodified lines
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')71>>> with httpx.Client(base_url='http://httpbin.org') as client:72... r = 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).78For a list of all available client-level parameters, see the [`Client` API reference](/api/#client).7980## Calling into Python Web Apps8182You can configure an `httpx` client to call directly into a Python web83application using the ASGI protocol.82You can configure an `httpx` client to call directly into a Python web application using the WSGI protocol.8384This is particularly useful for two main use-cases:8586* Using `httpx` as a client inside test cases.87* Mocking out external services during tests or in dev/staging environments.8890Let's take this Starlette application as an example:89Here's an example of integrating against a Flask application:9091```python93from starlette.applications import Starlette94from starlette.responses import HTMLResponse95from starlette.routing import Route92from flask import Flask93import httpx949598async def hello():99 return HTMLResponse("Hello World!")96app = Flask(__name__)9798@app.route("/")99def hello():100 return "Hello World!"101102app = Starlette(routes=[Route("/", hello)])102with httpx.Client(app=app) as client:103 r = client.get('http://example/')104 assert r.status_code == 200105 assert r.text == "Hello World!"106```107105We can make requests directly against the application, like so:108For some more complex cases you might need to customize the WSGI dispatch. This allows you to:109107```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:116110* 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`.111* Mount the WSGI application at a subpath by setting `script_name` (WSGI).112* Use a given client address for requests by setting `remote_addr` (WSGI).113114For example:115116```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:117# Instantiate a client that makes WSGI requests with a client IP of "1.2.3.4".118dispatch = httpx.WSGIDispatch(app=app, remote_addr="1.2.3.4")119with httpx.Client(dispatch=dispatch) as client:120 ...121```122131See [the ASGI documentation](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) for more details on the `client` and `root_path`132keys.133123## Build Request124125You can use `Client.build_request()` to build a request and126make modifications before sending the request.127128```python140>>> async with httpx.AsyncClient() as client:129>>> with httpx.Client() as client:130... req = client.build_request("OPTIONS", "https://example.com")131... req.url.full_path = "*" # Build an 'OPTIONS *' request for CORS143... r = await client.send(req)132... r = client.send(req)133...134>>> r135<Response [200 OK]>136```
9 unmodified lines
146 you should create a new client or restart the interpreter.147148As default `trust_env` is true. To set false:149```python161>>> await httpx.get('https://example.org/', trust_env=False)150>>> httpx.get('https://example.org/', trust_env=False)151```152153If `NETRC` environment is empty, HTTPX tries to use default files.154(`~/.netrc`, `~/_netrc`)
15 unmodified lines
170171When using `Client` instances, `trust_env` should be set on the client itself, rather that on the request methods:172173```python185client = httpx.AsyncClient(trust_env=False)174client = httpx.Client(trust_env=False)175```176188## 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```202177## HTTP Proxying178179HTTPX supports setting up proxies the same way that Requests does via the `proxies` parameter.180For example to forward all HTTP traffic to `http://127.0.0.1:3080` and all HTTPS traffic
3 unmodified lines
184>>> proxies = {185... "http": "http://127.0.0.1:3080",186... "https": "http://127.0.0.1:3081"187... }214>>> async with httpx.AsyncClient(proxies=proxies) as client:188>>> with httpx.Client(proxies=proxies) as client:189... ...190```191192Proxies can be configured for a specific scheme and host, all schemes of a host,
6 unmodified lines
199... "all://example.com": "...", # Host200... "http": "...", # Scheme201... "all": "...", # All202... }229>>> async with httpx.AsyncClient(proxies=proxies) as client:203>>> with httpx.Client(proxies=proxies) as client:204... ...205...206>>> proxy = "..." # Shortcut for {'all': '...'}233>>> async with httpx.AsyncClient(proxies=proxy) as client:207>>> with httpx.Client(proxies=proxy) as client:208... ...209```210211!!! warning212 To make sure that proxies cannot read your traffic,213 and even if the proxy_url uses HTTPS, it is recommended to214 use HTTPS and tunnel requests if possible.215242By default `HTTPProxy` will operate as a forwarding proxy for `http://...` requests216By default `httpx.Proxy` will operate as a forwarding proxy for `http://...` requests217and will establish a `CONNECT` TCP tunnel for `https://` requests. This doesn't change244regardless of the `proxy_url` being `http` or `https`.218regardless of the proxy `url` being `http` or `https`.219220Proxies can be configured to have different behavior such as forwarding or tunneling all requests:221222```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".223proxy = httpx.Proxy(224 url="https://127.0.0.1",225 mode="TUNNEL_ONLY" # May be "TUNNEL_ONLY" or "FORWARD_ONLY". Defaults to "DEFAULT".226)253async with httpx.AsyncClient(proxies=proxy) as client:227with httpx.Client(proxies=proxy) as client:228 # This request will be tunneled instead of forwarded.255 r = await client.get("http://example.com")229 r = client.get("http://example.com")230```231232!!! note233260 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.234 To use proxies you must pass the proxy information at `Client` initialization,235 rather than on the `.get(...)` call or other request methods.236237## Timeout Configuration238239HTTPX is careful to enforce timeouts everywhere by default.
6 unmodified lines
246You can set timeouts for an individual request:247248```python249# Using the top-level API:277await httpx.get('http://example.com/api/v1/example', timeout=10.0)250httpx.get('http://example.com/api/v1/example', timeout=10.0)251252# Using a client instance:280async with httpx.AsyncClient() as client:281 await client.get("http://example.com/api/v1/example", timeout=10.0)253with httpx.Client() as client:254 client.get("http://example.com/api/v1/example", timeout=10.0)255```256257Or disable timeouts for an individual request:258259```python260# Using the top-level API:288await httpx.get('http://example.com/api/v1/example', timeout=None)261httpx.get('http://example.com/api/v1/example', timeout=None)262263# Using a client instance:291async with httpx.AsyncClient() as client:292 await client.get("http://example.com/api/v1/example", timeout=None)264with httpx.Client() as client:265 client.get("http://example.com/api/v1/example", timeout=None)266```267268### Setting a default timeout on a client269270You can set a timeout on a client instance, which results in the given271`timeout` being used as the default for requests made with this client:272273```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.274client = httpx.Client() # Use a default 5s timeout everywhere.275client = httpx.Client(timeout=10.0) # Use a default 10s timeout everywhere.276client = httpx.Client(timeout=None) # Disable all timeouts by default.277```278279### Fine tuning the configuration280
21 unmodified lines
302303```python304# A client with a 60s timeout for connecting, and a 10s timeout elsewhere.305timeout = httpx.Timeout(10.0, connect_timeout=60.0)333client = httpx.AsyncClient(timeout=timeout)306client = httpx.Client(timeout=timeout)307335response = await client.get('http://example.com/')308response = client.get('http://example.com/')309```310311## Multipart file encoding312
2 unmodified lines
315name of the payloads as keys and either tuple of elements or a file-like object or a string as values.316317```python318>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}346>>> r = await httpx.post("https://httpbin.org/post", files=files)319>>> r = httpx.post("https://httpbin.org/post", files=files)320>>> print(r.text)321{322 ...323 "files": {
16 unmodified lines
340MIME header field.341342```python343>>> files = {'upload-file': (None, 'text content', 'text/plain')}371>>> r = await httpx.post("https://httpbin.org/post", files=files)344>>> r = httpx.post("https://httpbin.org/post", files=files)345>>> print(r.text)346{347 ...348 "files": {},
79 unmodified lines
428429```python430import httpx431459r = await httpx.get("https://example.org", verify="path/to/client.pem")432r = httpx.get("https://example.org", verify="path/to/client.pem")433```434435You can also disable the SSL verification...436437```python438import httpx439467r = await httpx.get("https://example.org", verify=False)440r = httpx.get("https://example.org", verify=False)441```442443### SSL configuration on client instances444445If you're using a `Client()` instance, then you should pass any SSL settings when instantiating the client.446447```python475client = httpx.AsyncClient(verify=False)448client = httpx.Client(verify=False)449```450451The `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.452
8 unmodified lines
4611. Tell HTTPX to use the certificates stored in `client.pem`:462463```python464>>> import httpx492>>> r = await httpx.get("https://localhost:8000", verify="/tmp/client.pem")465>>> r = httpx.get("https://localhost:8000", verify="/tmp/client.pem")466>>> r467Response <200 OK>468```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.
modified:docs/api.md+12 added-5 removed
added:docs/async.md+210 added
1# Async Support23HTTPX offers a standard synchronous API by default, but also gives you4the option of an async client if you need it.56Async is a concurrency model that is far more efficient than multi-threading,7and can provide significant performance benefits and enable the use of8long-lived network connections such as WebSockets.910If you're working with an async web framework then you'll also want to use an11async client for sending outgoing HTTP requests.1213## Making Async requests1415To make asynchronous requests, you'll need an `AsyncClient`.1617```python18>>> async with httpx.AsyncClient() as client:19>>> r = await client.get('https://www.example.com/')20>>> r21<Response [200 OK]>22```2324!!! tip25 Use [IPython](https://ipython.readthedocs.io/en/stable/) or Python 3.8+ with `python -m asyncio` to try this code interactively, as they support executing `async`/`await` expressions in the console.2627## API Differences2829If you're using an async client then there are a few bits of API that30use async methods.3132### Making requests3334The request methods are all async, so you should use `response = await client.get(...)` style for all of the following:3536* `AsyncClient.get(url, ...)`37* `AsyncClient.options(url, ...)`38* `AsyncClient.head(url, ...)`39* `AsyncClient.post(url, ...)`40* `AsyncClient.put(url, ...)`41* `AsyncClient.patch(url, ...)`42* `AsyncClient.delete(url, ...)`43* `AsyncClient.request(method, url, ...)`44* `AsyncClient.send(request, ...)`4546### Opening and closing clients4748Use `async with httpx.AsyncClient()` if you want a context-managed client...4950```python51async with httpx.AsyncClient() as client:52 ...53```5455Alternatively, use `await client.aclose()` if you want to close a client explicitly:5657```python58client = httpx.AsyncClient()59...60await client.aclose()61```6263### Streaming responses6465The `AsyncClient.stream(method, url, ...)` method is an async context block.6667```python68>>> client = httpx.AsyncClient()69>>> async with client.stream('GET', 'https://www.example.com/') as response:70>>> async for chunk in r.aiter_content():71>>> ...72```7374The async response streaming methods are:7576* `Response.aread()` - For conditionally reading a response inside a stream block.77* `Response.aiter_content()` - For streaming the response content as bytes.78* `Response.aiter_text()` - For streaming the response content as text.79* `Response.aiter_lines()` - For streaming the response content as lines of text.80* `Response.aiter_raw()` - For streaming the raw response bytes, without applying content decoding.81* `Response.aclose()` - For closing the response. You don't usually need this, since `.stream` block close the response automatically on exit.8283### Streaming requests8485When sending a streaming request body with an `AsyncClient` instance, you should use an async butes generator instead of a bytes generator:8687```python88async def upload_bytes():89 ... # yield byte content9091await client.post(url, data=upload_bytes())92```9394## Supported async environments9596HTTPX supports either `asyncio` or `trio` as an async environment.9798By default it will auto-detect which of those two to use as the backend99for socket operations and concurrency primitives.100101You can also explicitly select a backend by instantiating a client with the102`backend` argument...103104```python105client = httpx.AsyncClient(backend='auto') # Autodetection. The default case.106client = httpx.AsyncClient(backend='asyncio') # Use asyncio as the backend.107client = httpx.AsyncClient(backend='trio') # Use trio as the backend.108```109110### [AsyncIO](https://docs.python.org/3/library/asyncio.html)111112AsyncIO is Python's [built-in library](https://docs.python.org/3/library/asyncio.html)113for writing concurrent code with the async/await syntax.114115```python116import asyncio117import httpx118119async def main():120 async with httpx.AsyncClient() as client:121 response = await client.get('https://www.example.com/')122 print(response)123124asyncio.run(main())125```126127### [Trio](https://github.com/python-trio/trio)128129Trio is [an alternative async library](https://trio.readthedocs.io/en/stable/),130designed around the [the principles of structured concurrency](https://en.wikipedia.org/wiki/Structured_concurrency).131132```python133import httpx134import trio135136async def main():137 async with httpx.AsyncClient() as client:138 response = await client.get('https://www.example.com/')139 print(response)140141trio.run(main)142```143144!!! important145 The `trio` package must be installed to use the Trio backend.146147## Calling into Python Web Apps148149Just as `httpx.Client` allows you to call directly into WSGI web applications,150the `httpx.AsyncClient` class allows you to call directly into ASGI web applications.151152Let's take this Starlette application as an example:153154```python155from starlette.applications import Starlette156from starlette.responses import HTMLResponse157from starlette.routing import Route158159160async def hello():161 return HTMLResponse("Hello World!")162163164app = Starlette(routes=[Route("/", hello)])165```166167We can make requests directly against the application, like so:168169```python170>>> import httpx171>>> async with httpx.AsyncClient(app=app) as client:172... r = await client.get('http://example/')173... assert r.status_code == 200174... assert r.text == "Hello World!"175```176177For some more complex cases you might need to customise the ASGI dispatch. This allows you to:178179* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.180* Mount the ASGI application at a subpath by setting `root_path`.181* Use a given client address for requests by setting `client`.182183For example:184185```python186# Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",187# on port 123.188dispatch = httpx.ASGIDispatch(app=app, client=("1.2.3.4", 123))189async with httpx.AsyncClient(dispatch=dispatch) as client:190 ...191```192193See [the ASGI documentation](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) for more details on the `client` and `root_path` keys.194195## Unix Domain Sockets196197The async client provides support for connecting 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.198199Here's an example requesting the Docker Engine API:200201```python202import httpx203204205async with httpx.AsyncClient(uds="/var/run/docker.sock") as client:206 # This request will connect through the socket file.207 resp = await client.get("http://localhost/version")208```209210This functionality is not currently available in the synchronous client.
modified:docs/compatibility.md+8 added-8 removed
20 unmodified lines
2122For example:2324```python25async with request.stream("GET", "https://www.example.com") as response:25with request.stream("GET", "https://www.example.com") as response:26 ...27```2829Within a `stream()` block request data is made available with:3031* `.aiter_bytes()` - Instead of `response.iter_content()`32* `.aiter_text()` - Instead of `response.iter_content(decode_unicode=True)`33* `.aiter_lines()` - Instead of `response.iter_lines()`34* `.aiter_raw()` - Use this instead of `response.raw`35* `.aread()` - Read the entire response body, making `request.text` and `response.content` available.31* `.iter_bytes()` - Instead of `response.iter_content()`32* `.iter_text()` - Instead of `response.iter_content(decode_unicode=True)`33* `.iter_lines()` - Corresponding to `response.iter_lines()`34* `.iter_raw()` - Use this instead of `response.raw`35* `.read()` - Read the entire response body, making `request.text` and `response.content` available.3637## SSL configuration3839When using a `Client` instance, the `trust_env`, `verify`, and `cert` arguments should always be passed on client instantiation, rather than passed to the request method.
11 unmodified lines
51We don't support `response.is_ok` since the naming is ambiguous there, and might incorrectly imply an equivalence to `response.status_code == codes.OK`. Instead we provide the `response.is_error` property. Use `if not response.is_error:` instead of `if response.is_ok:`.5253## Client instances5455The HTTPX equivalent of `requests.Session` is `httpx.AsyncClient`.55The HTTPX equivalent of `requests.Session` is `httpx.Client`.5657```python58session = requests.Session(**kwargs)59```6061is generally equivalent to6263```python64client = httpx.AsyncClient(**kwargs)64client = httpx.Client(**kwargs)65```6667## Mocking68
1 unmodified line
modified:docs/environment_variables.md+2 added-2 removed
2 unmodified lines
34The HTTPX library can be configured via environment variables.5Environment variables are used by default. To ignore environment variables, `trust_env` has to be set `False`. There are two ways to set `trust_env` to disable environment variables:67* On the client via `httpx.AsyncClient(trust_env=False)`.7* On the client via `httpx.Client(trust_env=False)`.8* Using the top-level API, such as `httpx.get("<url>", trust_env=False)`.910Here is a list of environment variables that HTTPX recognizes and what function they serve:11
11 unmodified lines
23```python24# test_script.py25import httpx2627with httpx.AsyncClient() as client:27with httpx.Client() as client:28 r = client.get("https://google.com")29```3031Debug output:
123 unmodified lines
modified:docs/http2.md+5 added-5 removed
16 unmodified lines
17For a comprehensive guide to HTTP/2 you may want to check out "[HTTP2 Explained](https://http2-explained.haxx.se/content/en/)".1819## Enabling HTTP/22021The HTTPX client provides provisional HTTP/2 support.21The HTTPX client provides HTTP/2 support, **which is currently only available with the async client**.2223HTTP/2 support is not enabled by default, because HTTP/1.1 is a mature,24battle-hardened transport layer. With HTTP/2 being newer and significantly more25complex, our implementation should be considered a less robust option at this26point in time.24battle-hardened transport layer, and our HTTP/1.1 may be considered the more robust25option at this point in time. It is possible that a future version of `httpx` may26enable HTTP/2 support by default.2728However, if you're issuing highly concurrent requests you might want to consider28If you're issuing highly concurrent requests you might want to consider29trying out our HTTP/2 support. You can do so by instantiating a client with30HTTP/2 support enabled:3132```python
28 unmodified lines
modified:docs/index.md+14 added-26 removed
22 unmodified lines
2324<em>A next-generation HTTP client for Python.</em>25</div>2627HTTPX is an asynchronous client library that supports HTTP/1.1 and HTTP/2.27HTTPX is a fully featured HTTP client for Python 3, which provides sync and async APIs, and support for both HTTP/1.1 and HTTP/2.2829It can be used in high-performance async web frameworks, using either asyncio30or trio, and is able to support making large numbers of concurrent requests.2930!!! note33 HTTPX should currently be considered in alpha. We'd love early users and feedback,34 but would strongly recommend pinning your dependencies to the latest median35 release, so that you're able to properly review API changes between package36 updates. Currently you should be using `httpx==0.10.*`.31 HTTPX should currently be considered in beta.3238 In particular, the 0.8 release switched HTTPX into focusing exclusively on39 providing an async client, in order to move the project forward, and help40 us [change our approach to providing sync+async support][sync-support]. If41 you have been using the sync client, you may want to pin to `httpx==0.7.*`,42 and wait until our sync client is reintroduced.33 We believe we've got the public API to a stable point now, but would strongly recommend pinning your dependencies to the `0.11.*` release, so that you're able to properly review API changes between package updates.3435 A 1.0 release is expected to be issued sometime on or before April 2020.3637---3839Let's get started...4048The standard Python REPL does not allow top-level async statements.4950To run these async examples you'll probably want to either use `ipython`,51or use Python 3.8 with `python -m asyncio`.5241```python42>>> import httpx55>>> r = await httpx.get('https://www.example.org/')43>>> r = httpx.get('https://www.example.org/')44>>> r45<Response [200 OK]>46>>> r.status_code4720060>>> r.http_version61'HTTP/1.1'48>>> r.headers['content-type']49'text/html; charset=UTF-8'50>>> r.text51'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'
3 unmodified lines
5556HTTPX is a high performance asynchronous HTTP client, that builds on the57well-established usability of `requests`, and gives you:5873* A broadly requests-compatible API.74* HTTP/1.1 and [HTTP/2 support](http2.md).75* Ability to [make requests directly to ASGI applications](advanced.md#calling-into-python-web-apps).59* A requests-compatible API wherever possible.60* Standard synchronous interface, but with [async support if you need it](async.md).61* HTTP/1.1 [and HTTP/2 support](http2.md).62* Ability to make requests directly to [WSGI applications](https://www.encode.io/httpx/advanced/#calling-into-python-web-apps) or [ASGI applications](https://www.encode.io/httpx/async/#calling-into-python-web-apps).63* Strict timeouts everywhere.64* Fully type annotated.78* 100% test coverage.65* 99% test coverage.6667Plus all the standard features of `requests`...6869* International Domains and URLs
16 unmodified lines
8687For a run-through of all the basics, head over to the [QuickStart](quickstart.md).8889For more advanced topics, see the [Advanced Usage](advanced.md) section,103or the [HTTP/2](http2.md) section.90the [async support](async.md) section, or the [HTTP/2](http2.md) section.9192The [Developer Interface](api.md) provides a comprehensive API reference.9394## Dependencies9596The HTTPX project relies on these excellent libraries:97111* `h2` - HTTP/2 support.98* `urllib3` - Sync client support.99* `h11` - HTTP/1.1 support.100* `h2` - HTTP/2 support.101* `certifi` - SSL certificates.102* `chardet` - Fallback auto-detection for response encoding.103* `hstspreload` - determines whether IDNA-encoded host should be only accessed via HTTPS.104* `idna` - Internationalized domain name support.
18 unmodified lines
modified:docs/quickstart.md+39 added-45 removed
1# QuickStart23!!! note4 The standard Python REPL does not allow top-level async statements.56 To run async examples directly you'll probably want to either use `ipython`,7 or use Python 3.8 with `python -m asyncio`.83First, start by importing HTTPX:45```python6>>> import httpx
1 unmodified line
89Now, let’s try to get a webpage.1011```python18>>> r = await httpx.get('https://httpbin.org/get')12>>> r = httpx.get('https://httpbin.org/get')13>>> r14<Response [200 OK]>15```1617Similarly, to make an HTTP POST request:1819```python26>>> r = await httpx.post('https://httpbin.org/post', data={'key': 'value'})20>>> r = httpx.post('https://httpbin.org/post', data={'key': 'value'})21```2223The PUT, DELETE, HEAD, and OPTIONS requests all follow the same style:2425```python32>>> r = await httpx.put('https://httpbin.org/put', data={'key': 'value'})33>>> r = await httpx.delete('https://httpbin.org/delete')34>>> r = await httpx.head('https://httpbin.org/get')35>>> r = await httpx.options('https://httpbin.org/get')26>>> r = httpx.put('https://httpbin.org/put', data={'key': 'value'})27>>> r = httpx.delete('https://httpbin.org/delete')28>>> r = httpx.head('https://httpbin.org/get')29>>> r = httpx.options('https://httpbin.org/get')30```3132## Passing Parameters in URLs3334To include URL query parameters in the request, use the `params` keyword:3536```python37>>> params = {'key1': 'value1', 'key2': 'value2'}44>>> r = await httpx.get('https://httpbin.org/get', params=params)38>>> r = httpx.get('https://httpbin.org/get', params=params)39```4041To see how the values get encoding into the URL string, we can inspect the42resulting URL that was used to make the request:
6 unmodified lines
49You can also pass a list of items as a value:5051```python52>>> params = {'key1': 'value1', 'key2': ['value2', 'value3']}59>>> r = await httpx.get('https://httpbin.org/get', params=params)53>>> r = httpx.get('https://httpbin.org/get', params=params)54>>> r.url55URL('https://httpbin.org/get?key1=value1&key2=value2&key2=value3')56```57
1 unmodified line
5960HTTPX will automatically handle decoding the response content into Unicode text.6162```python69>>> r = await httpx.get('https://www.example.org/')63>>> r = httpx.get('https://www.example.org/')64>>> r.text65'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'66```67
36 unmodified lines
104105Often Web API responses will be encoded as JSON.106107```python114>>> r = await httpx.get('https://api.github.com/events')108>>> r = httpx.get('https://api.github.com/events')109>>> r.json()110[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...' ... }}]111```112
3 unmodified lines
116117```python118>>> url = 'http://httpbin.org/headers'119>>> headers = {'user-agent': 'my-app/0.0.1'}126>>> r = await httpx.get(url, headers=headers)120>>> r = httpx.get(url, headers=headers)121```122123## Sending Form Encoded Data124
2 unmodified lines
127which is used for HTML forms.128129```python130>>> data = {'key1': 'value1', 'key2': 'value2'}137>>> r = await httpx.post("https://httpbin.org/post", data=data)131>>> r = httpx.post("https://httpbin.org/post", data=data)132>>> print(r.text)133{134 ...135 "form": {
7 unmodified lines
143Form encoded data can also include multiple values form a given key.144145```python146>>> data = {'key1': ['value1', 'value2']}153>>> r = await httpx.post("https://httpbin.org/post", data=data)147>>> r = httpx.post("https://httpbin.org/post", data=data)148>>> print(r.text)149{150 ...151 "form": {
11 unmodified lines
163You can also upload files, using HTTP multipart encoding:164165```python166>>> files = {'upload-file': open('report.xls', 'rb')}173>>> r = await httpx.post("https://httpbin.org/post", files=files)167>>> r = httpx.post("https://httpbin.org/post", files=files)168>>> print(r.text)169{170 ...171 "files": {
7 unmodified lines
179of items for the file value:180181```python182>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}189>>> r = await httpx.post("https://httpbin.org/post", files=files)183>>> r = httpx.post("https://httpbin.org/post", files=files)184>>> print(r.text)185{186 ...187 "files": {
9 unmodified lines
197For more complicated data structures you'll often want to use JSON encoding instead.198199```python200>>> data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']}207>>> r = await httpx.post("https://httpbin.org/post", json=data)201>>> r = httpx.post("https://httpbin.org/post", json=data)202>>> print(r.text)203{204 ...205 "json": {
21 unmodified lines
227228We can inspect the HTTP status code of the response:229230```python237>>> r = await httpx.get('https://httpbin.org/get')231>>> r = httpx.get('https://httpbin.org/get')232>>> r.status_code233200234```235
6 unmodified lines
242243We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):244245```python252>>> not_found = await httpx.get('https://httpbin.org/status/404')246>>> not_found = httpx.get('https://httpbin.org/status/404')247>>> not_found.status_code248404249>>> not_found.raise_for_status()250Traceback (most recent call last):
45 unmodified lines
296297You can stream the binary content of the response...298299```306>>> async with httpx.stream("GET", "https://www.example.com") as r:307... async for data in r.aiter_bytes():300>>> with httpx.stream("GET", "https://www.example.com") as r:301... for data in r.iter_bytes():302... print(data)303```304305Or the text of the response...306307```314>>> async with httpx.stream("GET", "https://www.example.com") as r:315... async for text in r.aiter_text():308>>> with httpx.stream("GET", "https://www.example.com") as r:309... for text in r.iter_text():310... print(text)311```312313Or stream the text, on a line-by-line basis...314315```322>>> async with httpx.stream("GET", "https://www.example.com") as r:323... async for line in r.aiter_lines():316>>> with httpx.stream("GET", "https://www.example.com") as r:317... for line in r.iter_lines():318... print(line)319```320321HTTPX will use universal line endings, normalising all cases to `\n`.322323In some cases you might want to access the raw bytes on the response without applying any HTTP content decoding. In this case any content encoding that the web server has applied such as `gzip`, `deflate`, or `brotli` will not be automatically decoded.324325```332>>> async with httpx.stream("GET", "https://www.example.com") as r:333... async for chunk in r.aiter_raw():326>>> with httpx.stream("GET", "https://www.example.com") as r:327... for chunk in r.iter_raw():328... print(chunk)329```330331If you're using streaming responses in any of these ways then the `response.content` and `response.text` attributes will not be available, and will raise errors if accessed. However you can also use the response streaming functionality to conditionally load the response body:332339```340>>> async with httpx.stream("GET", "https://www.example.com") as r:333```python334>>> with httpx.stream("GET", "https://www.example.com") as r:335... if r.headers['Content-Length'] < TOO_LONG:342... await r.aread()336... r.read()337... print(r.text)338```339340## Cookies341342Any cookies that are set on the response can be easily accessed:343344```python351>>> r = await httpx.get('http://httpbin.org/cookies/set?chocolate=chip', allow_redirects=False)345>>> r = httpx.get('http://httpbin.org/cookies/set?chocolate=chip', allow_redirects=False)346>>> r.cookies['chocolate']347'chip'348```349350To include cookies in an outgoing request, use the `cookies` parameter:351352```python353>>> cookies = {"peanut": "butter"}360>>> r = await httpx.get('http://httpbin.org/cookies', cookies=cookies)354>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)355>>> r.json()356{'cookies': {'peanut': 'butter'}}357```358
3 unmodified lines
362```python363>>> cookies = httpx.Cookies()364>>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')365>>> cookies.set('cookie_off_domain', 'nope.', domain='example.org')372>>> r = await httpx.get('http://httpbin.org/cookies', cookies=cookies)366>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)367>>> r.json()368{'cookies': {'cookie_on_domain': 'hello, there!'}}369```370
7 unmodified lines
378379For example, GitHub redirects all HTTP requests to HTTPS.380381```python388>>> r = await httpx.get('http://github.com/')382>>> r = httpx.get('http://github.com/')383>>> r.url384URL('https://github.com/')385>>> r.status_code386200
3 unmodified lines
390391You can modify the default redirection handling with the allow_redirects parameter:392393```python400>>> r = await httpx.get('http://github.com/', allow_redirects=False)394>>> r = httpx.get('http://github.com/', allow_redirects=False)395>>> r.status_code396301397>>> r.history398[]
1 unmodified line
400401If you’re making a `HEAD` request, you can use this to enable redirection:402403```python410>>> r = await httpx.head('http://github.com/', allow_redirects=True)404>>> r = httpx.head('http://github.com/', allow_redirects=True)405>>> r.url406'https://github.com/'407>>> r.history408[<Response [301 Moved Permanently]>]
8 unmodified lines
417The default timeout for network inactivity is five seconds. You can modify the418value to be more or less strict:419420```python427>>> await httpx.get('https://github.com/', timeout=0.001)421>>> httpx.get('https://github.com/', timeout=0.001)422```423424You can also disable the timeout behavior completely...425426```python433>>> await httpx.get('https://github.com/', timeout=None)427>>> httpx.get('https://github.com/', timeout=None)428```429430For advanced timeout management, see [Timeout fine-tuning](https://www.encode.io/httpx/advanced/#fine-tuning-the-configuration).431
5 unmodified lines
437plaintext `str` or `bytes` objects as the `auth` argument to the request438functions:439440```python447>>> await httpx.get("https://example.com", auth=("my_user", "password123"))441>>> httpx.get("https://example.com", auth=("my_user", "password123"))442```443444To provide credentials for Digest authentication you'll need to instantiate445a `DigestAuth` object with the plaintext username and password as arguments.
1 unmodified line
447as above:448449```python450>>> auth = httpx.DigestAuth("my_user", "password123")457>>> await httpx.get("https://example.com", auth=auth)451>>> httpx.get("https://example.com", auth=auth)452<Response [200 OK]>453```
modified:mkdocs.yml+1 added
modified:README.md+13 added-29 removed
14 unmodified lines
15 <img src="https://badge.fury.io/py/httpx.svg" alt="Package version">16</a>17</p>1819HTTPX is an asynchronous HTTP client, that supports HTTP/2 and HTTP/1.1.19HTTPX is a fully featured HTTP client for Python 3, which provides sync and async APIs, and support for both HTTP/1.1 and HTTP/2.2021It can be used in high-performance async web frameworks, using either asyncio22or trio, and is able to support making large numbers of requests concurrently.21**Note**: _HTTPX should be considered in beta. We believe we've got the public API to22a stable point now, but would strongly recommend pinning your dependencies to the `0.11.*`23release, so that you're able to properly review API changes between package updates.24A 1.0 release is expected to be issued sometime on or before April 2020._2524**Note**: *HTTPX should still be considered in alpha. We'd love early users and feedback,25but would strongly recommend pinning your dependencies to the latest median26release, so that you're able to properly review API changes between package27updates. Currently you should be using `httpx==0.10.*`.*2829*In particular, the 0.8 release switched HTTPX into focusing exclusively on30providing an async client, in order to move the project forward, and help31us [change our approach to providing sync+async support][sync-support]. If32you have been using the sync client, you may want to pin to `httpx==0.7.*`,33and wait until our sync client is reintroduced.*3426---2728Let's get started...2939*The standard Python REPL does not allow top-level async statements.*4041*To run async examples directly you'll probably want to either use `ipython`,42or use Python 3.8 with `python -m asyncio`.*4330```python31>>> import httpx46>>> r = await httpx.get('https://www.example.org/')32>>> r = httpx.get('https://www.example.org/')33>>> r34<Response [200 OK]>35>>> r.status_code3620051>>> r.http_version52'HTTP/1.1'37>>> r.headers['content-type']38'text/html; charset=UTF-8'39>>> r.text40'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'
3 unmodified lines
4445HTTPX builds on the well-established usability of `requests`, and gives you:4647* A requests-compatible API wherever possible.64* HTTP/2 and HTTP/1.1 support.65* Ability to [make requests directly to ASGI applications](https://www.encode.io/httpx/advanced/#calling-into-python-web-apps).48* Standard synchronous interface, but with [async support if you need it](https://www.encode.io/httpx/async/).49* HTTP/1.1 [and HTTP/2 support](https://www.encode.io/httpx/http2/).50* Ability to make requests directly to [WSGI applications](https://www.encode.io/httpx/advanced/#calling-into-python-web-apps) or [ASGI applications](https://www.encode.io/httpx/async/#calling-into-python-web-apps).51* Strict timeouts everywhere.52* Fully type annotated.68* 100% test coverage.53* 99% test coverage.5455Plus all the standard features of `requests`...5657* International Domains and URLs
27 unmodified lines
85Project documentation is available at [www.encode.io/httpx/](https://www.encode.io/httpx/).8687For a run-through of all the basics, head over to the [QuickStart](https://www.encode.io/httpx/quickstart/).88104For more advanced topics, see the [Advanced Usage](https://www.encode.io/httpx/advanced/) section.89For more advanced topics, see the [Advanced Usage](https://www.encode.io/httpx/advanced/) section, the [async support](https://www.encode.io/httpx/async/) section, or the [HTTP/2](https://www.encode.io/httpx/http2/) section.9091The [Developer Interface](https://www.encode.io/httpx/api/) provides a comprehensive API reference.9293## Contribute
3 unmodified lines
97## Dependencies9899The httpx project relies on these excellent libraries:100116* `h2` - HTTP/2 support.101* `urllib3` - Sync client support.102* `h11` - HTTP/1.1 support.103* `h2` - HTTP/2 support.104* `certifi` - SSL certificates.105* `chardet` - Fallback auto-detection for response encoding.106* `hstspreload` - determines whether IDNA-encoded host should be only accessed via HTTPS.107* `idna` - Internationalized domain name support.
6 unmodified lines
114inspiration around the lower-level networking details.115116<p align="center">&mdash; ⭐️ &mdash;</p>117<p align="center"><i>HTTPX is <a href="https://github.com/encode/httpx/blob/master/LICENSE.md">BSD licensed</a> code. Designed & built in Brighton, England.</i></p>132133[sync-support]: https://github.com/encode/httpx/issues/572