Skip to content
Myr

quickstart.md

This file

Path

docs/quickstart.md

481 lines · 12.1 KiB · Markdown

Last changed by

Add cli support (#1855)Tom Christiebefore adoptionee9250d

History of this file

Take it

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

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 1–67why, one step back
1# QuickStart
23First, start by importing HTTPX:45```pycon6>>> import httpx7```89Now, let’s try to get a webpage.1011```pycon12>>> r = httpx.get('https://httpbin.org/get')13>>> r14<Response [200 OK]>15```1617Similarly, to make an HTTP POST request:1819```pycon20>>> r = httpx.post('https://httpbin.org/post', data={'key': 'value'})21```2223The PUT, DELETE, HEAD, and OPTIONS requests all follow the same style:2425```pycon26>>> 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:3536```pycon37>>> 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:4344```pycon45>>> r.url46URL('https://httpbin.org/get?key2=value2&key1=value1')47```4849You can also pass a list of items as a value:5051```pycon52>>> 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.6162```pycon63>>> r = httpx.get('https://www.example.org/')64>>> r.text65'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'66```67

Drop chardet (#1269)Tom Christiebefore adoptiond0fe113

line 68why, one step back
68You can inspect what encoding will be used to decode the response.

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 69–74why, one step back
69
70```pycon71>>> r.encoding72'UTF-8'73```74

Drop chardet (#1269)Tom Christiebefore adoptiond0fe113

line 75why, one step back
75In some cases the response may not contain an explicit encoding, in which case HTTPX

Add cli support (#1855)Tom Christiebefore adoptionee9250d

line 76why, one step back
76will attempt to automatically determine an encoding to use.

Drop chardet (#1269)Tom Christiebefore adoptiond0fe113

lines 77–85why, one step back
77
78```pycon79>>> r.encoding80None81>>> r.text82'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'83```8485If you need to override the standard behaviour and explicitly set the encoding to

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 86–127why, one step back
86use, then you can do that too.
8788```pycon89>>> r.encoding = 'ISO-8859-1'90```9192## Binary Response Content9394The response content can also be accessed as bytes, for non-text responses:9596```pycon97>>> r.content98b'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'99```100101Any `gzip` and `deflate` HTTP response encodings will automatically102be decoded for you. If `brotlipy` is installed, then the `brotli` response103encoding will also be supported.104105For example, to create an image from binary data returned by a request, you can use the following code:106107```pycon108>>> from PIL import Image109>>> from io import BytesIO110>>> i = Image.open(BytesIO(r.content))111```112113## JSON Response Content114115Often Web API responses will be encoded as JSON.116117```pycon118>>> r = httpx.get('https://api.github.com/events')119>>> r.json()120[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...' ... }}]121```122123## Custom Headers124125To include additional headers in the outgoing request, use the `headers` keyword argument:126127```pycon

Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7

line 128why, one step back
128>>> url = 'https://httpbin.org/headers'

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 129–248why, one step back
129>>> headers = {'user-agent': 'my-app/0.0.1'}
130>>> r = httpx.get(url, headers=headers)131```132133## Sending Form Encoded Data134135Some types of HTTP requests, such as `POST` and `PUT` requests, can include data136in the request body. One common way of including that is as form-encoded data,137which is used for HTML forms.138139```pycon140>>> data = {'key1': 'value1', 'key2': 'value2'}141>>> r = httpx.post("https://httpbin.org/post", data=data)142>>> print(r.text)143{144 ...145 "form": {146 "key2": "value2",147 "key1": "value1"148 },149 ...150}151```152153Form encoded data can also include multiple values from a given key.154155```pycon156>>> data = {'key1': ['value1', 'value2']}157>>> r = httpx.post("https://httpbin.org/post", data=data)158>>> print(r.text)159{160 ...161 "form": {162 "key1": [163 "value1",164 "value2"165 ]166 },167 ...168}169```170171## Sending Multipart File Uploads172173You can also upload files, using HTTP multipart encoding:174175```pycon176>>> files = {'upload-file': open('report.xls', 'rb')}177>>> r = httpx.post("https://httpbin.org/post", files=files)178>>> print(r.text)179{180 ...181 "files": {182 "upload-file": "<... binary content ...>"183 },184 ...185}186```187188You can also explicitly set the filename and content type, by using a tuple189of items for the file value:190191```pycon192>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}193>>> r = httpx.post("https://httpbin.org/post", files=files)194>>> print(r.text)195{196 ...197 "files": {198 "upload-file": "<... binary content ...>"199 },200 ...201}202```203204If you need to include non-file data fields in the multipart form, use the `data=...` parameter:205206```pycon207>>> data = {'message': 'Hello, world!'}208>>> files = {'file': open('report.xls', 'rb')}209>>> r = httpx.post("https://httpbin.org/post", data=data, files=files)210>>> print(r.text)211{212 ...213 "files": {214 "file": "<... binary content ...>"215 },216 "form": {217 "message": "Hello, world!",218 },219 ...220}221```222223## Sending JSON Encoded Data224225Form encoded data is okay if all you need is a simple key-value data structure.226For more complicated data structures you'll often want to use JSON encoding instead.227228```pycon229>>> data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']}230>>> r = httpx.post("https://httpbin.org/post", json=data)231>>> print(r.text)232{233 ...234 "json": {235 "boolean": true,236 "integer": 123,237 "list": [238 "a",239 "b",240 "c"241 ]242 },243 ...244}245```246247## Sending Binary Request Data248

Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f

lines 249–250why, one step back
249For other encodings, you should use the `content=...` parameter, passing
250either a `bytes` type or a generator that yields `bytes`.

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

line 251why, one step back
251

Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f

lines 252–257why, one step back
252```pycon
253>>> content = b'Hello, world'254>>> r = httpx.post("https://httpbin.org/post", content=content)255```256257You may also want to set a custom `Content-Type` header when uploading

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 258–259why, one step back
258binary data.
259

Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f

line 260why, one step back
260## Response Status Codes

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 261–276why, one step back
261
262We can inspect the HTTP status code of the response:263264```pycon265>>> r = httpx.get('https://httpbin.org/get')266>>> r.status_code267200268```269270HTTPX also includes an easy shortcut for accessing status codes by their text phrase.271272```pycon273>>> r.status_code == httpx.codes.OK274True275```276

Add cli support (#1855)Tom Christiebefore adoptionee9250d

line 277why, one step back
277We can raise an exception for any responses which are not a 2xx success code:

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 278–379why, one step back
278
279```pycon280>>> not_found = httpx.get('https://httpbin.org/status/404')281>>> not_found.status_code282404283>>> not_found.raise_for_status()284Traceback (most recent call last):285 File "/Users/tomchristie/GitHub/encode/httpcore/httpx/models.py", line 837, in raise_for_status286 raise HTTPStatusError(message, response=self)287httpx._exceptions.HTTPStatusError: 404 Client Error: Not Found for url: https://httpbin.org/status/404288For more information check: https://httpstatuses.com/404289```290291Any successful response codes will simply return `None` rather than raising an exception.292293```pycon294>>> r.raise_for_status()295```296297## Response Headers298299The response headers are available as a dictionary-like interface.300301```pycon302>>> r.headers303Headers({304 'content-encoding': 'gzip',305 'transfer-encoding': 'chunked',306 'connection': 'close',307 'server': 'nginx/1.0.4',308 'x-runtime': '148ms',309 'etag': '"e1ca502697e5c9317743dc078f67693f"',310 'content-type': 'application/json'311})312```313314The `Headers` data type is case-insensitive, so you can use any capitalization.315316```pycon317>>> r.headers['Content-Type']318'application/json'319320>>> r.headers.get('content-type')321'application/json'322```323324Multiple 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):325326> 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.327328## Streaming Responses329330For large downloads you may want to use streaming responses that do not load the entire response body into memory at once.331332You can stream the binary content of the response...333334```pycon335>>> with httpx.stream("GET", "https://www.example.com") as r:336... for data in r.iter_bytes():337... print(data)338```339340Or the text of the response...341342```pycon343>>> with httpx.stream("GET", "https://www.example.com") as r:344... for text in r.iter_text():345... print(text)346```347348Or stream the text, on a line-by-line basis...349350```pycon351>>> with httpx.stream("GET", "https://www.example.com") as r:352... for line in r.iter_lines():353... print(line)354```355356HTTPX will use universal line endings, normalising all cases to `\n`.357358In 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.359360```pycon361>>> with httpx.stream("GET", "https://www.example.com") as r:362... for chunk in r.iter_raw():363... print(chunk)364```365366If 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:367368```pycon369>>> with httpx.stream("GET", "https://www.example.com") as r:370... if r.headers['Content-Length'] < TOO_LONG:371... r.read()372... print(r.text)373```374375## Cookies376377Any cookies that are set on the response can be easily accessed:378379```pycon

Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7

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

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 381–388why, one step back
381>>> r.cookies['chocolate']
382'chip'383```384385To include cookies in an outgoing request, use the `cookies` parameter:386387```pycon388>>> cookies = {"peanut": "butter"}

Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7

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

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 390–407why, one step back
390>>> r.json()
391{'cookies': {'peanut': 'butter'}}392```393394Cookies are returned in a `Cookies` instance, which is a dict-like data structure395with additional API for accessing cookies by their domain or path.396397```pycon398>>> cookies = httpx.Cookies()399>>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')400>>> cookies.set('cookie_off_domain', 'nope.', domain='example.org')401>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)402>>> r.json()403{'cookies': {'cookie_on_domain': 'hello, there!'}}404```405406## Redirection and History407

Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7

lines 408–409why, one step back
408By default, HTTPX will **not** follow redirects for all HTTP methods, although
409this can be explicitly enabled.

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 410–415why, one step back
410
411For example, GitHub redirects all HTTP requests to HTTPS.412413```pycon414>>> r = httpx.get('http://github.com/')415>>> r.status_code

Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7

line 416why, one step back
416301

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

line 417why, one step back
417>>> r.history

Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7

lines 418–420why, one step back
418[]
419>>> r.next_request420<Request('GET', 'https://github.com/')>

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 421–422why, one step back
421```
422

Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7

line 423why, one step back
423You can modify the default redirection handling with the `follow_redirects` parameter:

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 424–425why, one step back
424
425```pycon

Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7

lines 426–428why, one step back
426>>> r = httpx.get('http://github.com/', follow_redirects=True)
427>>> r.url428URL('https://github.com/')

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

line 429why, one step back
429>>> r.status_code

Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7

line 430why, one step back
430200

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

line 431why, one step back
431>>> r.history

Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7

line 432why, one step back
432[<Response [301 Moved Permanently]>]

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

line 433why, one step back
433```

Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7

lines 434–437why, one step back
434
435The `history` property of the response can be used to inspect any followed redirects.436It contains a list of any redirect responses that were followed, in the order437in which they were made.

Issue warning on unclosed `AsyncClient`. (#1197)cdelerbefore adoptiondef9f1c

lines 438–481why, one step back
438
439## Timeouts440441HTTPX defaults to including reasonable timeouts for all network operations,442meaning that if a connection is not properly established then it should always443raise an error rather than hanging indefinitely.444445The default timeout for network inactivity is five seconds. You can modify the446value to be more or less strict:447448```pycon449>>> httpx.get('https://github.com/', timeout=0.001)450```451452You can also disable the timeout behavior completely...453454```pycon455>>> httpx.get('https://github.com/', timeout=None)456```457458For advanced timeout management, see [Timeout fine-tuning](advanced.md#fine-tuning-the-configuration).459460## Authentication461462HTTPX supports Basic and Digest HTTP authentication.463464To provide Basic authentication credentials, pass a 2-tuple of465plaintext `str` or `bytes` objects as the `auth` argument to the request466functions:467468```pycon469>>> httpx.get("https://example.com", auth=("my_user", "password123"))470```471472To provide credentials for Digest authentication you'll need to instantiate473a `DigestAuth` object with the plaintext username and password as arguments.474This object can be then passed as the `auth` argument to the request methods475as above:476477```pycon478>>> auth = httpx.DigestAuth("my_user", "password123")479>>> httpx.get("https://example.com", auth=auth)480<Response [200 OK]>481```