Skip to content
Myr

quickstart.md

This file

Path

docs/quickstart.md

535 lines · 13.9 KiB · Markdown

Last changed by

Rework docs structure (#2308)Florimond Mancabefore adoption3a82176

History of this file

Take it

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

Update stale.yml (#2150)Tom Christiebefore adoption4747c31

lines 1–481why, 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```6768You can inspect what encoding will be used to decode the response.6970```pycon71>>> r.encoding72'UTF-8'73```7475In some cases the response may not contain an explicit encoding, in which case HTTPX76will attempt to automatically determine an encoding to use.7778```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 to86use, 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```pycon128>>> url = 'https://httpbin.org/headers'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 Data248249For other encodings, you should use the `content=...` parameter, passing250either a `bytes` type or a generator that yields `bytes`.251252```pycon253>>> 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 uploading258binary data.259260## Response Status Codes261262We 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```276277We can raise an exception for any responses which are not a 2xx success code:278279```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```pycon380>>> r = httpx.get('https://httpbin.org/cookies/set?chocolate=chip')381>>> r.cookies['chocolate']382'chip'383```384385To include cookies in an outgoing request, use the `cookies` parameter:386387```pycon388>>> cookies = {"peanut": "butter"}389>>> r = httpx.get('https://httpbin.org/cookies', cookies=cookies)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 History407408By default, HTTPX will **not** follow redirects for all HTTP methods, although409this can be explicitly enabled.410411For example, GitHub redirects all HTTP requests to HTTPS.412413```pycon414>>> r = httpx.get('http://github.com/')415>>> r.status_code416301417>>> r.history418[]419>>> r.next_request420<Request('GET', 'https://github.com/')>421```422423You can modify the default redirection handling with the `follow_redirects` parameter:424425```pycon426>>> r = httpx.get('http://github.com/', follow_redirects=True)427>>> r.url428URL('https://github.com/')429>>> r.status_code430200431>>> r.history432[<Response [301 Moved Permanently]>]433```434435The `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.438439## 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```

Rework docs structure (#2308)Florimond Mancabefore adoption3a82176

lines 482–535why, one step back
482
483## Exceptions484485HTTPX will raise exceptions if an error occurs.486487The most important exception classes in HTTPX are `RequestError` and `HTTPStatusError`.488489The `RequestError` class is a superclass that encompasses any exception that occurs490while issuing an HTTP request. These exceptions include a `.request` attribute.491492```python493try:494 response = httpx.get("https://www.example.com/")495except httpx.RequestError as exc:496 print(f"An error occurred while requesting {exc.request.url!r}.")497```498499The `HTTPStatusError` class is raised by `response.raise_for_status()` on responses which are not a 2xx success code.500These exceptions include both a `.request` and a `.response` attribute.501502```python503response = httpx.get("https://www.example.com/")504try:505 response.raise_for_status()506except httpx.HTTPStatusError as exc:507 print(f"Error response {exc.response.status_code} while requesting {exc.request.url!r}.")508```509510There is also a base class `HTTPError` that includes both of these categories, and can be used511to catch either failed requests, or 4xx and 5xx responses.512513You can either use this base class to catch both categories...514515```python516try:517 response = httpx.get("https://www.example.com/")518 response.raise_for_status()519except httpx.HTTPError as exc:520 print(f"Error while requesting {exc.request.url!r}.")521```522523Or handle each case explicitly...524525```python526try:527 response = httpx.get("https://www.example.com/")528 response.raise_for_status()529except httpx.RequestError as exc:530 print(f"An error occurred while requesting {exc.request.url!r}.")531except httpx.HTTPStatusError as exc:532 print(f"Error response {exc.response.status_code} while requesting {exc.request.url!r}.")533```534535For a full list of available exceptions, see [Exceptions (API Reference)](exceptions.md).