quickstart.md
This file
Path
docs/quickstart.md
453 lines · 11.4 KiB · Markdown
Last changed by
Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
History of this fileTake it
The walk stopped after 200 commits: lines older than c38fd68 point at it.
Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 1–11why, one step back1# QuickStart23First, start by importing HTTPX:45```python6>>> import httpx7```89Now, let’s try to get a webpage.1011```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 12why, one step back12>>> r = httpx.get('https://httpbin.org/get')Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 13–19why, one step back13>>> r14<Response [200 OK]>15```1617Similarly, to make an HTTP POST request:1819```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 20why, one step back20>>> r = httpx.post('https://httpbin.org/post', data={'key': 'value'})Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 21–25why, one step back21```2223The PUT, DELETE, HEAD, and OPTIONS requests all follow the same style:2425```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 26–29why, one step back26>>> 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')Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 30–37why, one step back30```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 back38>>> r = httpx.get('https://httpbin.org/get', params=params)Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 39–52why, one step back39```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 back53>>> r = httpx.get('https://httpbin.org/get', params=params)Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 54–62why, one step back54>>> 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.6162```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 63why, one step back63>>> r = httpx.get('https://www.example.org/')Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 64–107why, one step back64>>> 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.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```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 108why, one step back108>>> r = httpx.get('https://api.github.com/events')Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 109–119why, one step back109>>> 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 back120>>> r = httpx.get(url, headers=headers)Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 121–130why, one step back121```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 back131>>> r = httpx.post("https://httpbin.org/post", data=data)Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 132–142why, one step back132>>> print(r.text)133{134 ...135 "form": {136 "key2": "value2",137 "key1": "value1"138 },139 ...140}141```142Fix small typo (#920)Ryan Balfanzbefore adoption3b9ebe0
line 143why, one step back143Form encoded data can also include multiple values from a given key.Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 144–146why, one step back144145```python146>>> data = {'key1': ['value1', 'value2']}Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 147why, one step back147>>> r = httpx.post("https://httpbin.org/post", data=data)Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 148–166why, one step back148>>> 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 back167>>> r = httpx.post("https://httpbin.org/post", files=files)Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 168–182why, one step back168>>> 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 back183>>> r = httpx.post("https://httpbin.org/post", files=files)Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 184–200why, one step back184>>> print(r.text)185{186 ...187 "files": {188 "upload-file": "<... binary content ...>"189 },190 ...191}192```193194## Sending JSON Encoded Data195196Form encoded data is okay if all you need is a simple key-value data structure.197For more complicated data structures you'll often want to use JSON encoding instead.198199```python200>>> data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']}Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 201why, one step back201>>> r = httpx.post("https://httpbin.org/post", json=data)Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 202–230why, one step back202>>> print(r.text)203{204 ...205 "json": {206 "boolean": true,207 "integer": 123,208 "list": [209 "a",210 "b",211 "c"212 ]213 },214 ...215}216```217218## Sending Binary Request Data219220For other encodings, you should use either a `bytes` type or a generator221that yields `bytes`.222223You'll probably also want to set a custom `Content-Type` header when uploading224binary data.225226## Response Status Codes227228We can inspect the HTTP status code of the response:229230```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 231why, one step back231>>> r = httpx.get('https://httpbin.org/get')Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 232–245why, one step back232>>> r.status_code233200234```235236HTTPX also includes an easy shortcut for accessing status codes by their text phrase.237238```python239>>> r.status_code == httpx.codes.OK240True241```242243We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):244245```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 246why, one step back246>>> not_found = httpx.get('https://httpbin.org/status/404')Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 247–251why, one step back247>>> not_found.status_code248404249>>> not_found.raise_for_status()250Traceback (most recent call last):251 File "/Users/tomchristie/GitHub/encode/httpcore/httpx/models.py", line 776, in raise_for_statusIncrease test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
lines 252–253why, one step back252 raise HTTPError(message)253httpx.HTTPError: 404 Not FoundDrop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 254–257why, one step back254```255256Any successful response codes will simply return `None` rather than raising an exception.257Fix syntax highlighting (#757)Francesco Pongiluppibefore adoption7f0e791
line 258why, one step back258```pythonDrop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 259–298why, one step back259>>> r.raise_for_status()260```261262## Response Headers263264The response headers are available as a dictionary-like interface.265266```python267>>> r.headers268Headers({269 'content-encoding': 'gzip',270 'transfer-encoding': 'chunked',271 'connection': 'close',272 'server': 'nginx/1.0.4',273 'x-runtime': '148ms',274 'etag': '"e1ca502697e5c9317743dc078f67693f"',275 'content-type': 'application/json'276})277```278279The `Headers` data type is case-insensitive, so you can use any capitalization.280281```python282>>> r.headers['Content-Type']283'application/json'284285>>> r.headers.get('content-type')286'application/json'287```288289Multiple 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):290291> 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.292293## Streaming Responses294295For large downloads you may want to use streaming responses that do not load the entire response body into memory at once.296297You can stream the binary content of the response...298Fix syntax highlighting (#757)Francesco Pongiluppibefore adoption7f0e791
line 299why, one step back299```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 300–301why, one step back300>>> with httpx.stream("GET", "https://www.example.com") as r:301... for data in r.iter_bytes():Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 302–306why, one step back302... print(data)303```304305Or the text of the response...306Fix syntax highlighting (#757)Francesco Pongiluppibefore adoption7f0e791
line 307why, one step back307```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 308–309why, one step back308>>> with httpx.stream("GET", "https://www.example.com") as r:309... for text in r.iter_text():Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 310–314why, one step back310... print(text)311```312313Or stream the text, on a line-by-line basis...314Fix syntax highlighting (#757)Francesco Pongiluppibefore adoption7f0e791
line 315why, one step back315```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 316–317why, one step back316>>> with httpx.stream("GET", "https://www.example.com") as r:317... for line in r.iter_lines():Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 318–324why, one step back318... print(line)319```320321HTTPX will use universal line endings, normalising all cases to `\n`.322323In 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.324Fix syntax highlighting (#757)Francesco Pongiluppibefore adoption7f0e791
line 325why, one step back325```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 326–327why, one step back326>>> with httpx.stream("GET", "https://www.example.com") as r:327... for chunk in r.iter_raw():Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 328–332why, one step back328... print(chunk)329```330331If 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:332Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 333–334why, one step back333```python334>>> with httpx.stream("GET", "https://www.example.com") as r:Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
line 335why, one step back335... if r.headers['Content-Length'] < TOO_LONG:Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 336why, one step back336... r.read()Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 337–344why, one step back337... print(r.text)338```339340## Cookies341342Any cookies that are set on the response can be easily accessed:343344```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 345why, one step back345>>> r = httpx.get('http://httpbin.org/cookies/set?chocolate=chip', allow_redirects=False)Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 346–353why, one step back346>>> r.cookies['chocolate']347'chip'348```349350To include cookies in an outgoing request, use the `cookies` parameter:351352```python353>>> cookies = {"peanut": "butter"}Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 354why, one step back354>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 355–365why, one step back355>>> r.json()356{'cookies': {'peanut': 'butter'}}357```358359Cookies are returned in a `Cookies` instance, which is a dict-like data structure360with additional API for accessing cookies by their domain or path.361362```python363>>> cookies = httpx.Cookies()364>>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')365>>> cookies.set('cookie_off_domain', 'nope.', domain='example.org')Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 366why, one step back366>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 367–375why, one step back367>>> r.json()368{'cookies': {'cookie_on_domain': 'hello, there!'}}369```370371## Redirection and History372373By default, HTTPX will follow redirects for anything except `HEAD` requests.374375The `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 376why, one step back376It contains a list of any redirect responses that were followed, in the orderDrop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 377–381why, one step back377in which they were made.378379For example, GitHub redirects all HTTP requests to HTTPS.380381```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 382why, one step back382>>> r = httpx.get('http://github.com/')Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 383–393why, one step back383>>> r.url384URL('https://github.com/')385>>> r.status_code386200387>>> r.history388[<Response [301 Moved Permanently]>]389```390391You can modify the default redirection handling with the allow_redirects parameter:392393```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 394why, one step back394>>> r = httpx.get('http://github.com/', allow_redirects=False)Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 395–403why, one step back395>>> r.status_code396301397>>> r.history398[]399```400401If you’re making a `HEAD` request, you can use this to enable redirection:402403```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 404why, one step back404>>> r = httpx.head('http://github.com/', allow_redirects=True)Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 405–420why, one step back405>>> r.url406'https://github.com/'407>>> r.history408[<Response [301 Moved Permanently]>]409```410411## Timeouts412413HTTPX defaults to including reasonable timeouts for all network operations,414meaning that if a connection is not properly established then it should always415raise an error rather than hanging indefinitely.416417The default timeout for network inactivity is five seconds. You can modify the418value to be more or less strict:419420```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 421why, one step back421>>> httpx.get('https://github.com/', timeout=0.001)Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 422–426why, one step back422```423424You can also disable the timeout behavior completely...425426```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 427why, one step back427>>> httpx.get('https://github.com/', timeout=None)Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 428–429why, one step back428```429Use www.python-httpx.org domainTom Christiebefore adoptionb932d94
line 430why, one step back430For advanced timeout management, see [Timeout fine-tuning](advanced.md#fine-tuning-the-configuration).Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 431–440why, one step back431432## Authentication433434HTTPX supports Basic and Digest HTTP authentication.435436To provide Basic authentication credentials, pass a 2-tuple of437plaintext `str` or `bytes` objects as the `auth` argument to the request438functions:439440```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 441why, one step back441>>> httpx.get("https://example.com", auth=("my_user", "password123"))Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 442–450why, one step back442```443444To provide credentials for Digest authentication you'll need to instantiate445a `DigestAuth` object with the plaintext username and password as arguments.446This object can be then passed as the `auth` argument to the request methods447as above:448449```python450>>> auth = httpx.DigestAuth("my_user", "password123")Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 451why, one step back451>>> httpx.get("https://example.com", auth=auth)Drop BackgroundManager in favor of fork(func1, func2) (#603)Florimond Mancabefore adoptionc38fd68
lines 452–453why, one step back452<Response [200 OK]>453```