Skip to content
Myr

quickstart.md

This file

Path

docs/quickstart.md

472 lines · 11.8 KiB · Markdown

Last changed by

Add note on data fields in multipart form encoding (#1022)Florimond Mancabefore adoption0f7d644

History of this file

Take it

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

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

lines 1–11why, one step back
1# QuickStart
23First, start by importing HTTPX:45```python6>>> import httpx7```89Now, let’s try to get a webpage.1011```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 13–19why, one step back
13>>> r
14<Response [200 OK]>15```1617Similarly, to make an HTTP POST request:1819```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 21–25why, one step back
21```
2223The PUT, DELETE, HEAD, and OPTIONS requests all follow the same style:2425```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 30–37why, one step back
30```
3132## Passing Parameters in URLs3334To include URL query parameters in the request, use the `params` keyword:3536```python37>>> params = {'key1': 'value1', 'key2': 'value2'}

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 39–52why, one step back
39```
4041To see how the values get encoding into the URL string, we can inspect the42resulting URL that was used to make the request:4344```python45>>> r.url46URL('https://httpbin.org/get?key2=value2&key1=value1')47```4849You can also pass a list of items as a value:5051```python52>>> params = {'key1': 'value1', 'key2': ['value2', 'value3']}

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 54–62why, one step back
54>>> r.url
55URL('https://httpbin.org/get?key1=value1&key2=value2&key2=value3')56```5758## Response Content5960HTTPX will automatically handle decoding the response content into Unicode text.6162```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 64–107why, one step back
64>>> r.text
65'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'66```6768You can inspect what encoding has been used to decode the response.6970```python71>>> r.encoding72'UTF-8'73```7475If you need to override the standard behavior and explicitly set the encoding to76use, then you can do that too.7778```python79>>> r.encoding = 'ISO-8859-1'80```8182## Binary Response Content8384The response content can also be accessed as bytes, for non-text responses:8586```python87>>> r.content88b'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'89```9091Any `gzip` and `deflate` HTTP response encodings will automatically92be decoded for you. If `brotlipy` is installed, then the `brotli` response93encoding will also be supported.9495For example, to create an image from binary data returned by a request, you can use the following code:9697```python98>>> from PIL import Image99>>> from io import BytesIO100>>> i = Image.open(BytesIO(r.content))101```102103## JSON Response Content104105Often Web API responses will be encoded as JSON.106107```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 109–119why, one step back
109>>> r.json()
110[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...' ... }}]111```112113## Custom Headers114115To include additional headers in the outgoing request, use the `headers` keyword argument:116117```python118>>> url = 'http://httpbin.org/headers'119>>> headers = {'user-agent': 'my-app/0.0.1'}

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 121–130why, one step back
121```
122123## Sending Form Encoded Data124125Some types of HTTP requests, such as `POST` and `PUT` requests, can include data126in the request body. One common way of including that is as form-encoded data,127which is used for HTML forms.128129```python130>>> data = {'key1': 'value1', 'key2': 'value2'}

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 132–142why, one step back
132>>> print(r.text)
133{134 ...135 "form": {136 "key2": "value2",137 "key1": "value1"138 },139 ...140}141```142

Fix small typo (#920)Ryan Balfanzbefore adoption3b9ebe0

line 143why, one step back
143Form encoded data can also include multiple values from a given key.

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

lines 144–146why, one step back
144
145```python146>>> data = {'key1': ['value1', 'value2']}

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 148–166why, one step back
148>>> print(r.text)
149{150 ...151 "form": {152 "key1": [153 "value1",154 "value2"155 ]156 },157 ...158}159```160161## Sending Multipart File Uploads162163You can also upload files, using HTTP multipart encoding:164165```python166>>> files = {'upload-file': open('report.xls', 'rb')}

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 168–182why, one step back
168>>> print(r.text)
169{170 ...171 "files": {172 "upload-file": "<... binary content ...>"173 },174 ...175}176```177178You can also explicitly set the filename and content type, by using a tuple179of items for the file value:180181```python182>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 184–193why, one step back
184>>> print(r.text)
185{186 ...187 "files": {188 "upload-file": "<... binary content ...>"189 },190 ...191}192```193

Add note on data fields in multipart form encoding (#1022)Florimond Mancabefore adoption0f7d644

lines 194–212why, one step back
194If you need to include non-file data fields in the multipart form, use the `data=...` parameter:
195196```python197>>> data = {'message': 'Hello, world!'}198>>> files = {'file': open('report.xls', 'rb')}199>>> r = httpx.post("https://httpbin.org/post", data=data, files=files)200>>> print(r.text)201{202 ...203 "files": {204 "file": "<... binary content ...>"205 },206 "form": {207 "message": "Hello, world!",208 },209 ...210}211```212

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

lines 213–219why, one step back
213## Sending JSON Encoded Data
214215Form encoded data is okay if all you need is a simple key-value data structure.216For more complicated data structures you'll often want to use JSON encoding instead.217218```python219>>> data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']}

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 221–249why, one step back
221>>> print(r.text)
222{223 ...224 "json": {225 "boolean": true,226 "integer": 123,227 "list": [228 "a",229 "b",230 "c"231 ]232 },233 ...234}235```236237## Sending Binary Request Data238239For other encodings, you should use either a `bytes` type or a generator240that yields `bytes`.241242You'll probably also want to set a custom `Content-Type` header when uploading243binary data.244245## Response Status Codes246247We can inspect the HTTP status code of the response:248249```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 251–264why, one step back
251>>> r.status_code
252200253```254255HTTPX also includes an easy shortcut for accessing status codes by their text phrase.256257```python258>>> r.status_code == httpx.codes.OK259True260```261262We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):263264```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 266–270why, one step back
266>>> not_found.status_code
267404268>>> not_found.raise_for_status()269Traceback (most recent call last):270 File "/Users/tomchristie/GitHub/encode/httpcore/httpx/models.py", line 776, in raise_for_status

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 271–272why, one step back
271 raise HTTPError(message)
272httpx.HTTPError: 404 Not Found

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

lines 273–276why, one step back
273```
274275Any successful response codes will simply return `None` rather than raising an exception.276

Fix syntax highlighting (#757)Francesco Pongiluppibefore adoption7f0e791

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

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

lines 278–317why, one step back
278>>> r.raise_for_status()
279```280281## Response Headers282283The response headers are available as a dictionary-like interface.284285```python286>>> r.headers287Headers({288 'content-encoding': 'gzip',289 'transfer-encoding': 'chunked',290 'connection': 'close',291 'server': 'nginx/1.0.4',292 'x-runtime': '148ms',293 'etag': '"e1ca502697e5c9317743dc078f67693f"',294 'content-type': 'application/json'295})296```297298The `Headers` data type is case-insensitive, so you can use any capitalization.299300```python301>>> r.headers['Content-Type']302'application/json'303304>>> r.headers.get('content-type')305'application/json'306```307308Multiple 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):309310> 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.311312## Streaming Responses313314For large downloads you may want to use streaming responses that do not load the entire response body into memory at once.315316You can stream the binary content of the response...317

Fix syntax highlighting (#757)Francesco Pongiluppibefore adoption7f0e791

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

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 319–320why, one step back
319>>> with httpx.stream("GET", "https://www.example.com") as r:
320... for data in r.iter_bytes():

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

lines 321–325why, one step back
321... print(data)
322```323324Or the text of the response...325

Fix syntax highlighting (#757)Francesco Pongiluppibefore adoption7f0e791

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

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 327–328why, one step back
327>>> with httpx.stream("GET", "https://www.example.com") as r:
328... for text in r.iter_text():

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

lines 329–333why, one step back
329... print(text)
330```331332Or stream the text, on a line-by-line basis...333

Fix syntax highlighting (#757)Francesco Pongiluppibefore adoption7f0e791

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

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 335–336why, one step back
335>>> with httpx.stream("GET", "https://www.example.com") as r:
336... for line in r.iter_lines():

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

lines 337–343why, one step back
337... print(line)
338```339340HTTPX will use universal line endings, normalising all cases to `\n`.341342In 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.343

Fix syntax highlighting (#757)Francesco Pongiluppibefore adoption7f0e791

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

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 345–346why, one step back
345>>> with httpx.stream("GET", "https://www.example.com") as r:
346... for chunk in r.iter_raw():

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

lines 347–351why, one step back
347... print(chunk)
348```349350If 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:351

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

lines 352–353why, one step back
352```python
353>>> with httpx.stream("GET", "https://www.example.com") as r:

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

line 354why, one step back
354... if r.headers['Content-Length'] < TOO_LONG:

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

line 355why, one step back
355... r.read()

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

lines 356–363why, one step back
356... print(r.text)
357```358359## Cookies360361Any cookies that are set on the response can be easily accessed:362363```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 365–372why, one step back
365>>> r.cookies['chocolate']
366'chip'367```368369To include cookies in an outgoing request, use the `cookies` parameter:370371```python372>>> cookies = {"peanut": "butter"}

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 374–384why, one step back
374>>> r.json()
375{'cookies': {'peanut': 'butter'}}376```377378Cookies are returned in a `Cookies` instance, which is a dict-like data structure379with additional API for accessing cookies by their domain or path.380381```python382>>> cookies = httpx.Cookies()383>>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')384>>> cookies.set('cookie_off_domain', 'nope.', domain='example.org')

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 386–394why, one step back
386>>> r.json()
387{'cookies': {'cookie_on_domain': 'hello, there!'}}388```389390## Redirection and History391392By default, HTTPX will follow redirects for anything except `HEAD` requests.393394The `history` property of the response can be used to inspect any followed redirects.

Fix typo in 'Redirection and History' docs (#719)Florimond Mancabefore adoptionff44d2d

line 395why, one step back
395It contains a list of any redirect responses that were followed, in the order

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

lines 396–400why, one step back
396in which they were made.
397398For example, GitHub redirects all HTTP requests to HTTPS.399400```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 402–412why, one step back
402>>> r.url
403URL('https://github.com/')404>>> r.status_code405200406>>> r.history407[<Response [301 Moved Permanently]>]408```409410You can modify the default redirection handling with the allow_redirects parameter:411412```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 414–422why, one step back
414>>> r.status_code
415301416>>> r.history417[]418```419420If you’re making a `HEAD` request, you can use this to enable redirection:421422```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 424–439why, one step back
424>>> r.url
425'https://github.com/'426>>> r.history427[<Response [301 Moved Permanently]>]428```429430## Timeouts431432HTTPX defaults to including reasonable timeouts for all network operations,433meaning that if a connection is not properly established then it should always434raise an error rather than hanging indefinitely.435436The default timeout for network inactivity is five seconds. You can modify the437value to be more or less strict:438439```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 441–445why, one step back
441```
442443You can also disable the timeout behavior completely...444445```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 447–448why, one step back
447```
448

Use www.python-httpx.org domainTom Christiebefore adoptionb932d94

line 449why, one step back
449For advanced timeout management, see [Timeout fine-tuning](advanced.md#fine-tuning-the-configuration).

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

lines 450–459why, one step back
450
451## Authentication452453HTTPX supports Basic and Digest HTTP authentication.454455To provide Basic authentication credentials, pass a 2-tuple of456plaintext `str` or `bytes` objects as the `auth` argument to the request457functions:458459```python

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 461–469why, one step back
461```
462463To provide credentials for Digest authentication you'll need to instantiate464a `DigestAuth` object with the plaintext username and password as arguments.465This object can be then passed as the `auth` argument to the request methods466as above:467468```python469>>> auth = httpx.DigestAuth("my_user", "password123")

Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919

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

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

lines 471–472why, one step back
471<Response [200 OK]>
472```