Once you have a `Client`, you can send requests using `.get()`, `.post()`, etc. For example:
-```python
+```pycon
>>> with httpx.Client() as client:
... r = client.get('https://example.com')
...
For example, to send a request with custom headers:
-```python
+```pycon
>>> with httpx.Client() as client:
... headers = {'X-Custom': 'value'}
... r = client.get('https://example.com', headers=headers)
For example, to apply a set of custom headers _on every request_:
-```python
+```pycon
>>> url = 'http://httpbin.org/headers'
>>> headers = {'user-agent': 'my-app/0.0.1'}
>>> with httpx.Client(headers=headers) as client:
- For headers, query parameters and cookies, the values are combined together. For example:
-```python
+```pycon
>>> headers = {'X-Auth': 'from-client'}
>>> params = {'client_id': 'client1'}
>>> with httpx.Client(headers=headers, params=params) as client:
- For all other parameters, the request-level value takes priority. For example:
-```python
+```pycon
>>> with httpx.Client(auth=('tom', 'mot123')) as client:
... r = client.get('https://example.com', auth=('alice', 'ecila123'))
...
For example, `base_url` allows you to prepend an URL to all outgoing requests:
-```python
+```pycon
>>> with httpx.Client(base_url='http://httpbin.org') as client:
... r = client.get('/headers')
...
you should create a new client or restart the interpreter.
As default `trust_env` is true. To set false:
-```python
+```pycon
>>> httpx.get('https://example.org/', trust_env=False)
```
(`~/.netrc`, `~/_netrc`)
To change `NETRC` environment:
-```python
+```pycon
>>> import os
>>> os.environ["NETRC"] = "my_default_folder/.my_netrc"
```
multipart file encoding is available by passing a dictionary with the
name of the payloads as keys and either tuple of elements or a file-like object or a string as values.
-```python
+```pycon
>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}
>>> r = httpx.post("https://httpbin.org/post", files=files)
>>> print(r.text)
If the file name is explicitly set to `None` then HTTPX will not include a content-type
MIME header field.
-```python
+```pycon
>>> files = {'upload-file': (None, 'text content', 'text/plain')}
>>> r = httpx.post("https://httpbin.org/post", files=files)
>>> print(r.text)
To do that, pass a list of `(field, <file>)` items instead of a dictionary, allowing you to pass multiple items with the same `field`.
For instance this request sends 2 files, `foo.png` and `bar.png` in one request on the `images` form field:
-```python
+```pycon
>>> files = [('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),
('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]
>>> r = httpx.post("https://httpbin.org/post", files=files)
Alternatively, you can pass a standard library `ssl.SSLContext`.
-```python
+```pycon
>>> import ssl
>>> import httpx
>>> context = ssl.create_default_context()
We also include a helper function for creating properly configured `SSLContext` instances.
-```python
+```pycon
>>> context = httpx.create_ssl_context()
```
(`trust_env`, `verify`, `cert` and `http2` arguments)
as `httpx.Client` or `httpx.AsyncClient`
-```python
+```pycon
>>> import httpx
>>> context = httpx.create_ssl_context(verify="/tmp/client.pem")
>>> httpx.get('https://example.org', verify=context)
1. Pass the server key/cert files when starting your local server. (This depends on the particular web server you're using. For example, [Uvicorn](https://www.uvicorn.org) provides the `--ssl-keyfile` and `--ssl-certfile` options.)
1. Tell HTTPX to use the certificates stored in `client.pem`:
-```python
+```pycon
>>> import httpx
>>> r = httpx.get("https://localhost:8000", verify="/tmp/client.pem")
>>> r
provides a `local_address` configuration that is only available via this
low-level API.
-```python
+```pycon
>>> import httpx, httpcore
>>> ssl_context = httpx.create_ssl_context()
>>> transport = httpcore.SyncConnectionPool(
[`urllib3` library](https://urllib3.readthedocs.io/en/latest/), which can be
used with the sync `Client`...
-```python
+```pycon
>>> import httpx
>>> client = httpx.Client(transport=httpx.URLLib3Transport())
>>> client.get("https://example.org")
Which we can use in the same way:
-```python
+```pycon
>>> import httpx
>>> client = httpx.Client(transport=HelloWorldTransport())
>>> response = client.get("https://example.org/")
First, start by importing HTTPX:
-```python
+```pycon
>>> import httpx
```
Now, let’s try to get a webpage.
-```python
+```pycon
>>> r = httpx.get('https://httpbin.org/get')
>>> r
<Response [200 OK]>
Similarly, to make an HTTP POST request:
-```python
+```pycon
>>> r = httpx.post('https://httpbin.org/post', data={'key': 'value'})
```
The PUT, DELETE, HEAD, and OPTIONS requests all follow the same style:
-```python
+```pycon
>>> r = httpx.put('https://httpbin.org/put', data={'key': 'value'})
>>> r = httpx.delete('https://httpbin.org/delete')
>>> r = httpx.head('https://httpbin.org/get')
To include URL query parameters in the request, use the `params` keyword:
-```python
+```pycon
>>> params = {'key1': 'value1', 'key2': 'value2'}
>>> r = httpx.get('https://httpbin.org/get', params=params)
```
To see how the values get encoding into the URL string, we can inspect the
resulting URL that was used to make the request:
-```python
+```pycon
>>> r.url
URL('https://httpbin.org/get?key2=value2&key1=value1')
```
You can also pass a list of items as a value:
-```python
+```pycon
>>> params = {'key1': 'value1', 'key2': ['value2', 'value3']}
>>> r = httpx.get('https://httpbin.org/get', params=params)
>>> r.url
HTTPX will automatically handle decoding the response content into Unicode text.
-```python
+```pycon
>>> r = httpx.get('https://www.example.org/')
>>> r.text
'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'
You can inspect what encoding has been used to decode the response.
-```python
+```pycon
>>> r.encoding
'UTF-8'
```
If you need to override the standard behavior and explicitly set the encoding to
use, then you can do that too.
-```python
+```pycon
>>> r.encoding = 'ISO-8859-1'
```
The response content can also be accessed as bytes, for non-text responses:
-```python
+```pycon
>>> r.content
b'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'
```
For example, to create an image from binary data returned by a request, you can use the following code:
-```python
+```pycon
>>> from PIL import Image
>>> from io import BytesIO
>>> i = Image.open(BytesIO(r.content))
Often Web API responses will be encoded as JSON.
-```python
+```pycon
>>> r = httpx.get('https://api.github.com/events')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...' ... }}]
To include additional headers in the outgoing request, use the `headers` keyword argument:
-```python
+```pycon
>>> url = 'http://httpbin.org/headers'
>>> headers = {'user-agent': 'my-app/0.0.1'}
>>> r = httpx.get(url, headers=headers)
in the request body. One common way of including that is as form-encoded data,
which is used for HTML forms.
-```python
+```pycon
>>> data = {'key1': 'value1', 'key2': 'value2'}
>>> r = httpx.post("https://httpbin.org/post", data=data)
>>> print(r.text)
Form encoded data can also include multiple values from a given key.
-```python
+```pycon
>>> data = {'key1': ['value1', 'value2']}
>>> r = httpx.post("https://httpbin.org/post", data=data)
>>> print(r.text)
You can also upload files, using HTTP multipart encoding:
-```python
+```pycon
>>> files = {'upload-file': open('report.xls', 'rb')}
>>> r = httpx.post("https://httpbin.org/post", files=files)
>>> print(r.text)
You can also explicitly set the filename and content type, by using a tuple
of items for the file value:
-```python
+```pycon
>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}
>>> r = httpx.post("https://httpbin.org/post", files=files)
>>> print(r.text)
If you need to include non-file data fields in the multipart form, use the `data=...` parameter:
-```python
+```pycon
>>> data = {'message': 'Hello, world!'}
>>> files = {'file': open('report.xls', 'rb')}
>>> r = httpx.post("https://httpbin.org/post", data=data, files=files)
Form encoded data is okay if all you need is a simple key-value data structure.
For more complicated data structures you'll often want to use JSON encoding instead.
-```python
+```pycon
>>> data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']}
>>> r = httpx.post("https://httpbin.org/post", json=data)
>>> print(r.text)
We can inspect the HTTP status code of the response:
-```python
+```pycon
>>> r = httpx.get('https://httpbin.org/get')
>>> r.status_code
200
HTTPX also includes an easy shortcut for accessing status codes by their text phrase.
-```python
+```pycon
>>> r.status_code == httpx.codes.OK
True
```
We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):
-```python
+```pycon
>>> not_found = httpx.get('https://httpbin.org/status/404')
>>> not_found.status_code
404
Any successful response codes will simply return `None` rather than raising an exception.
-```python
+```pycon
>>> r.raise_for_status()
```
The response headers are available as a dictionary-like interface.
-```python
+```pycon
>>> r.headers
Headers({
'content-encoding': 'gzip',
The `Headers` data type is case-insensitive, so you can use any capitalization.
-```python
+```pycon
>>> r.headers['Content-Type']
'application/json'
You can stream the binary content of the response...
-```python
+```pycon
>>> with httpx.stream("GET", "https://www.example.com") as r:
... for data in r.iter_bytes():
... print(data)
Or the text of the response...
-```python
+```pycon
>>> with httpx.stream("GET", "https://www.example.com") as r:
... for text in r.iter_text():
... print(text)
Or stream the text, on a line-by-line basis...
-```python
+```pycon
>>> with httpx.stream("GET", "https://www.example.com") as r:
... for line in r.iter_lines():
... print(line)
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.
-```python
+```pycon
>>> with httpx.stream("GET", "https://www.example.com") as r:
... for chunk in r.iter_raw():
... print(chunk)
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:
-```python
+```pycon
>>> with httpx.stream("GET", "https://www.example.com") as r:
... if r.headers['Content-Length'] < TOO_LONG:
... r.read()
Any cookies that are set on the response can be easily accessed:
-```python
+```pycon
>>> r = httpx.get('http://httpbin.org/cookies/set?chocolate=chip', allow_redirects=False)
>>> r.cookies['chocolate']
'chip'
To include cookies in an outgoing request, use the `cookies` parameter:
-```python
+```pycon
>>> cookies = {"peanut": "butter"}
>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)
>>> r.json()
Cookies are returned in a `Cookies` instance, which is a dict-like data structure
with additional API for accessing cookies by their domain or path.
-```python
+```pycon
>>> cookies = httpx.Cookies()
>>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')
>>> cookies.set('cookie_off_domain', 'nope.', domain='example.org')
For example, GitHub redirects all HTTP requests to HTTPS.
-```python
+```pycon
>>> r = httpx.get('http://github.com/')
>>> r.url
URL('https://github.com/')
You can modify the default redirection handling with the allow_redirects parameter:
-```python
+```pycon
>>> r = httpx.get('http://github.com/', allow_redirects=False)
>>> r.status_code
301
If you’re making a `HEAD` request, you can use this to enable redirection:
-```python
+```pycon
>>> r = httpx.head('http://github.com/', allow_redirects=True)
>>> r.url
'https://github.com/'
The default timeout for network inactivity is five seconds. You can modify the
value to be more or less strict:
-```python
+```pycon
>>> httpx.get('https://github.com/', timeout=0.001)
```
You can also disable the timeout behavior completely...
-```python
+```pycon
>>> httpx.get('https://github.com/', timeout=None)
```
plaintext `str` or `bytes` objects as the `auth` argument to the request
functions:
-```python
+```pycon
>>> httpx.get("https://example.com", auth=("my_user", "password123"))
```
This object can be then passed as the `auth` argument to the request methods
as above:
-```python
+```pycon
>>> auth = httpx.DigestAuth("my_user", "password123")
>>> httpx.get("https://example.com", auth=auth)
<Response [200 OK]>