Skip to content
Myr

quickstart.md

This file

Path

docs/quickstart.md

473 lines · 11.9 KiB · Markdown

Last changed by

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

History of this file

Take it

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

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 1–4why, one step back
1# QuickStart
23First, start by importing HTTPX:4

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 5why, one step back
5```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 6–10why, one step back
6>>> import httpx
7```89Now, let’s try to get a webpage.10

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

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

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 12–18why, one step back
12>>> r = httpx.get('https://httpbin.org/get')
13>>> r14<Response [200 OK]>15```1617Similarly, to make an HTTP POST request:18

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 19why, one step back
19```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 20–24why, one step back
20>>> r = httpx.post('https://httpbin.org/post', data={'key': 'value'})
21```2223The PUT, DELETE, HEAD, and OPTIONS requests all follow the same style:24

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 25why, one step back
25```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 26–35why, 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')30```3132## Passing Parameters in URLs3334To include URL query parameters in the request, use the `params` keyword:35

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 36why, one step back
36```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 37–43why, one step back
37>>> params = {'key1': 'value1', 'key2': 'value2'}
38>>> r = httpx.get('https://httpbin.org/get', params=params)39```4041To see how the values get encoding into the URL string, we can inspect the42resulting URL that was used to make the request:43

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 44why, one step back
44```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 45–50why, one step back
45>>> r.url
46URL('https://httpbin.org/get?key2=value2&key1=value1')47```4849You can also pass a list of items as a value:50

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 51why, one step back
51```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 52–61why, one step back
52>>> params = {'key1': 'value1', 'key2': ['value2', 'value3']}
53>>> r = httpx.get('https://httpbin.org/get', params=params)54>>> r.url55URL('https://httpbin.org/get?key1=value1&key2=value2&key2=value3')56```5758## Response Content5960HTTPX will automatically handle decoding the response content into Unicode text.61

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 62why, one step back
62```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 63–69why, one step back
63>>> r = httpx.get('https://www.example.org/')
64>>> r.text65'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'66```6768You can inspect what encoding has been used to decode the response.69

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 70why, one step back
70```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 71–77why, one step back
71>>> r.encoding
72'UTF-8'73```7475If you need to override the standard behavior and explicitly set the encoding to76use, then you can do that too.77

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 78why, one step back
78```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 79–85why, one step back
79>>> r.encoding = 'ISO-8859-1'
80```8182## Binary Response Content8384The response content can also be accessed as bytes, for non-text responses:85

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 86why, one step back
86```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 87–96why, one step back
87>>> r.content
88b'<!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:96

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 97why, one step back
97```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 98–106why, one step back
98>>> from PIL import Image
99>>> from io import BytesIO100>>> i = Image.open(BytesIO(r.content))101```102103## JSON Response Content104105Often Web API responses will be encoded as JSON.106

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 107why, one step back
107```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 108–116why, one step back
108>>> r = httpx.get('https://api.github.com/events')
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:116

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 117why, one step back
117```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 118–128why, one step back
118>>> url = 'http://httpbin.org/headers'
119>>> headers = {'user-agent': 'my-app/0.0.1'}120>>> r = httpx.get(url, headers=headers)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.128

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 129why, one step back
129```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 130–142why, one step back
130>>> data = {'key1': 'value1', 'key2': 'value2'}
131>>> r = httpx.post("https://httpbin.org/post", data=data)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 issue templates (#880)Florimond Mancabefore adoption4ef5de4

line 144why, one step back
144

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 145why, one step back
145```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 146–164why, one step back
146>>> data = {'key1': ['value1', 'value2']}
147>>> r = httpx.post("https://httpbin.org/post", data=data)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:164

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 165why, one step back
165```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 166–180why, one step back
166>>> files = {'upload-file': open('report.xls', 'rb')}
167>>> r = httpx.post("https://httpbin.org/post", files=files)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:180

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 181why, one step back
181```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 182–193why, one step back
182>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}
183>>> r = httpx.post("https://httpbin.org/post", files=files)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–195why, one step back
194If you need to include non-file data fields in the multipart form, use the `data=...` parameter:
195

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 196why, one step back
196```pycon

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

lines 197–212why, one step back
197>>> 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 issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 213–217why, 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.217

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 218why, one step back
218```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 219–248why, one step back
219>>> data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']}
220>>> r = httpx.post("https://httpbin.org/post", json=data)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:248

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 249why, one step back
249```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 250–256why, one step back
250>>> r = httpx.get('https://httpbin.org/get')
251>>> r.status_code252200253```254255HTTPX also includes an easy shortcut for accessing status codes by their text phrase.256

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 257why, one step back
257```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 258–263why, one step back
258>>> r.status_code == httpx.codes.OK
259True260```261262We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):263

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 264why, one step back
264```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 265–269why, one step back
265>>> not_found = httpx.get('https://httpbin.org/status/404')
266>>> not_found.status_code267404268>>> not_found.raise_for_status()269Traceback (most recent call last):

Raise HTTPStatusError in raise_from_status (#1072)François Voronbefore adoption27b0dbc

lines 270–273why, one step back
270 File "/Users/tomchristie/GitHub/encode/httpcore/httpx/models.py", line 837, in raise_for_status
271 raise HTTPStatusError(message, response=self)272httpx._exceptions.HTTPStatusError: 404 Client Error: Not Found for url: https://httpbin.org/status/404273For more information check: https://httpstatuses.com/404

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 274–277why, one step back
274```
275276Any successful response codes will simply return `None` rather than raising an exception.277

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 278why, one step back
278```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 279–285why, one step back
279>>> r.raise_for_status()
280```281282## Response Headers283284The response headers are available as a dictionary-like interface.285

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 286why, one step back
286```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 287–300why, one step back
287>>> r.headers
288Headers({289 'content-encoding': 'gzip',290 'transfer-encoding': 'chunked',291 'connection': 'close',292 'server': 'nginx/1.0.4',293 'x-runtime': '148ms',294 'etag': '"e1ca502697e5c9317743dc078f67693f"',295 'content-type': 'application/json'296})297```298299The `Headers` data type is case-insensitive, so you can use any capitalization.300

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 301why, one step back
301```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 302–318why, one step back
302>>> r.headers['Content-Type']
303'application/json'304305>>> r.headers.get('content-type')306'application/json'307```308309Multiple 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):310311> 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.312313## Streaming Responses314315For large downloads you may want to use streaming responses that do not load the entire response body into memory at once.316317You can stream the binary content of the response...318

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 319why, one step back
319```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 320–326why, one step back
320>>> with httpx.stream("GET", "https://www.example.com") as r:
321... for data in r.iter_bytes():322... print(data)323```324325Or the text of the response...326

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 327why, one step back
327```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 328–334why, one step back
328>>> with httpx.stream("GET", "https://www.example.com") as r:
329... for text in r.iter_text():330... print(text)331```332333Or stream the text, on a line-by-line basis...334

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 335why, one step back
335```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 336–344why, one step back
336>>> with httpx.stream("GET", "https://www.example.com") as r:
337... for line in r.iter_lines():338... print(line)339```340341HTTPX will use universal line endings, normalising all cases to `\n`.342343In 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.344

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 345why, one step back
345```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 346–352why, one step back
346>>> with httpx.stream("GET", "https://www.example.com") as r:
347... for chunk in r.iter_raw():348... print(chunk)349```350351If 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:352

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 353why, one step back
353```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 354–363why, one step back
354>>> with httpx.stream("GET", "https://www.example.com") as r:
355... if r.headers['Content-Length'] < TOO_LONG:356... r.read()357... print(r.text)358```359360## Cookies361362Any cookies that are set on the response can be easily accessed:363

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 364why, one step back
364```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 365–371why, one step back
365>>> r = httpx.get('http://httpbin.org/cookies/set?chocolate=chip', allow_redirects=False)
366>>> r.cookies['chocolate']367'chip'368```369370To include cookies in an outgoing request, use the `cookies` parameter:371

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 372why, one step back
372```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 373–381why, one step back
373>>> cookies = {"peanut": "butter"}
374>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)375>>> r.json()376{'cookies': {'peanut': 'butter'}}377```378379Cookies are returned in a `Cookies` instance, which is a dict-like data structure380with additional API for accessing cookies by their domain or path.381

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 382why, one step back
382```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 383–400why, one step back
383>>> cookies = httpx.Cookies()
384>>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')385>>> cookies.set('cookie_off_domain', 'nope.', domain='example.org')386>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)387>>> r.json()388{'cookies': {'cookie_on_domain': 'hello, there!'}}389```390391## Redirection and History392393By default, HTTPX will follow redirects for anything except `HEAD` requests.394395The `history` property of the response can be used to inspect any followed redirects.396It contains a list of any redirect responses that were followed, in the order397in which they were made.398399For example, GitHub redirects all HTTP requests to HTTPS.400

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 401why, one step back
401```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 402–412why, one step back
402>>> r = httpx.get('http://github.com/')
403>>> r.url404URL('https://github.com/')405>>> r.status_code406200407>>> r.history408[<Response [301 Moved Permanently]>]409```410411You can modify the default redirection handling with the allow_redirects parameter:412

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 413why, one step back
413```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 414–422why, one step back
414>>> r = httpx.get('http://github.com/', allow_redirects=False)
415>>> r.status_code416301417>>> r.history418[]419```420421If you’re making a `HEAD` request, you can use this to enable redirection:422

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 423why, one step back
423```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 424–439why, one step back
424>>> r = httpx.head('http://github.com/', allow_redirects=True)
425>>> r.url426'https://github.com/'427>>> r.history428[<Response [301 Moved Permanently]>]429```430431## Timeouts432433HTTPX defaults to including reasonable timeouts for all network operations,434meaning that if a connection is not properly established then it should always435raise an error rather than hanging indefinitely.436437The default timeout for network inactivity is five seconds. You can modify the438value to be more or less strict:439

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 440why, one step back
440```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 441–445why, one step back
441>>> httpx.get('https://github.com/', timeout=0.001)
442```443444You can also disable the timeout behavior completely...445

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 446why, one step back
446```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 447–459why, one step back
447>>> httpx.get('https://github.com/', timeout=None)
448```449450For advanced timeout management, see [Timeout fine-tuning](advanced.md#fine-tuning-the-configuration).451452## Authentication453454HTTPX supports Basic and Digest HTTP authentication.455456To provide Basic authentication credentials, pass a 2-tuple of457plaintext `str` or `bytes` objects as the `auth` argument to the request458functions:459

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 460why, one step back
460```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 461–468why, one step back
461>>> httpx.get("https://example.com", auth=("my_user", "password123"))
462```463464To provide credentials for Digest authentication you'll need to instantiate465a `DigestAuth` object with the plaintext username and password as arguments.466This object can be then passed as the `auth` argument to the request methods467as above:468

Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd

line 469why, one step back
469```pycon

Add issue templates (#880)Florimond Mancabefore adoption4ef5de4

lines 470–473why, one step back
470>>> auth = httpx.DigestAuth("my_user", "password123")
471>>> httpx.get("https://example.com", auth=auth)472<Response [200 OK]>473```