quickstart.md
This file
Path
docs/quickstart.md
486 lines · 12.3 KiB · Markdown
Last changed by
Drop chardet (#1269)Tom Christiebefore adoptiond0fe113
History of this fileTake 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 back1# QuickStart23First, start by importing HTTPX:4Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 5why, one step back5```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 6–10why, one step back6>>> import httpx7```89Now, let’s try to get a webpage.10Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 11why, one step back11```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 12–18why, one step back12>>> r = httpx.get('https://httpbin.org/get')13>>> r14<Response [200 OK]>15```1617Similarly, to make an HTTP POST request:18Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 19why, one step back19```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 20–24why, one step back20>>> r = httpx.post('https://httpbin.org/post', data={'key': 'value'})21```2223The PUT, DELETE, HEAD, and OPTIONS requests all follow the same style:24Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 25why, one step back25```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 26–35why, 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')30```3132## Passing Parameters in URLs3334To include URL query parameters in the request, use the `params` keyword:35Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 36why, one step back36```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 37–43why, one step back37>>> 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:43Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 44why, one step back44```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 45–50why, one step back45>>> r.url46URL('https://httpbin.org/get?key2=value2&key1=value1')47```4849You can also pass a list of items as a value:50Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 51why, one step back51```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 52–61why, one step back52>>> 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.61Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 62why, one step back62```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 63–67why, one step back63>>> r = httpx.get('https://www.example.org/')64>>> r.text65'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'66```67Drop chardet (#1269)Tom Christiebefore adoptiond0fe113
line 68why, one step back68You can inspect what encoding will be used to decode the response.Add issue templates (#880)Florimond Mancabefore adoption4ef5de4
line 69why, one step back69Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 70why, one step back70```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 71–74why, one step back71>>> r.encoding72'UTF-8'73```74Drop chardet (#1269)Tom Christiebefore adoptiond0fe113
lines 75–88why, one step back75In some cases the response may not contain an explicit encoding, in which case HTTPX76will attempt to automatically determine an encoding to use. This defaults to77UTF-8, but also includes robust fallback behaviour for handling ascii,78iso-8859-1 and windows 1252 encodings.7980```pycon81>>> r.encoding82None83>>> r.text84'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'85```868788If you need to override the standard behaviour and explicitly set the encoding toAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 89–90why, one step back89use, then you can do that too.90Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 91why, one step back91```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 92–98why, one step back92>>> r.encoding = 'ISO-8859-1'93```9495## Binary Response Content9697The response content can also be accessed as bytes, for non-text responses:98Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 99why, one step back99```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 100–109why, one step back100>>> r.content101b'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'102```103104Any `gzip` and `deflate` HTTP response encodings will automatically105be decoded for you. If `brotlipy` is installed, then the `brotli` response106encoding will also be supported.107108For example, to create an image from binary data returned by a request, you can use the following code:109Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 110why, one step back110```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 111–119why, one step back111>>> from PIL import Image112>>> from io import BytesIO113>>> i = Image.open(BytesIO(r.content))114```115116## JSON Response Content117118Often Web API responses will be encoded as JSON.119Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 120why, one step back120```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 121–129why, one step back121>>> r = httpx.get('https://api.github.com/events')122>>> r.json()123[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...' ... }}]124```125126## Custom Headers127128To include additional headers in the outgoing request, use the `headers` keyword argument:129Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 130why, one step back130```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 131–141why, one step back131>>> url = 'http://httpbin.org/headers'132>>> headers = {'user-agent': 'my-app/0.0.1'}133>>> r = httpx.get(url, headers=headers)134```135136## Sending Form Encoded Data137138Some types of HTTP requests, such as `POST` and `PUT` requests, can include data139in the request body. One common way of including that is as form-encoded data,140which is used for HTML forms.141Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 142why, one step back142```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 143–155why, one step back143>>> data = {'key1': 'value1', 'key2': 'value2'}144>>> r = httpx.post("https://httpbin.org/post", data=data)145>>> print(r.text)146{147 ...148 "form": {149 "key2": "value2",150 "key1": "value1"151 },152 ...153}154```155Fix small typo (#920)Ryan Balfanzbefore adoption3b9ebe0
line 156why, one step back156Form encoded data can also include multiple values from a given key.Add issue templates (#880)Florimond Mancabefore adoption4ef5de4
line 157why, one step back157Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 158why, one step back158```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 159–177why, one step back159>>> data = {'key1': ['value1', 'value2']}160>>> r = httpx.post("https://httpbin.org/post", data=data)161>>> print(r.text)162{163 ...164 "form": {165 "key1": [166 "value1",167 "value2"168 ]169 },170 ...171}172```173174## Sending Multipart File Uploads175176You can also upload files, using HTTP multipart encoding:177Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 178why, one step back178```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 179–193why, one step back179>>> files = {'upload-file': open('report.xls', 'rb')}180>>> r = httpx.post("https://httpbin.org/post", files=files)181>>> print(r.text)182{183 ...184 "files": {185 "upload-file": "<... binary content ...>"186 },187 ...188}189```190191You can also explicitly set the filename and content type, by using a tuple192of items for the file value:193Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 194why, one step back194```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 195–206why, one step back195>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}196>>> r = httpx.post("https://httpbin.org/post", files=files)197>>> print(r.text)198{199 ...200 "files": {201 "upload-file": "<... binary content ...>"202 },203 ...204}205```206Add note on data fields in multipart form encoding (#1022)Florimond Mancabefore adoption0f7d644
lines 207–208why, one step back207If you need to include non-file data fields in the multipart form, use the `data=...` parameter:208Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 209why, one step back209```pyconAdd note on data fields in multipart form encoding (#1022)Florimond Mancabefore adoption0f7d644
lines 210–225why, one step back210>>> data = {'message': 'Hello, world!'}211>>> files = {'file': open('report.xls', 'rb')}212>>> r = httpx.post("https://httpbin.org/post", data=data, files=files)213>>> print(r.text)214{215 ...216 "files": {217 "file": "<... binary content ...>"218 },219 "form": {220 "message": "Hello, world!",221 },222 ...223}224```225Add issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 226–230why, one step back226## Sending JSON Encoded Data227228Form encoded data is okay if all you need is a simple key-value data structure.229For more complicated data structures you'll often want to use JSON encoding instead.230Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 231why, one step back231```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 232–261why, one step back232>>> data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']}233>>> r = httpx.post("https://httpbin.org/post", json=data)234>>> print(r.text)235{236 ...237 "json": {238 "boolean": true,239 "integer": 123,240 "list": [241 "a",242 "b",243 "c"244 ]245 },246 ...247}248```249250## Sending Binary Request Data251252For other encodings, you should use either a `bytes` type or a generator253that yields `bytes`.254255You'll probably also want to set a custom `Content-Type` header when uploading256binary data.257258## Response Status Codes259260We can inspect the HTTP status code of the response:261Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 262why, one step back262```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 263–269why, one step back263>>> r = httpx.get('https://httpbin.org/get')264>>> r.status_code265200266```267268HTTPX also includes an easy shortcut for accessing status codes by their text phrase.269Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 270why, one step back270```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 271–276why, one step back271>>> r.status_code == httpx.codes.OK272True273```274275We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):276Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 277why, one step back277```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 278–282why, one step back278>>> not_found = httpx.get('https://httpbin.org/status/404')279>>> not_found.status_code280404281>>> not_found.raise_for_status()282Traceback (most recent call last):Raise HTTPStatusError in raise_from_status (#1072)François Voronbefore adoption27b0dbc
lines 283–286why, one step back283 File "/Users/tomchristie/GitHub/encode/httpcore/httpx/models.py", line 837, in raise_for_status284 raise HTTPStatusError(message, response=self)285httpx._exceptions.HTTPStatusError: 404 Client Error: Not Found for url: https://httpbin.org/status/404286For more information check: https://httpstatuses.com/404Add issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 287–290why, one step back287```288289Any successful response codes will simply return `None` rather than raising an exception.290Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 291why, one step back291```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 292–298why, one step back292>>> r.raise_for_status()293```294295## Response Headers296297The response headers are available as a dictionary-like interface.298Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 299why, one step back299```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 300–313why, one step back300>>> r.headers301Headers({302 'content-encoding': 'gzip',303 'transfer-encoding': 'chunked',304 'connection': 'close',305 'server': 'nginx/1.0.4',306 'x-runtime': '148ms',307 'etag': '"e1ca502697e5c9317743dc078f67693f"',308 'content-type': 'application/json'309})310```311312The `Headers` data type is case-insensitive, so you can use any capitalization.313Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 314why, one step back314```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 315–331why, one step back315>>> r.headers['Content-Type']316'application/json'317318>>> r.headers.get('content-type')319'application/json'320```321322Multiple 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):323324> 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.325326## Streaming Responses327328For large downloads you may want to use streaming responses that do not load the entire response body into memory at once.329330You can stream the binary content of the response...331Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 332why, one step back332```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 333–339why, one step back333>>> with httpx.stream("GET", "https://www.example.com") as r:334... for data in r.iter_bytes():335... print(data)336```337338Or the text of the response...339Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 340why, one step back340```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 341–347why, one step back341>>> with httpx.stream("GET", "https://www.example.com") as r:342... for text in r.iter_text():343... print(text)344```345346Or stream the text, on a line-by-line basis...347Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 348why, one step back348```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 349–357why, one step back349>>> with httpx.stream("GET", "https://www.example.com") as r:350... for line in r.iter_lines():351... print(line)352```353354HTTPX will use universal line endings, normalising all cases to `\n`.355356In 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.357Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 358why, one step back358```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 359–365why, one step back359>>> with httpx.stream("GET", "https://www.example.com") as r:360... for chunk in r.iter_raw():361... print(chunk)362```363364If 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:365Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 366why, one step back366```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 367–376why, one step back367>>> with httpx.stream("GET", "https://www.example.com") as r:368... if r.headers['Content-Length'] < TOO_LONG:369... r.read()370... print(r.text)371```372373## Cookies374375Any cookies that are set on the response can be easily accessed:376Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 377why, one step back377```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 378–384why, one step back378>>> r = httpx.get('http://httpbin.org/cookies/set?chocolate=chip', allow_redirects=False)379>>> r.cookies['chocolate']380'chip'381```382383To include cookies in an outgoing request, use the `cookies` parameter:384Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 385why, one step back385```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 386–394why, one step back386>>> cookies = {"peanut": "butter"}387>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)388>>> r.json()389{'cookies': {'peanut': 'butter'}}390```391392Cookies are returned in a `Cookies` instance, which is a dict-like data structure393with additional API for accessing cookies by their domain or path.394Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 395why, one step back395```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 396–413why, one step back396>>> cookies = httpx.Cookies()397>>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')398>>> cookies.set('cookie_off_domain', 'nope.', domain='example.org')399>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)400>>> r.json()401{'cookies': {'cookie_on_domain': 'hello, there!'}}402```403404## Redirection and History405406By default, HTTPX will follow redirects for anything except `HEAD` requests.407408The `history` property of the response can be used to inspect any followed redirects.409It contains a list of any redirect responses that were followed, in the order410in which they were made.411412For example, GitHub redirects all HTTP requests to HTTPS.413Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 414why, one step back414```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 415–425why, one step back415>>> r = httpx.get('http://github.com/')416>>> r.url417URL('https://github.com/')418>>> r.status_code419200420>>> r.history421[<Response [301 Moved Permanently]>]422```423424You can modify the default redirection handling with the allow_redirects parameter:425Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 426why, one step back426```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 427–435why, one step back427>>> r = httpx.get('http://github.com/', allow_redirects=False)428>>> r.status_code429301430>>> r.history431[]432```433434If you’re making a `HEAD` request, you can use this to enable redirection:435Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 436why, one step back436```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 437–452why, one step back437>>> r = httpx.head('http://github.com/', allow_redirects=True)438>>> r.url439'https://github.com/'440>>> r.history441[<Response [301 Moved Permanently]>]442```443444## Timeouts445446HTTPX defaults to including reasonable timeouts for all network operations,447meaning that if a connection is not properly established then it should always448raise an error rather than hanging indefinitely.449450The default timeout for network inactivity is five seconds. You can modify the451value to be more or less strict:452Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 453why, one step back453```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 454–458why, one step back454>>> httpx.get('https://github.com/', timeout=0.001)455```456457You can also disable the timeout behavior completely...458Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 459why, one step back459```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 460–472why, one step back460>>> httpx.get('https://github.com/', timeout=None)461```462463For advanced timeout management, see [Timeout fine-tuning](advanced.md#fine-tuning-the-configuration).464465## Authentication466467HTTPX supports Basic and Digest HTTP authentication.468469To provide Basic authentication credentials, pass a 2-tuple of470plaintext `str` or `bytes` objects as the `auth` argument to the request471functions:472Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 473why, one step back473```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 474–481why, one step back474>>> httpx.get("https://example.com", auth=("my_user", "password123"))475```476477To provide credentials for Digest authentication you'll need to instantiate478a `DigestAuth` object with the plaintext username and password as arguments.479This object can be then passed as the `auth` argument to the request methods480as above:481Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 482why, one step back482```pyconAdd issue templates (#880)Florimond Mancabefore adoption4ef5de4
lines 483–486why, one step back483>>> auth = httpx.DigestAuth("my_user", "password123")484>>> httpx.get("https://example.com", auth=auth)485<Response [200 OK]>486```