quickstart.md
This file
Path
docs/quickstart.md
482 lines · 12.2 KiB · Markdown
Last changed by
Fix redirect description about HEAD (#1520)laggardkernelbefore adoptionea5ffce
History of this fileTake it
The walk stopped after 200 commits: lines older than f540bd0 point at it.
Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
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```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
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```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
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```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
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```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
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```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
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```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
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```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
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```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
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.Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
line 69why, one step back69Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 70why, one step back70```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
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 toExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
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```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
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```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
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```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
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```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
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```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
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```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 143–157why, 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```155156Form encoded data can also include multiple values from a given key.157Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 158why, one step back158```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
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```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
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```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 195–208why, 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```206207If 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```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 210–230why, 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```225226## 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```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 232–251why, 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 Data251Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
lines 252–253why, one step back252For other encodings, you should use the `content=...` parameter, passing253either a `bytes` type or a generator that yields `bytes`.Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
line 254why, one step back254Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
lines 255–260why, one step back255```pycon256>>> content = b'Hello, world'257>>> r = httpx.post("https://httpbin.org/post", content=content)258```259260You may also want to set a custom `Content-Type` header when uploadingExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 261–262why, one step back261binary data.262Seperate `content=...` and `data=...` parameters (#1266)Tom Christiebefore adoptionfeb404f
line 263why, one step back263## Response Status CodesExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 264–266why, one step back264265We can inspect the HTTP status code of the response:266Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 267why, one step back267```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 268–274why, one step back268>>> r = httpx.get('https://httpbin.org/get')269>>> r.status_code270200271```272273HTTPX also includes an easy shortcut for accessing status codes by their text phrase.274Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 275why, one step back275```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 276–281why, one step back276>>> r.status_code == httpx.codes.OK277True278```279280We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):281Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 282why, one step back282```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 283–295why, one step back283>>> not_found = httpx.get('https://httpbin.org/status/404')284>>> not_found.status_code285404286>>> not_found.raise_for_status()287Traceback (most recent call last):288 File "/Users/tomchristie/GitHub/encode/httpcore/httpx/models.py", line 837, in raise_for_status289 raise HTTPStatusError(message, response=self)290httpx._exceptions.HTTPStatusError: 404 Client Error: Not Found for url: https://httpbin.org/status/404291For more information check: https://httpstatuses.com/404292```293294Any successful response codes will simply return `None` rather than raising an exception.295Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 296why, one step back296```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 297–303why, one step back297>>> r.raise_for_status()298```299300## Response Headers301302The response headers are available as a dictionary-like interface.303Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 304why, one step back304```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 305–318why, one step back305>>> r.headers306Headers({307 'content-encoding': 'gzip',308 'transfer-encoding': 'chunked',309 'connection': 'close',310 'server': 'nginx/1.0.4',311 'x-runtime': '148ms',312 'etag': '"e1ca502697e5c9317743dc078f67693f"',313 'content-type': 'application/json'314})315```316317The `Headers` data type is case-insensitive, so you can use any capitalization.318Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 319why, one step back319```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 320–336why, one step back320>>> r.headers['Content-Type']321'application/json'322323>>> r.headers.get('content-type')324'application/json'325```326327Multiple 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):328329> 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.330331## Streaming Responses332333For large downloads you may want to use streaming responses that do not load the entire response body into memory at once.334335You can stream the binary content of the response...336Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 337why, one step back337```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 338–344why, one step back338>>> with httpx.stream("GET", "https://www.example.com") as r:339... for data in r.iter_bytes():340... print(data)341```342343Or the text of the response...344Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 345why, one step back345```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 346–352why, one step back346>>> with httpx.stream("GET", "https://www.example.com") as r:347... for text in r.iter_text():348... print(text)349```350351Or stream the text, on a line-by-line basis...352Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 353why, one step back353```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 354–362why, one step back354>>> with httpx.stream("GET", "https://www.example.com") as r:355... for line in r.iter_lines():356... print(line)357```358359HTTPX will use universal line endings, normalising all cases to `\n`.360361In 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.362Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 363why, one step back363```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 364–370why, one step back364>>> with httpx.stream("GET", "https://www.example.com") as r:365... for chunk in r.iter_raw():366... print(chunk)367```368369If 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:370Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 371why, one step back371```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 372–381why, one step back372>>> with httpx.stream("GET", "https://www.example.com") as r:373... if r.headers['Content-Length'] < TOO_LONG:374... r.read()375... print(r.text)376```377378## Cookies379380Any cookies that are set on the response can be easily accessed:381Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 382why, one step back382```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 383–389why, one step back383>>> r = httpx.get('http://httpbin.org/cookies/set?chocolate=chip', allow_redirects=False)384>>> r.cookies['chocolate']385'chip'386```387388To include cookies in an outgoing request, use the `cookies` parameter:389Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 390why, one step back390```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 391–399why, one step back391>>> cookies = {"peanut": "butter"}392>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)393>>> r.json()394{'cookies': {'peanut': 'butter'}}395```396397Cookies are returned in a `Cookies` instance, which is a dict-like data structure398with additional API for accessing cookies by their domain or path.399Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 400why, one step back400```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 401–410why, one step back401>>> cookies = httpx.Cookies()402>>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')403>>> cookies.set('cookie_off_domain', 'nope.', domain='example.org')404>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)405>>> r.json()406{'cookies': {'cookie_on_domain': 'hello, there!'}}407```408409## Redirection and History410Fix redirect description about HEAD (#1520)laggardkernelbefore adoptionea5ffce
line 411why, one step back411By default, HTTPX will follow redirects for all HTTP methods.Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
line 412why, one step back412Fix redirect description about HEAD (#1520)laggardkernelbefore adoptionea5ffce
line 413why, one step back413Expand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 414–419why, one step back414The `history` property of the response can be used to inspect any followed redirects.415It contains a list of any redirect responses that were followed, in the order416in which they were made.417418For example, GitHub redirects all HTTP requests to HTTPS.419Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 420why, one step back420```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 421–431why, one step back421>>> r = httpx.get('http://github.com/')422>>> r.url423URL('https://github.com/')424>>> r.status_code425200426>>> r.history427[<Response [301 Moved Permanently]>]428```429430You can modify the default redirection handling with the allow_redirects parameter:431Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 432why, one step back432```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 433–448why, one step back433>>> r = httpx.get('http://github.com/', allow_redirects=False)434>>> r.status_code435301436>>> r.history437[]438```439440## Timeouts441442HTTPX defaults to including reasonable timeouts for all network operations,443meaning that if a connection is not properly established then it should always444raise an error rather than hanging indefinitely.445446The default timeout for network inactivity is five seconds. You can modify the447value to be more or less strict:448Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 449why, one step back449```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 450–454why, one step back450>>> httpx.get('https://github.com/', timeout=0.001)451```452453You can also disable the timeout behavior completely...454Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 455why, one step back455```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 456–468why, one step back456>>> httpx.get('https://github.com/', timeout=None)457```458459For advanced timeout management, see [Timeout fine-tuning](advanced.md#fine-tuning-the-configuration).460461## Authentication462463HTTPX supports Basic and Digest HTTP authentication.464465To provide Basic authentication credentials, pass a 2-tuple of466plaintext `str` or `bytes` objects as the `auth` argument to the request467functions:468Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 469why, one step back469```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 470–477why, one step back470>>> httpx.get("https://example.com", auth=("my_user", "password123"))471```472473To provide credentials for Digest authentication you'll need to instantiate474a `DigestAuth` object with the plaintext username and password as arguments.475This object can be then passed as the `auth` argument to the request methods476as above:477Use pycon for Python console code blocks (#1187)Hugo van Kemenadebefore adoptiond10b7cd
line 478why, one step back478```pyconExpand client docstrings (#1152)Felix Hildénbefore adoptionf540bd0
lines 479–482why, one step back479>>> auth = httpx.DigestAuth("my_user", "password123")480>>> httpx.get("https://example.com", auth=auth)481<Response [200 OK]>482```