Skip to content
Myr

quickstart.md

This file

Path

docs/quickstart.md

459 lines · 11.9 KiB · Markdown

Last changed by

Add aiter methods on response (#610)Tom Christiebefore adoptionec40d04

History of this file

Take it

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 1–3why, one step back
1# QuickStart
23!!! note

Drop sync (#544)Tom Christiebefore adoption206c537

line 4why, one step back
4 The standard Python REPL does not allow top-level async statements.

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

line 5why, one step back
5

Drop sync (#544)Tom Christiebefore adoption206c537

lines 6–8why, one step back
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

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

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

line 10why, one step back
10

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

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 12–17why, one step back
12>>> import httpx
13```1415Now, let’s try to get a webpage.1617```python

Drop sync (#544)Tom Christiebefore adoption206c537

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 19–25why, one step back
19>>> r
20<Response [200 OK]>21```2223Similarly, to make an HTTP POST request:2425```python

Drop sync (#544)Tom Christiebefore adoption206c537

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 27–31why, one step back
27```
2829The PUT, DELETE, HEAD, and OPTIONS requests all follow the same style:3031```python

Drop sync (#544)Tom Christiebefore adoption206c537

lines 32–35why, one step back
32>>> 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')

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 36–43why, one step back
36```
3738## Passing Parameters in URLs3940To include URL query parameters in the request, use the `params` keyword:4142```python43>>> params = {'key1': 'value1', 'key2': 'value2'}

Drop sync (#544)Tom Christiebefore adoption206c537

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 45–58why, one step back
45```
4647To see how the values get encoding into the URL string, we can inspect the48resulting URL that was used to make the request:4950```python51>>> r.url52URL('https://httpbin.org/get?key2=value2&key1=value1')53```5455You can also pass a list of items as a value:5657```python58>>> params = {'key1': 'value1', 'key2': ['value2', 'value3']}

Drop sync (#544)Tom Christiebefore adoption206c537

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

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

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

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

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

Drop sync (#544)Tom Christiebefore adoption206c537

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 70–113why, one step back
70>>> r.text
71'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'72```7374You can inspect what encoding has been used to decode the response.7576```python77>>> r.encoding78'UTF-8'79```8081If you need to override the standard behavior and explicitly set the encoding to82use, then you can do that too.8384```python85>>> r.encoding = 'ISO-8859-1'86```8788## Binary Response Content8990The response content can also be accessed as bytes, for non-text responses:9192```python93>>> r.content94b'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'95```9697Any `gzip` and `deflate` HTTP response encodings will automatically98be decoded for you. If `brotlipy` is installed, then the `brotli` response99encoding will also be supported.100101For example, to create an image from binary data returned by a request, you can use the following code:102103```python104>>> from PIL import Image105>>> from io import BytesIO106>>> i = Image.open(BytesIO(r.content))107```108109## JSON Response Content110111Often Web API responses will be encoded as JSON.112113```python

Drop sync (#544)Tom Christiebefore adoption206c537

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

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

Drop sync (#544)Tom Christiebefore adoption206c537

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 127–131why, one step back
127```
128129## Sending Form Encoded Data130131Some 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 132why, one step back
132in the request body. One common way of including that is as form-encoded data,

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 133–136why, one step back
133which is used for HTML forms.
134135```python136>>> data = {'key1': 'value1', 'key2': 'value2'}

Drop sync (#544)Tom Christiebefore adoption206c537

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

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

Drop sync (#544)Tom Christiebefore adoption206c537

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

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

Drop sync (#544)Tom Christiebefore adoption206c537

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

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

Drop sync (#544)Tom Christiebefore adoption206c537

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

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

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

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

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

Drop sync (#544)Tom Christiebefore adoption206c537

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

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

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

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 227–236why, one step back
227that yields `bytes`.
228229You'll probably also want to set a custom `Content-Type` header when uploading230binary data.231232## Response Status Codes233234We can inspect the HTTP status code of the response:235236```python

Drop sync (#544)Tom Christiebefore adoption206c537

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 238–251why, one step back
238>>> r.status_code
239200240```241242HTTPX also includes an easy shortcut for accessing status codes by their text phrase.243244```python245>>> r.status_code == httpx.codes.OK246True247```248249We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):250251```python

Drop sync (#544)Tom Christiebefore adoption206c537

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 253–294why, one step back
253>>> not_found.status_code
254404255>>> not_found.raise_for_status()256Traceback (most recent call last):257 File "/Users/tomchristie/GitHub/encode/httpcore/httpx/models.py", line 776, in raise_for_status258 raise HttpError(message)259httpx.exceptions.HttpError: 404 Not Found260```261262Any successful response codes will simply return `None` rather than raising an exception.263264``` python265>>> r.raise_for_status()266```267268## Response Headers269270The response headers are available as a dictionary-like interface.271272```python273>>> r.headers274Headers({275 'content-encoding': 'gzip',276 'transfer-encoding': 'chunked',277 'connection': 'close',278 'server': 'nginx/1.0.4',279 'x-runtime': '148ms',280 'etag': '"e1ca502697e5c9317743dc078f67693f"',281 'content-type': 'application/json'282})283```284285The `Headers` data type is case-insensitive, so you can use any capitalization.286287```python288>>> r.headers['Content-Type']289'application/json'290291>>> r.headers.get('content-type')292'application/json'293```294

Add Client.stream() method. (#600)Tom Christiebefore adoption8d8ea8b

line 295why, one step back
295Multiple values for a single response header are represented as a single comma-separated value, as per [RFC 7230](https://tools.ietf.org/html/rfc7230#section-3.2):

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

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

Add Client.stream() method. (#600)Tom Christiebefore adoption8d8ea8b

lines 298–306why, one step back
298
299## Streaming Responses300301For large downloads you may want to use streaming responses that do not load the entire response body into memory at once.302303You can stream the binary content of the response...304305```306>>> async with httpx.stream("GET", "https://www.example.com") as r:

Add aiter methods on response (#610)Tom Christiebefore adoptionec40d04

line 307why, one step back
307... async for data in r.aiter_bytes():

Add Client.stream() method. (#600)Tom Christiebefore adoption8d8ea8b

lines 308–314why, one step back
308... print(data)
309```310311Or the text of the response...312313```314>>> async with httpx.stream("GET", "https://www.example.com") as r:

Add aiter methods on response (#610)Tom Christiebefore adoptionec40d04

line 315why, one step back
315... async for text in r.aiter_text():

Add Client.stream() method. (#600)Tom Christiebefore adoption8d8ea8b

lines 316–322why, one step back
316... print(text)
317```318319Or stream the text, on a line-by-line basis...320321```322>>> async with httpx.stream("GET", "https://www.example.com") as r:

Add aiter methods on response (#610)Tom Christiebefore adoptionec40d04

line 323why, one step back
323... async for line in r.aiter_lines():

Add Client.stream() method. (#600)Tom Christiebefore adoption8d8ea8b

lines 324–332why, one step back
324... print(line)
325```326327HTTPX will use universal line endings, normalising all cases to `\n`.328329In 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.330331```332>>> async with httpx.stream("GET", "https://www.example.com") as r:

Add aiter methods on response (#610)Tom Christiebefore adoptionec40d04

line 333why, one step back
333... async for chunk in r.aiter_raw():

Add Client.stream() method. (#600)Tom Christiebefore adoption8d8ea8b

lines 334–344why, one step back
334... print(chunk)
335```336337If 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:338339```340>>> async with httpx.stream("GET", "https://www.example.com") as r:341... if r.headers['Content-Length'] < TOO_LONG:342... await r.read()343... print(r.text)344```

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 345–350why, one step back
345
346## Cookies347348Any cookies that are set on the response can be easily accessed:349350```python

Drop sync (#544)Tom Christiebefore adoption206c537

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 352–359why, one step back
352>>> r.cookies['chocolate']
353'chip'354```355356To include cookies in an outgoing request, use the `cookies` parameter:357358```python359>>> cookies = {"peanut": "butter"}

Drop sync (#544)Tom Christiebefore adoption206c537

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 361–371why, one step back
361>>> r.json()
362{'cookies': {'peanut': 'butter'}}363```364365Cookies are returned in a `Cookies` instance, which is a dict-like data structure366with additional API for accessing cookies by their domain or path.367368```python369>>> cookies = httpx.Cookies()370>>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')371>>> cookies.set('cookie_off_domain', 'nope.', domain='example.org')

Drop sync (#544)Tom Christiebefore adoption206c537

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 373–378why, one step back
373>>> r.json()
374{'cookies': {'cookie_on_domain': 'hello, there!'}}375```376377## Redirection and History378

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

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 380–387why, one step back
380
381The `history` property of the response can be used to inspect any followed redirects.382It contains a list of all any redirect responses that were followed, in the order383in which they were made.384385For example, GitHub redirects all HTTP requests to HTTPS.386387```python

Drop sync (#544)Tom Christiebefore adoption206c537

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 389–399why, one step back
389>>> r.url
390URL('https://github.com/')391>>> r.status_code392200393>>> r.history394[<Response [301 Moved Permanently]>]395```396397You can modify the default redirection handling with the allow_redirects parameter:398399```python

Drop sync (#544)Tom Christiebefore adoption206c537

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 401–409why, one step back
401>>> r.status_code
402301403>>> r.history404[]405```406407If you’re making a `HEAD` request, you can use this to enable redirection:408409```python

Drop sync (#544)Tom Christiebefore adoption206c537

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 411–426why, one step back
411>>> r.url
412'https://github.com/'413>>> r.history414[<Response [301 Moved Permanently]>]415```416417## Timeouts418419HTTPX defaults to including reasonable timeouts for all network operations,420meaning that if a connection is not properly established then it should always421raise an error rather than hanging indefinitely.422423The default timeout for network inactivity is five seconds. You can modify the424value to be more or less strict:425426```python

Drop sync (#544)Tom Christiebefore adoption206c537

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

line 428why, one step back
428```

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

line 429why, one step back
429

Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20

lines 430–435why, one step back
430You can also disable the timeout behavior completely...
431432```python433>>> await httpx.get('https://github.com/', timeout=None)434```435

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

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

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

lines 438–446why, one step back
438## Authentication
439440HTTPX supports Basic and Digest HTTP authentication.441442To provide Basic authentication credentials, pass a 2-tuple of443plaintext `str` or `bytes` objects as the `auth` argument to the request444functions:445446```python

Drop sync (#544)Tom Christiebefore adoption206c537

line 447why, one step back
447>>> await httpx.get("https://example.com", auth=("my_user", "password123"))

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

lines 448–456why, one step back
448```
449450To provide credentials for Digest authentication you'll need to instantiate451a `DigestAuth` object with the plaintext username and password as arguments.452This object can be then passed as the `auth` argument to the request methods453as above:454455```python456>>> auth = httpx.DigestAuth("my_user", "password123")

Drop sync (#544)Tom Christiebefore adoption206c537

line 457why, one step back
457>>> await httpx.get("https://example.com", auth=auth)

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

line 458why, one step back
458<Response [200 OK]>

Fix broken docs (#415)Dustin Ingrambefore adoption5df822c

line 459why, one step back
459```