QuickStart

!!! note This page closely follows the layout of the requests QuickStart documentation. The httpx library is designed to be API compatible with requests wherever possible.

First start by importing HTTPX:

  1. >>> import httpx

Now, let’s try to get a webpage.

  1. >>> r = httpx.get('https://httpbin.org/get')
  2. >>> r
  3. <Response [200 OK]>

Similarly, to make an HTTP POST request:

  1. >>> r = httpx.post('https://httpbin.org/post', data={'key': 'value'})

The PUT, DELETE, HEAD, and OPTIONS requests all follow the same style:

  1. >>> r = httpx.put('https://httpbin.org/put', data={'key': 'value'})
  2. >>> r = httpx.delete('https://httpbin.org/delete')
  3. >>> r = httpx.head('https://httpbin.org/get')
  4. >>> r = httpx.options('https://httpbin.org/get')

Passing Parameters in URLs

To include URL query parameters in the request, use the params keyword:

  1. >>> params = {'key1': 'value1', 'key2': 'value2'}
  2. >>> r = httpx.get('https://httpbin.org/get', params=params)

To see how the values get encoding into the URL string, we can inspect theresulting URL that was used to make the request:

  1. >>> r.url
  2. URL('https://httpbin.org/get?key2=value2&key1=value1')

You can also pass a list of items as a value:

  1. >>> params = {'key1': 'value1', 'key2': ['value2', 'value3']}
  2. >>> r = httpx.get('https://httpbin.org/get', params=params)
  3. >>> r.url
  4. URL('https://httpbin.org/get?key1=value1&key2=value2&key2=value3')

Response Content

HTTPX will automatically handle decoding the response content into unicode text.

  1. >>> r = httpx.get('https://www.example.org/')
  2. >>> r.text
  3. '<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'

You can inspect what encoding has been used to decode the response.

  1. >>> r.encoding
  2. 'UTF-8'

If you need to override the standard behavior and explicitly set the encoding touse, then you can do that too.

  1. >>> r.encoding = 'ISO-8859-1'

Binary Response Content

The response content can also be accessed as bytes, for non-text responses:

  1. >>> r.content
  2. b'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'

Any gzip and deflate HTTP response encodings will automaticallybe decoded for you. If brotlipy is installed, then the brotli responseencoding will also be supported.

For example, to create an image from binary data returned by a request, you can use the following code:

  1. >>> from PIL import Image
  2. >>> from io import BytesIO
  3. >>> i = Image.open(BytesIO(r.content))

JSON Response Content

Often Web API responses will be encoded as JSON.

  1. >>> r = httpx.get('https://api.github.com/events')
  2. >>> r.json()
  3. [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...' ... }}]

Custom Headers

To include additional headers in the outgoing request, use the headers keyword argument:

  1. >>> url = 'http://httpbin.org/headers'
  2. >>> headers = {'user-agent': 'my-app/0.0.1'}
  3. >>> r = httpx.get(url, headers=headers)

Sending Form Encoded Data

Some types of HTTP requests, such as POST and PUT requests, can include datain the request body. One common way of including that is as form encoded data,which is used for HTML forms.

  1. >>> data = {'key1': 'value1', 'key2': 'value2'}
  2. >>> r = httpx.post("https://httpbin.org/post", data=data)
  3. >>> print(r.text)
  4. {
  5. ...
  6. "form": {
  7. "key2": "value2",
  8. "key1": "value1"
  9. },
  10. ...
  11. }

Form encoded data can also include multiple values form a given key.

  1. >>> data = {'key1': ['value1', 'value2']}
  2. >>> r = httpx.post("https://httpbin.org/post", data=data)
  3. >>> print(r.text)
  4. {
  5. ...
  6. "form": {
  7. "key1": [
  8. "value1",
  9. "value2"
  10. ]
  11. },
  12. ...
  13. }

Sending Multipart File Uploads

You can also upload files, using HTTP multipart encoding:

  1. >>> files = {'upload-file': open('report.xls', 'rb')}
  2. >>> r = httpx.post("https://httpbin.org/post", files=files)
  3. >>> print(r.text)
  4. {
  5. ...
  6. "files": {
  7. "upload-file": "<... binary content ...>"
  8. },
  9. ...
  10. }

You can also explicitly set the filename and content type, by using a tupleof items for the file value:

  1. >>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}
  2. >>> r = httpx.post("https://httpbin.org/post", files=files)
  3. >>> print(r.text)
  4. {
  5. ...
  6. "files": {
  7. "upload-file": "<... binary content ...>"
  8. },
  9. ...
  10. }

Sending JSON Encoded Data

