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>
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
Provenance
- Commit
2038919- Tree
0376df7- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
eac4b9b
10 files changed+366 added−262 removed
modified:docs/advanced.md+62 added-142 removed
17 unmodified lines18 19 The 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:20 21 ```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 ```28 29-Alternatively, you can explicitly close the connection pool without block-usage using `.aclose()`:29+Alternatively, you can explicitly close the connection pool without block-usage using `.close()`:30 31 ```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 lines49 50 ```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 lines67 68 One particularly useful parameter is `base_url`, which allows you to define a base URL to prepend to all outgoing requests:69 70 ```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.url75 URL('http://httpbin.org/headers')76 ```77 78-For a list of all available client-level parameters, see the [`AsyncClient` API reference](/api/#async-client).78+For a list of all available client-level parameters, see the [`Client` API reference](/api/#client).79 80 ## Calling into Python Web Apps81 82-You can configure an `httpx` client to call directly into a Python web83-application using the ASGI protocol.82+You can configure an `httpx` client to call directly into a Python web application using the WSGI protocol.83 84 This is particularly useful for two main use-cases:85 86 * Using `httpx` as a client inside test cases.87 * Mocking out external services during tests or in dev/staging environments.88 90-Let's take this Starlette application as an example:89+Here's an example of integrating against a Flask application:90 91 ```python93-from starlette.applications import Starlette94-from starlette.responses import HTMLResponse95-from starlette.routing import Route92+from flask import Flask93+import httpx94 95 98-async def hello():99- return HTMLResponse("Hello World!")96+app = Flask(__name__)97 98+@app.route("/")99+def hello():100+ return "Hello World!"101 102-app = Starlette(routes=[Route("/", hello)])102+with httpx.Client(app=app) as client:103+ r = client.get('http://example/')104+ assert r.status_code == 200105+ assert r.text == "Hello World!"106 ```107 105-We can make requests directly against the application, like so:108+For some more complex cases you might need to customize the WSGI dispatch. This allows you to:109 107-```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-```114-115-For some more complex cases you might need to customise the ASGI dispatch. This allows you to:116-110 * 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).113 114 For example:115 116 ```python124-# Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",125-# on port 123.126-dispatch = httpx.dispatch.ASGIDispatch(app=app, client=("1.2.3.4", 123))127-async with httpx.AsyncClient(dispatch=dispatch) as client:117+# Instantiate a client that makes WSGI requests with a client IP of "1.2.3.4".118+dispatch = httpx.WSGIDispatch(app=app, remote_addr="1.2.3.4")119+with httpx.Client(dispatch=dispatch) as client:120 ...121 ```122 131-See [the ASGI documentation](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) for more details on the `client` and `root_path`132-keys.133-123 ## Build Request124 125 You can use `Client.build_request()` to build a request and126 make modifications before sending the request.127 128 ```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 lines146 you should create a new client or restart the interpreter.147 148 As 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 ```152 153 If `NETRC` environment is empty, HTTPX tries to use default files.154 (`~/.netrc`, `~/_netrc`)15 unmodified lines170 171 When using `Client` instances, `trust_env` should be set on the client itself, rather that on the request methods:172 173 ```python185-client = httpx.AsyncClient(trust_env=False)174+client = httpx.Client(trust_env=False)175 ```176 188-## Unix Domain Sockets189-190-You 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.191-192-Here's an example requesting the Docker Engine API:193-194-```python195-import httpx196-197-198-async 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-```202-177 ## HTTP Proxying178 179 HTTPX supports setting up proxies the same way that Requests does via the `proxies` parameter.180 For example to forward all HTTP traffic to `http://127.0.0.1:3080` and all HTTPS traffic3 unmodified lines184 >>> 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 ```191 192 Proxies can be configured for a specific scheme and host, all schemes of a host,6 unmodified lines199 ... "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 ```210 211 !!! 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.215 242-By default `HTTPProxy` will operate as a forwarding proxy for `http://...` requests216+By default `httpx.Proxy` will operate as a forwarding proxy for `http://...` requests217 and will establish a `CONNECT` TCP tunnel for `https://` requests. This doesn't change244-regardless of the `proxy_url` being `http` or `https`.218+regardless of the proxy `url` being `http` or `https`.219 220 Proxies can be configured to have different behavior such as forwarding or tunneling all requests:221 222 ```python249-proxy = 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".223+proxy = httpx.Proxy(224+ url="https://127.0.0.1",225+ mode="TUNNEL_ONLY" # May be "TUNNEL_ONLY" or "FORWARD_ONLY". Defaults to "DEFAULT".226 )253-async with httpx.AsyncClient(proxies=proxy) as client:227+with 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 ```231 232 !!! note233 260- 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.236 237 ## Timeout Configuration238 239 HTTPX is careful to enforce timeouts everywhere by default.6 unmodified lines246 You can set timeouts for an individual request:247 248 ```python249 # Using the top-level API:277-await httpx.get('http://example.com/api/v1/example', timeout=10.0)250+httpx.get('http://example.com/api/v1/example', timeout=10.0)251 252 # Using a client instance:280-async with httpx.AsyncClient() as client:281- await client.get("http://example.com/api/v1/example", timeout=10.0)253+with httpx.Client() as client:254+ client.get("http://example.com/api/v1/example", timeout=10.0)255 ```256 257 Or disable timeouts for an individual request:258 259 ```python260 # Using the top-level API:288-await httpx.get('http://example.com/api/v1/example', timeout=None)261+httpx.get('http://example.com/api/v1/example', timeout=None)262 263 # Using a client instance:291-async with httpx.AsyncClient() as client:292- await client.get("http://example.com/api/v1/example", timeout=None)264+with httpx.Client() as client:265+ client.get("http://example.com/api/v1/example", timeout=None)266 ```267 268 ### Setting a default timeout on a client269 270 You 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:272 273 ```python301-client = httpx.AsyncClient() # Use a default 5s timeout everywhere.302-client = httpx.AsyncClient(timeout=10.0) # Use a default 10s timeout everywhere.303-client = httpx.AsyncClient(timeout=None) # Disable all timeouts by default.274+client = httpx.Client() # Use a default 5s timeout everywhere.275+client = httpx.Client(timeout=10.0) # Use a default 10s timeout everywhere.276+client = httpx.Client(timeout=None) # Disable all timeouts by default.277 ```278 279 ### Fine tuning the configuration280 21 unmodified lines302 303 ```python304 # A client with a 60s timeout for connecting, and a 10s timeout elsewhere.305 timeout = httpx.Timeout(10.0, connect_timeout=60.0)333-client = httpx.AsyncClient(timeout=timeout)306+client = httpx.Client(timeout=timeout)307 335-response = await client.get('http://example.com/')308+response = client.get('http://example.com/')309 ```310 311 ## Multipart file encoding312 2 unmodified lines315 name of the payloads as keys and either tuple of elements or a file-like object or a string as values.316 317 ```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 lines340 MIME header field.341 342 ```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 lines428 429 ```python430 import httpx431 459-r = await httpx.get("https://example.org", verify="path/to/client.pem")432+r = httpx.get("https://example.org", verify="path/to/client.pem")433 ```434 435 You can also disable the SSL verification...436 437 ```python438 import httpx439 467-r = await httpx.get("https://example.org", verify=False)440+r = httpx.get("https://example.org", verify=False)441 ```442 443 ### SSL configuration on client instances444 445 If you're using a `Client()` instance, then you should pass any SSL settings when instantiating the client.446 447 ```python475-client = httpx.AsyncClient(verify=False)448+client = httpx.Client(verify=False)449 ```450 451 The `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 lines461 1. Tell HTTPX to use the certificates stored in `client.pem`:462 463 ```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 >>> r467 Response <200 OK>468 ```496-497-## Supported async environments498-499-HTTPX supports either `asyncio` or `trio` as an async environment.500-501-By default it will auto-detect which of those two to use as the backend502-for socket operations and concurrency primitives.503-504-You can also explicitly select a backend by instantiating a client with the505-`backend` argument...506-507-```python508-client = httpx.AsyncClient(backend='auto') # Autodetection. The default case.509-client = httpx.AsyncClient(backend='asyncio') # Use asyncio as the backend.510-client = httpx.AsyncClient(backend='trio') # Use trio as the backend.511-```512-513-### [AsyncIO](https://docs.python.org/3/library/asyncio.html)514-515-AsyncIO is Python's [built-in library](https://docs.python.org/3/library/asyncio.html)516-for writing concurrent code with the async/await syntax.517-518-```python519-import asyncio520-import httpx521-522-async def main():523- client = httpx.AsyncClient()524- response = await client.get('https://www.example.com/')525- print(response)526-527-asyncio.run(main())528-```529-530-### [Trio](https://github.com/python-trio/trio)531-532-Trio is [an alternative async library](https://trio.readthedocs.io/en/stable/),533-designed around the [the principles of structured concurrency](https://en.wikipedia.org/wiki/Structured_concurrency).534-535-```python536-import httpx537-import trio538-539-async def main():540- client = httpx.AsyncClient()541- response = await client.get('https://www.example.com/')542- print(response)543-544-trio.run(main)545-```546-547-!!! important548- The `trio` package must be installed to use the Trio backend.modified:docs/api.md+12 added-5 removed
30 unmodified lines3132333435353637373839394041424316 unmodified lines6061626364656667686970717273747 unmodified lines828384857986878889909185929394959670 unmodified lines30 unmodified lines
::: httpx.delete :docstring:
## `AsyncClient`## `Client`
::: httpx.AsyncClient::: httpx.Client :docstring: :members: headers cookies params request get head options post put patch delete build_request send aclose :members: headers cookies params request get head options post put patch delete build_request send close
## `Response`
*An HTTP response.*16 unmodified lines [total_seconds()](https://docs.python.org/3/library/datetime.html#datetime.timedelta.total_seconds) to correctly get the total elapsed seconds.* `def .raise_for_status()` - **None*** `def .json()` - **Any*** `def .read()` - **bytes*** `def .iter_raw()` - **async bytes iterator*** `def .iter_bytes()` - **async bytes iterator*** `def .iter_text()` - **async text iterator*** `def .iter_lines()` - **async text iterator*** `def .close()` - **None*** `def .next()` - **Response*** `def .aread()` - **bytes*** `def .aiter_raw()` - **async bytes iterator*** `def .aiter_bytes()` - **async bytes iterator*** `def .aiter_text()` - **async text iterator**7 unmodified lineswhat gets sent over the wire.*
```python>>> request = httpx.Request("GET", "https://example.org", headers={'host': 'example.org'})>>> response = await client.send(request)>>> response = client.send(request)```
* `def __init__(method, url, [params], [data], [json], [headers], [cookies])`* `.method` - **str*** `.url` - **URL*** `.content` - **byte** or **byte async iterator*** `.content` - **byte**, **byte iterator**, or **byte async iterator*** `.headers` - **Headers*** `.cookies` - **Cookies**
## `URL`70 unmodified linesadded:docs/async.md+210 added
1+# Async Support2+3+HTTPX offers a standard synchronous API by default, but also gives you4+the option of an async client if you need it.5+6+Async is a concurrency model that is far more efficient than multi-threading,7+and can provide significant performance benefits and enable the use of8+long-lived network connections such as WebSockets.9+10+If you're working with an async web framework then you'll also want to use an11+async client for sending outgoing HTTP requests.12+13+## Making Async requests14+15+To make asynchronous requests, you'll need an `AsyncClient`.16+17+```python18+>>> async with httpx.AsyncClient() as client:19+>>> r = await client.get('https://www.example.com/')20+>>> r21+<Response [200 OK]>22+```23+24+!!! 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.26+27+## API Differences28+29+If you're using an async client then there are a few bits of API that30+use async methods.31+32+### Making requests33+34+The request methods are all async, so you should use `response = await client.get(...)` style for all of the following:35+36+* `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, ...)`45+46+### Opening and closing clients47+48+Use `async with httpx.AsyncClient()` if you want a context-managed client...49+50+```python51+async with httpx.AsyncClient() as client:52+ ...53+```54+55+Alternatively, use `await client.aclose()` if you want to close a client explicitly:56+57+```python58+client = httpx.AsyncClient()59+...60+await client.aclose()61+```62+63+### Streaming responses64+65+The `AsyncClient.stream(method, url, ...)` method is an async context block.66+67+```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+```73+74+The async response streaming methods are:75+76+* `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.82+83+### Streaming requests84+85+When sending a streaming request body with an `AsyncClient` instance, you should use an async butes generator instead of a bytes generator:86+87+```python88+async def upload_bytes():89+ ... # yield byte content90+91+await client.post(url, data=upload_bytes())92+```93+94+## Supported async environments95+96+HTTPX supports either `asyncio` or `trio` as an async environment.97+98+By default it will auto-detect which of those two to use as the backend99+for socket operations and concurrency primitives.100+101+You can also explicitly select a backend by instantiating a client with the102+`backend` argument...103+104+```python105+client = httpx.AsyncClient(backend='auto') # Autodetection. The default case.106+client = httpx.AsyncClient(backend='asyncio') # Use asyncio as the backend.107+client = httpx.AsyncClient(backend='trio') # Use trio as the backend.108+```109+110+### [AsyncIO](https://docs.python.org/3/library/asyncio.html)111+112+AsyncIO is Python's [built-in library](https://docs.python.org/3/library/asyncio.html)113+for writing concurrent code with the async/await syntax.114+115+```python116+import asyncio117+import httpx118+119+async def main():120+ async with httpx.AsyncClient() as client:121+ response = await client.get('https://www.example.com/')122+ print(response)123+124+asyncio.run(main())125+```126+127+### [Trio](https://github.com/python-trio/trio)128+129+Trio is [an alternative async library](https://trio.readthedocs.io/en/stable/),130+designed around the [the principles of structured concurrency](https://en.wikipedia.org/wiki/Structured_concurrency).131+132+```python133+import httpx134+import trio135+136+async def main():137+ async with httpx.AsyncClient() as client:138+ response = await client.get('https://www.example.com/')139+ print(response)140+141+trio.run(main)142+```143+144+!!! important145+ The `trio` package must be installed to use the Trio backend.146+147+## Calling into Python Web Apps148+149+Just as `httpx.Client` allows you to call directly into WSGI web applications,150+the `httpx.AsyncClient` class allows you to call directly into ASGI web applications.151+152+Let's take this Starlette application as an example:153+154+```python155+from starlette.applications import Starlette156+from starlette.responses import HTMLResponse157+from starlette.routing import Route158+159+160+async def hello():161+ return HTMLResponse("Hello World!")162+163+164+app = Starlette(routes=[Route("/", hello)])165+```166+167+We can make requests directly against the application, like so:168+169+```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+```176+177+For some more complex cases you might need to customise the ASGI dispatch. This allows you to:178+179+* 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`.182+183+For example:184+185+```python186+# Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",187+# on port 123.188+dispatch = httpx.ASGIDispatch(app=app, client=("1.2.3.4", 123))189+async with httpx.AsyncClient(dispatch=dispatch) as client:190+ ...191+```192+193+See [the ASGI documentation](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) for more details on the `client` and `root_path` keys.194+195+## Unix Domain Sockets196+197+The 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.198+199+Here's an example requesting the Docker Engine API:200+201+```python202+import httpx203+204+205+async 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+```209+210+This functionality is not currently available in the synchronous client.modified:docs/compatibility.md+8 added-8 removed
20 unmodified lines21 22 For example:23 24 ```python25-async with request.stream("GET", "https://www.example.com") as response:25+with request.stream("GET", "https://www.example.com") as response:26 ...27 ```28 29 Within a `stream()` block request data is made available with:30 31-* `.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.36 37 ## SSL configuration38 39 When 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 lines51 We 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:`.52 53 ## Client instances54 55-The HTTPX equivalent of `requests.Session` is `httpx.AsyncClient`.55+The HTTPX equivalent of `requests.Session` is `httpx.Client`.56 57 ```python58 session = requests.Session(**kwargs)59 ```60 61 is generally equivalent to62 63 ```python64-client = httpx.AsyncClient(**kwargs)64+client = httpx.Client(**kwargs)65 ```66 67 ## Mocking68 1 unmodified linemodified:docs/environment_variables.md+2 added-2 removed
2 unmodified lines3 4 The HTTPX library can be configured via environment variables.5 Environment 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:6 7-* 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)`.9 10 Here is a list of environment variables that HTTPX recognizes and what function they serve:11 11 unmodified lines23 ```python24 # test_script.py25 import httpx26 27-with httpx.AsyncClient() as client:27+with httpx.Client() as client:28 r = client.get("https://google.com")29 ```30 31 Debug output:123 unmodified linesmodified:docs/http2.md+5 added-5 removed
16 unmodified lines17 For a comprehensive guide to HTTP/2 you may want to check out "[HTTP2 Explained](https://http2-explained.haxx.se/content/en/)".18 19 ## Enabling HTTP/220 21-The HTTPX client provides provisional HTTP/2 support.21+The HTTPX client provides HTTP/2 support, **which is currently only available with the async client**.22 23 HTTP/2 support is not enabled by default, because HTTP/1.1 is a mature,24-battle-hardened transport layer. With HTTP/2 being newer and significantly more25-complex, our implementation should be considered a less robust option at this26-point in time.24+battle-hardened transport layer, and our HTTP/1.1 may be considered the more robust25+option at this point in time. It is possible that a future version of `httpx` may26+enable HTTP/2 support by default.27 28-However, if you're issuing highly concurrent requests you might want to consider28+If you're issuing highly concurrent requests you might want to consider29 trying out our HTTP/2 support. You can do so by instantiating a client with30 HTTP/2 support enabled:31 32 ```python28 unmodified linesmodified:docs/index.md+14 added-26 removed
22 unmodified lines23 24 <em>A next-generation HTTP client for Python.</em>25 </div>26 27-HTTPX is an asynchronous client library that supports HTTP/1.1 and HTTP/2.27+HTTPX 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.28 29-It can be used in high-performance async web frameworks, using either asyncio30-or trio, and is able to support making large numbers of concurrent requests.29 30 !!! 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.32 38- 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.34 35+ A 1.0 release is expected to be issued sometime on or before April 2020.36+37 ---38 39 Let's get started...40 48-The standard Python REPL does not allow top-level async statements.49-50-To run these async examples you'll probably want to either use `ipython`,51-or use Python 3.8 with `python -m asyncio`.52-41 ```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_code47 20060->>> 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 lines55 56 HTTPX is a high performance asynchronous HTTP client, that builds on the57 well-established usability of `requests`, and gives you:58 73-* 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.66 67 Plus all the standard features of `requests`...68 69 * International Domains and URLs16 unmodified lines86 87 For a run-through of all the basics, head over to the [QuickStart](quickstart.md).88 89 For more advanced topics, see the [Advanced Usage](advanced.md) section,103-or the [HTTP/2](http2.md) section.90+the [async support](async.md) section, or the [HTTP/2](http2.md) section.91 92 The [Developer Interface](api.md) provides a comprehensive API reference.93 94 ## Dependencies95 96 The HTTPX project relies on these excellent libraries:97 111-* `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 linesmodified:docs/quickstart.md+39 added-45 removed
1 # QuickStart2 3-!!! note4- The standard Python REPL does not allow top-level async statements.5-6- To run async examples directly you'll probably want to either use `ipython`,7- or use Python 3.8 with `python -m asyncio`.8-3 First, start by importing HTTPX:4 5 ```python6 >>> import httpx1 unmodified line8 9 Now, let’s try to get a webpage.10 11 ```python18->>> r = await httpx.get('https://httpbin.org/get')12+>>> r = httpx.get('https://httpbin.org/get')13 >>> r14 <Response [200 OK]>15 ```16 17 Similarly, to make an HTTP POST request:18 19 ```python26->>> r = await httpx.post('https://httpbin.org/post', data={'key': 'value'})20+>>> r = httpx.post('https://httpbin.org/post', data={'key': 'value'})21 ```22 23 The PUT, DELETE, HEAD, and OPTIONS requests all follow the same style:24 25 ```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 ```31 32 ## Passing Parameters in URLs33 34 To include URL query parameters in the request, use the `params` keyword:35 36 ```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 ```40 41 To see how the values get encoding into the URL string, we can inspect the42 resulting URL that was used to make the request:6 unmodified lines49 You can also pass a list of items as a value:50 51 ```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.url55 URL('https://httpbin.org/get?key1=value1&key2=value2&key2=value3')56 ```57 1 unmodified line59 60 HTTPX will automatically handle decoding the response content into Unicode text.61 62 ```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 lines104 105 Often Web API responses will be encoded as JSON.106 107 ```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 lines116 117 ```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 ```122 123 ## Sending Form Encoded Data124 2 unmodified lines127 which is used for HTML forms.128 129 ```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 lines143 Form encoded data can also include multiple values form a given key.144 145 ```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 lines163 You can also upload files, using HTTP multipart encoding:164 165 ```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 lines179 of items for the file value:180 181 ```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 lines197 For more complicated data structures you'll often want to use JSON encoding instead.198 199 ```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 lines227 228 We can inspect the HTTP status code of the response:229 230 ```python237->>> r = await httpx.get('https://httpbin.org/get')231+>>> r = httpx.get('https://httpbin.org/get')232 >>> r.status_code233 200234 ```235 6 unmodified lines242 243 We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):244 245 ```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_code248 404249 >>> not_found.raise_for_status()250 Traceback (most recent call last):45 unmodified lines296 297 You can stream the binary content of the response...298 299 ```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 ```304 305 Or the text of the response...306 307 ```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 ```312 313 Or stream the text, on a line-by-line basis...314 315 ```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 ```320 321 HTTPX will use universal line endings, normalising all cases to `\n`.322 323 In 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.324 325 ```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 ```330 331 If 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:332 339-```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 ```339 340 ## Cookies341 342 Any cookies that are set on the response can be easily accessed:343 344 ```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 ```349 350 To include cookies in an outgoing request, use the `cookies` parameter:351 352 ```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 lines362 ```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 lines378 379 For example, GitHub redirects all HTTP requests to HTTPS.380 381 ```python388->>> r = await httpx.get('http://github.com/')382+>>> r = httpx.get('http://github.com/')383 >>> r.url384 URL('https://github.com/')385 >>> r.status_code386 2003 unmodified lines390 391 You can modify the default redirection handling with the allow_redirects parameter:392 393 ```python400->>> r = await httpx.get('http://github.com/', allow_redirects=False)394+>>> r = httpx.get('http://github.com/', allow_redirects=False)395 >>> r.status_code396 301397 >>> r.history398 []1 unmodified line400 401 If you’re making a `HEAD` request, you can use this to enable redirection:402 403 ```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 lines417 The default timeout for network inactivity is five seconds. You can modify the418 value to be more or less strict:419 420 ```python427->>> await httpx.get('https://github.com/', timeout=0.001)421+>>> httpx.get('https://github.com/', timeout=0.001)422 ```423 424 You can also disable the timeout behavior completely...425 426 ```python433->>> await httpx.get('https://github.com/', timeout=None)427+>>> httpx.get('https://github.com/', timeout=None)428 ```429 430 For advanced timeout management, see [Timeout fine-tuning](https://www.encode.io/httpx/advanced/#fine-tuning-the-configuration).431 5 unmodified lines437 plaintext `str` or `bytes` objects as the `auth` argument to the request438 functions:439 440 ```python447->>> await httpx.get("https://example.com", auth=("my_user", "password123"))441+>>> httpx.get("https://example.com", auth=("my_user", "password123"))442 ```443 444 To provide credentials for Digest authentication you'll need to instantiate445 a `DigestAuth` object with the plaintext username and password as arguments.1 unmodified line447 as above:448 449 ```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
10 unmodified lines1112131415161718199 unmodified lines10 unmodified linesnav: - Introduction: 'index.md' - QuickStart: 'quickstart.md' - Advanced Usage: 'advanced.md' - Async Support: 'async.md' - HTTP/2 Support: 'http2.md' - Environment Variables: 'environment_variables.md' - Requests Compatibility: 'compatibility.md' - Developer Interface: 'api.md'9 unmodified linesmodified:README.md+13 added-29 removed
14 unmodified lines15 <img src="https://badge.fury.io/py/httpx.svg" alt="Package version">16 </a>17 </p>18 19-HTTPX is an asynchronous HTTP client, that supports HTTP/2 and HTTP/1.1.19+HTTPX 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.20 21-It can be used in high-performance async web frameworks, using either asyncio22-or 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 to22+a stable point now, but would strongly recommend pinning your dependencies to the `0.11.*`23+release, so that you're able to properly review API changes between package updates.24+A 1.0 release is expected to be issued sometime on or before April 2020._25 24-**Note**: *HTTPX should still be considered in alpha. We'd love early users and feedback,25-but would strongly recommend pinning your dependencies to the latest median26-release, so that you're able to properly review API changes between package27-updates. Currently you should be using `httpx==0.10.*`.*28-29-*In particular, the 0.8 release switched HTTPX into focusing exclusively on30-providing an async client, in order to move the project forward, and help31-us [change our approach to providing sync+async support][sync-support]. If32-you have been using the sync client, you may want to pin to `httpx==0.7.*`,33-and wait until our sync client is reintroduced.*34-26 ---27 28 Let's get started...29 39-*The standard Python REPL does not allow top-level async statements.*40-41-*To run async examples directly you'll probably want to either use `ipython`,42-or use Python 3.8 with `python -m asyncio`.*43-30 ```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_code36 20051->>> 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 lines44 45 HTTPX builds on the well-established usability of `requests`, and gives you:46 47 * 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.54 55 Plus all the standard features of `requests`...56 57 * International Domains and URLs27 unmodified lines85 Project documentation is available at [www.encode.io/httpx/](https://www.encode.io/httpx/).86 87 For a run-through of all the basics, head over to the [QuickStart](https://www.encode.io/httpx/quickstart/).88 104-For more advanced topics, see the [Advanced Usage](https://www.encode.io/httpx/advanced/) section.89+For 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.90 91 The [Developer Interface](https://www.encode.io/httpx/api/) provides a comprehensive API reference.92 93 ## Contribute3 unmodified lines97 ## Dependencies98 99 The httpx project relies on these excellent libraries:100 116-* `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 lines114 inspiration around the lower-level networking details.115 116 <p align="center">— ⭐️ —</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>132-133-[sync-support]: https://github.com/encode/httpx/issues/572