Skip to content
Myr

quickstart.md

This file

Path

docs/quickstart.md

406 lines · 9.9 KiB · Markdown

Last changed by

Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499

History of this file

Take it

The walk stopped after 200 commits: lines older than f9e3ad4 point at it.

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 1–4why, one step back
1# QuickStart
23!!! note4 This page closely follows the layout of the `requests` QuickStart documentation.

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 5why, one step back
5 The `httpx` library is designed to be API compatible with `requests` wherever

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 6–7why, one step back
6 possible.
7

Fix typos, spelling issues, and grammar in docs (#426)Kyle Galbraithbefore adoptionb65bce5

line 8why, one step back
8First, start by importing HTTPX:

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

line 9why, one step back
9

Add language syntax highlighting in Quickstart (#466)ImPerat0R_before adoption97a104a

line 10why, one step back
10```python

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 11why, one step back
11>>> import httpx

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 12–16why, one step back
12```
1314Now, let’s try to get a webpage.1516```python

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 17why, one step back
17>>> r = httpx.get('https://httpbin.org/get')

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 18–24why, one step back
18>>> r
19<Response [200 OK]>20```2122Similarly, to make an HTTP POST request:2324```python

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 25why, one step back
25>>> r = httpx.post('https://httpbin.org/post', data={'key': 'value'})

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 26–30why, one step back
26```
2728The PUT, DELETE, HEAD, and OPTIONS requests all follow the same style:2930```python

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

lines 31–34why, one step back
31>>> r = httpx.put('https://httpbin.org/put', data={'key': 'value'})
32>>> r = httpx.delete('https://httpbin.org/delete')33>>> r = httpx.head('https://httpbin.org/get')34>>> r = httpx.options('https://httpbin.org/get')

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 35–42why, one step back
35```
3637## Passing Parameters in URLs3839To include URL query parameters in the request, use the `params` keyword:4041```python42>>> params = {'key1': 'value1', 'key2': 'value2'}

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 43why, one step back
43>>> r = httpx.get('https://httpbin.org/get', params=params)

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 44–57why, one step back
44```
4546To see how the values get encoding into the URL string, we can inspect the47resulting URL that was used to make the request:4849```python50>>> r.url51URL('https://httpbin.org/get?key2=value2&key1=value1')52```5354You can also pass a list of items as a value:5556```python57>>> params = {'key1': 'value1', 'key2': ['value2', 'value3']}

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 58why, one step back
58>>> r = httpx.get('https://httpbin.org/get', params=params)

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 59–64why, one step back
59>>> r.url
60URL('https://httpbin.org/get?key1=value1&key2=value2&key2=value3')61```6263## Response Content64

Fix typos, spelling issues, and grammar in docs (#426)Kyle Galbraithbefore adoptionb65bce5

line 65why, one step back
65HTTPX will automatically handle decoding the response content into Unicode text.

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 66–67why, one step back
66
67```python

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 68why, one step back
68>>> r = httpx.get('https://www.example.org/')

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 69–112why, one step back
69>>> r.text
70'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'71```7273You can inspect what encoding has been used to decode the response.7475```python76>>> r.encoding77'UTF-8'78```7980If you need to override the standard behavior and explicitly set the encoding to81use, then you can do that too.8283```python84>>> r.encoding = 'ISO-8859-1'85```8687## Binary Response Content8889The response content can also be accessed as bytes, for non-text responses:9091```python92>>> r.content93b'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'94```9596Any `gzip` and `deflate` HTTP response encodings will automatically97be decoded for you. If `brotlipy` is installed, then the `brotli` response98encoding will also be supported.99100For example, to create an image from binary data returned by a request, you can use the following code:101102```python103>>> from PIL import Image104>>> from io import BytesIO105>>> i = Image.open(BytesIO(r.content))106```107108## JSON Response Content109110Often Web API responses will be encoded as JSON.111112```python

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 113why, one step back
113>>> r = httpx.get('https://api.github.com/events')

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 114–124why, one step back
114>>> r.json()
115[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...' ... }}]116```117118## Custom Headers119120To include additional headers in the outgoing request, use the `headers` keyword argument:121122```python123>>> url = 'http://httpbin.org/headers'124>>> headers = {'user-agent': 'my-app/0.0.1'}

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 125why, one step back
125>>> r = httpx.get(url, headers=headers)

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 126–130why, one step back
126```
127128## Sending Form Encoded Data129130Some types of HTTP requests, such as `POST` and `PUT` requests, can include data

Fix typos, spelling issues, and grammar in docs (#426)Kyle Galbraithbefore adoptionb65bce5

line 131why, one step back
131in the request body. One common way of including that is as form-encoded data,

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 132–135why, one step back
132which is used for HTML forms.
133134```python135>>> data = {'key1': 'value1', 'key2': 'value2'}

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 136why, one step back
136>>> r = httpx.post("https://httpbin.org/post", data=data)

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 137–151why, one step back
137>>> print(r.text)
138{139 ...140 "form": {141 "key2": "value2",142 "key1": "value1"143 },144 ...145}146```147148Form encoded data can also include multiple values form a given key.149150```python151>>> data = {'key1': ['value1', 'value2']}

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 152why, one step back
152>>> r = httpx.post("https://httpbin.org/post", data=data)

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 153–171why, one step back
153>>> print(r.text)
154{155 ...156 "form": {157 "key1": [158 "value1",159 "value2"160 ]161 },162 ...163}164```165166## Sending Multipart File Uploads167168You can also upload files, using HTTP multipart encoding:169170```python171>>> files = {'upload-file': open('report.xls', 'rb')}

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 172why, one step back
172>>> r = httpx.post("https://httpbin.org/post", files=files)

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 173–187why, one step back
173>>> print(r.text)
174{175 ...176 "files": {177 "upload-file": "<... binary content ...>"178 },179 ...180}181```182183You can also explicitly set the filename and content type, by using a tuple184of items for the file value:185186```python187>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 188why, one step back
188>>> r = httpx.post("https://httpbin.org/post", files=files)

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 189–200why, one step back
189>>> print(r.text)
190{191 ...192 "files": {193 "upload-file": "<... binary content ...>"194 },195 ...196}197```198199## Sending JSON Encoded Data200

Fix typos, spelling issues, and grammar in docs (#426)Kyle Galbraithbefore adoptionb65bce5

line 201why, one step back
201Form encoded data is okay if all you need is a simple key-value data structure.

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 202–205why, one step back
202For more complicated data structures you'll often want to use JSON encoding instead.
203204```python205>>> data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']}

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 206why, one step back
206>>> r = httpx.post("https://httpbin.org/post", json=data)

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 207–224why, one step back
207>>> print(r.text)
208{209 ...210 "json": {211 "boolean": true,212 "integer": 123,213 "list": [214 "a",215 "b",216 "c"217 ]218 },219 ...220}221```222223## Sending Binary Request Data224

Fix typos, spelling issues, and grammar in docs (#426)Kyle Galbraithbefore adoptionb65bce5

line 225why, one step back
225For other encodings, you should use either a `bytes` type or a generator

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 226–235why, one step back
226that yields `bytes`.
227228You'll probably also want to set a custom `Content-Type` header when uploading229binary data.230231## Response Status Codes232233We can inspect the HTTP status code of the response:234235```python

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 236why, one step back
236>>> r = httpx.get('https://httpbin.org/get')

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 237–240why, one step back
237>>> r.status_code
238200239```240

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 241why, one step back
241HTTPX also includes an easy shortcut for accessing status codes by their text phrase.

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 242–243why, one step back
242
243```python

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 244why, one step back
244>>> r.status_code == httpx.codes.OK

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 245–250why, one step back
245True
246```247248We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):249250```python

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 251why, one step back
251>>> not_found = httpx.get('https://httpbin.org/status/404')

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 252–255why, one step back
252>>> not_found.status_code
253404254>>> not_found.raise_for_status()255Traceback (most recent call last):

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 256why, one step back
256 File "/Users/tomchristie/GitHub/encode/httpcore/httpx/models.py", line 776, in raise_for_status

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

line 257why, one step back
257 raise HttpError(message)

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 258why, one step back
258httpx.exceptions.HttpError: 404 Not Found

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 259–293why, one step back
259```
260261Any successful response codes will simply return `None` rather than raising an exception.262263``` python264>>> r.raise_for_status()265```266267## Response Headers268269The response headers are available as a dictionary-like interface.270271```python272>>> r.headers273Headers({274 'content-encoding': 'gzip',275 'transfer-encoding': 'chunked',276 'connection': 'close',277 'server': 'nginx/1.0.4',278 'x-runtime': '148ms',279 'etag': '"e1ca502697e5c9317743dc078f67693f"',280 'content-type': 'application/json'281})282```283284The `Headers` data type is case-insensitive, so you can use any capitalization.285286```python287>>> r.headers['Content-Type']288'application/json'289290>>> r.headers.get('content-type')291'application/json'292```293

Fix typos, spelling issues, and grammar in docs (#426)Kyle Galbraithbefore adoptionb65bce5

line 294why, one step back
294Multiple values for a single response header are represented as a single comma-separated

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 295–296why, one step back
295value, as per [RFC 7230](https://tools.ietf.org/html/rfc7230#section-3.2):
296

Fix typos, spelling issues, and grammar in docs (#426)Kyle Galbraithbefore adoptionb65bce5

line 297why, one step back
297> 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.

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 298–303why, one step back
298
299## Cookies300301Any cookies that are set on the response can be easily accessed:302303```python

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 304why, one step back
304>>> r = httpx.get('http://httpbin.org/cookies/set?chocolate=chip', allow_redirects=False)

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 305–312why, one step back
305>>> r.cookies['chocolate']
306'chip'307```308309To include cookies in an outgoing request, use the `cookies` parameter:310311```python312>>> cookies = {"peanut": "butter"}

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 313why, one step back
313>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 314–321why, one step back
314>>> r.json()
315{'cookies': {'peanut': 'butter'}}316```317318Cookies are returned in a `Cookies` instance, which is a dict-like data structure319with additional API for accessing cookies by their domain or path.320321```python

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 322why, one step back
322>>> cookies = httpx.Cookies()

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 323–324why, one step back
323>>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')
324>>> cookies.set('cookie_off_domain', 'nope.', domain='example.org')

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 325why, one step back
325>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 326–331why, one step back
326>>> r.json()
327{'cookies': {'cookie_on_domain': 'hello, there!'}}328```329330## Redirection and History331

Fix typos, spelling issues, and grammar in docs (#426)Kyle Galbraithbefore adoptionb65bce5

line 332why, one step back
332By default, HTTPX will follow redirects for anything except `HEAD` requests.

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 333–340why, one step back
333
334The `history` property of the response can be used to inspect any followed redirects.335It contains a list of all any redirect responses that were followed, in the order336in which they were made.337338For example, GitHub redirects all HTTP requests to HTTPS.339340```python

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 341why, one step back
341>>> r = httpx.get('http://github.com/')

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 342–352why, one step back
342>>> r.url
343URL('https://github.com/')344>>> r.status_code345200346>>> r.history347[<Response [301 Moved Permanently]>]348```349350You can modify the default redirection handling with the allow_redirects parameter:351352```python

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 353why, one step back
353>>> r = httpx.get('http://github.com/', allow_redirects=False)

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 354–362why, one step back
354>>> r.status_code
355301356>>> r.history357[]358```359360If you’re making a `HEAD` request, you can use this to enable redirection:361362```python

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 363why, one step back
363>>> r = httpx.head('http://github.com/', allow_redirects=True)

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 364–371why, one step back
364>>> r.url
365'https://github.com/'366>>> r.history367[<Response [301 Moved Permanently]>]368```369370## Timeouts371

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 372why, one step back
372HTTPX defaults to including reasonable timeouts for all network operations,

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

lines 373–379why, one step back
373meaning that if a connection is not properly established then it should always
374raise an error rather than hanging indefinitely.375376The default timeout for network inactivity is five seconds. You can modify the377value to be more or less strict:378379```python

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 380why, one step back
380>>> httpx.get('https://github.com/', timeout=0.001)

Fixed response repr. (#101)updatatodaybefore adoptionf9e3ad4

line 381why, one step back
381```

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

line 382why, one step back
382

Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499

lines 383–384why, one step back
383For advanced timeout management, see [Timeout fine-tuning](https://www.encode.io/httpx/advanced/#timeout-fine-tuning).
384

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

lines 385–405why, one step back
385## Authentication
386387HTTPX supports Basic and Digest HTTP authentication.388389To provide Basic authentication credentials, pass a 2-tuple of390plaintext `str` or `bytes` objects as the `auth` argument to the request391functions:392393```python394>>> httpx.get("https://example.com", auth=("my_user", "password123"))395```396397To provide credentials for Digest authentication you'll need to instantiate398a `DigestAuth` object with the plaintext username and password as arguments.399This object can be then passed as the `auth` argument to the request methods400as above:401402```python403>>> auth = httpx.DigestAuth("my_user", "password123")404>>> httpx.get("https://example.com", auth=auth)405<Response [200 OK]>

Fix broken docs (#415)Dustin Ingrambefore adoption5df822c

line 406why, one step back
406```