Form encoded data is okay if all you need is simple key-value data structure.For more complicated data structures you’ll often want to use JSON encoding instead.

  1. >>> data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']}
  2. >>> r = httpx.post("https://httpbin.org/post", json=data)
  3. >>> print(r.text)
  4. {
  5. ...
  6. "json": {
  7. "boolean": true,
  8. "integer": 123,
  9. "list": [
  10. "a",
  11. "b",
  12. "c"
  13. ]
  14. },
  15. ...
  16. }

Sending Binary Request Data

For other encodings you should use either a bytes type, or a generatorthat yields bytes.

You’ll probably also want to set a custom Content-Type header when uploadingbinary data.

Response Status Codes

We can inspect the HTTP status code of the response:

  1. >>> r = httpx.get('https://httpbin.org/get')
  2. >>> r.status_code
  3. 200

HTTPX also includes an easy shortcut for accessing status codes by their text phrase.

  1. >>> r.status_code == httpx.codes.OK
  2. True

We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):

  1. >>> not_found = httpx.get('https://httpbin.org/status/404')
  2. >>> not_found.status_code
  3. 404
  4. >>> not_found.raise_for_status()
  5. Traceback (most recent call last):
  6. File "/Users/tomchristie/GitHub/encode/httpcore/httpx/models.py", line 776, in raise_for_status
  7. raise HttpError(message)
  8. httpx.exceptions.HttpError: 404 Not Found

Any successful response codes will simply return None rather than raising an exception.

  1. >>> r.raise_for_status()

Response Headers

The response headers are available as a dictionary-like interface.

  1. >>> r.headers
  2. Headers({
  3. 'content-encoding': 'gzip',
  4. 'transfer-encoding': 'chunked',
  5. 'connection': 'close',
  6. 'server': 'nginx/1.0.4',
  7. 'x-runtime': '148ms',
  8. 'etag': '"e1ca502697e5c9317743dc078f67693f"',
  9. 'content-type': 'application/json'
  10. })

The Headers data type is case-insensitive, so you can use any capitalization.

  1. >>> r.headers['Content-Type']
  2. 'application/json'
  3. >>> r.headers.get('content-type')
  4. 'application/json'

Multiple values for a single response header are represented as a single comma separatedvalue, as per RFC 7230:

A recipient MAY combine multiple header fields with the same field name into one “field-name: field-value” pair, without changing the semantics of the message, by appending each subsequent field value to the combined field value in order, separated by a comma.

Cookies

Any cookies that are set on the response can be easily accessed:

  1. >>> r = httpx.get('http://httpbin.org/cookies/set?chocolate=chip', allow_redirects=False)
  2. >>> r.cookies['chocolate']
  3. 'chip'

To include cookies in an outgoing request, use the cookies parameter:

  1. >>> cookies = {"peanut": "butter"}
  2. >>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)
  3. >>> r.json()
  4. {'cookies': {'peanut': 'butter'}}

Cookies are returned in a Cookies instance, which is a dict-like data structurewith additional API for accessing cookies by their domain or path.

  1. >>> cookies = httpx.Cookies()
  2. >>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')
  3. >>> cookies.set('cookie_off_domain', 'nope.', domain='example.org')
  4. >>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)
  5. >>> r.json()
  6. {'cookies': {'cookie_on_domain': 'hello, there!'}}

Redirection and History

By default HTTPX will follow redirects for anything except HEAD requests.

The history property of the response can be used to inspect any followed redirects.It contains a list of all any redirect responses that were followed, in the orderin which they were made.

For example, GitHub redirects all HTTP requests to HTTPS.

  1. >>> r = httpx.get('http://github.com/')
  2. >>> r.url
  3. URL('https://github.com/')
  4. >>> r.status_code
  5. 200
  6. >>> r.history
  7. [<Response [301 Moved Permanently]>]

You can modify the default redirection handling with the allow_redirects parameter:

  1. >>> r = httpx.get('http://github.com/', allow_redirects=False)
  2. >>> r.status_code
  3. 301
  4. >>> r.history
  5. []

If you’re making a HEAD request, you can use this to enable redirection:

  1. >>> r = httpx.head('http://github.com/', allow_redirects=True)
  2. >>> r.url
  3. 'https://github.com/'
  4. >>> r.history
  5. [<Response [301 Moved Permanently]>]

Timeouts

HTTPX defaults to including reasonable timeouts for all network operations,meaning that if a connection is not properly established then it should alwaysraise an error rather than hanging indefinitely.

The default timeout for network inactivity is five seconds. You can modify thevalue to be more or less strict:

  1. >>> httpx.get('https://github.com/', timeout=0.001)