Skip to content
Myr

quickstart.md

This file

Path

docs/quickstart.md

542 lines · 14.1 KiB · Markdown

Last changed by

Fix sections references (#3058)Kar Petrosyanbefore adoption73e6888

History of this file

Take it

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

Drop multipart requirement from tests (#2456)Tom Christiebefore adoption883cf8c

lines 1–287why, 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/404

Use Mozilla documentation instead of `httpstatuses.com` for HTTP error reference (#2768)Zaniebefore adoption18d7721

line 288why, one step back
288For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404

Drop multipart requirement from tests (#2456)Tom Christiebefore adoption883cf8c

lines 289–290why, one step back
289```
290

Make `raise_for_status` chainable (#2776)Trim21before adoption9415af6

line 291why, one step back
291Any successful response codes will return the `Response` instance rather than raising an exception.

Drop multipart requirement from tests (#2456)Tom Christiebefore adoption883cf8c

lines 292–294why, one step back
292
293```pycon294>>> r.raise_for_status()

Make `raise_for_status` chainable (#2776)Trim21before adoption9415af6

lines 295–301why, one step back
295```
296297The method returns the response instance, allowing you to use it inline. For example:298299```pycon300>>> r = httpx.get('...').raise_for_status()301>>> data = httpx.get('...').raise_for_status().json()

Drop multipart requirement from tests (#2456)Tom Christiebefore adoption883cf8c

lines 302–376why, one step back
302```
303304## Response Headers305306The response headers are available as a dictionary-like interface.307308```pycon309>>> r.headers310Headers({311 'content-encoding': 'gzip',312 'transfer-encoding': 'chunked',313 'connection': 'close',314 'server': 'nginx/1.0.4',315 'x-runtime': '148ms',316 'etag': '"e1ca502697e5c9317743dc078f67693f"',317 'content-type': 'application/json'318})319```320321The `Headers` data type is case-insensitive, so you can use any capitalization.322323```pycon324>>> r.headers['Content-Type']325'application/json'326327>>> r.headers.get('content-type')328'application/json'329```330331Multiple 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):332333> 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.334335## Streaming Responses336337For large downloads you may want to use streaming responses that do not load the entire response body into memory at once.338339You can stream the binary content of the response...340341```pycon342>>> with httpx.stream("GET", "https://www.example.com") as r:343... for data in r.iter_bytes():344... print(data)345```346347Or the text of the response...348349```pycon350>>> with httpx.stream("GET", "https://www.example.com") as r:351... for text in r.iter_text():352... print(text)353```354355Or stream the text, on a line-by-line basis...356357```pycon358>>> with httpx.stream("GET", "https://www.example.com") as r:359... for line in r.iter_lines():360... print(line)361```362363HTTPX will use universal line endings, normalising all cases to `\n`.364365In 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.366367```pycon368>>> with httpx.stream("GET", "https://www.example.com") as r:369... for chunk in r.iter_raw():370... print(chunk)371```372373If 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:374375```pycon376>>> with httpx.stream("GET", "https://www.example.com") as r:

Fix sample in quickstart.md (#2747)Johnny Limbefore adoption2e2949c

line 377why, one step back
377... if int(r.headers['Content-Length']) < TOO_LONG:

Drop multipart requirement from tests (#2456)Tom Christiebefore adoption883cf8c

lines 378–464why, one step back
378... r.read()
379... print(r.text)380```381382## Cookies383384Any cookies that are set on the response can be easily accessed:385386```pycon387>>> r = httpx.get('https://httpbin.org/cookies/set?chocolate=chip')388>>> r.cookies['chocolate']389'chip'390```391392To include cookies in an outgoing request, use the `cookies` parameter:393394```pycon395>>> cookies = {"peanut": "butter"}396>>> r = httpx.get('https://httpbin.org/cookies', cookies=cookies)397>>> r.json()398{'cookies': {'peanut': 'butter'}}399```400401Cookies are returned in a `Cookies` instance, which is a dict-like data structure402with additional API for accessing cookies by their domain or path.403404```pycon405>>> cookies = httpx.Cookies()406>>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')407>>> cookies.set('cookie_off_domain', 'nope.', domain='example.org')408>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)409>>> r.json()410{'cookies': {'cookie_on_domain': 'hello, there!'}}411```412413## Redirection and History414415By default, HTTPX will **not** follow redirects for all HTTP methods, although416this can be explicitly enabled.417418For example, GitHub redirects all HTTP requests to HTTPS.419420```pycon421>>> r = httpx.get('http://github.com/')422>>> r.status_code423301424>>> r.history425[]426>>> r.next_request427<Request('GET', 'https://github.com/')>428```429430You can modify the default redirection handling with the `follow_redirects` parameter:431432```pycon433>>> r = httpx.get('http://github.com/', follow_redirects=True)434>>> r.url435URL('https://github.com/')436>>> r.status_code437200438>>> r.history439[<Response [301 Moved Permanently]>]440```441442The `history` property of the response can be used to inspect any followed redirects.443It contains a list of any redirect responses that were followed, in the order444in which they were made.445446## Timeouts447448HTTPX defaults to including reasonable timeouts for all network operations,449meaning that if a connection is not properly established then it should always450raise an error rather than hanging indefinitely.451452The default timeout for network inactivity is five seconds. You can modify the453value to be more or less strict:454455```pycon456>>> httpx.get('https://github.com/', timeout=0.001)457```458459You can also disable the timeout behavior completely...460461```pycon462>>> httpx.get('https://github.com/', timeout=None)463```464

Fix sections references (#3058)Kar Petrosyanbefore adoption73e6888

line 465why, one step back
465For advanced timeout management, see [Timeout fine-tuning](advanced/timeouts.md#fine-tuning-the-configuration).

Drop multipart requirement from tests (#2456)Tom Christiebefore adoption883cf8c

lines 466–542why, one step back
466
467## Authentication468469HTTPX supports Basic and Digest HTTP authentication.470471To provide Basic authentication credentials, pass a 2-tuple of472plaintext `str` or `bytes` objects as the `auth` argument to the request473functions:474475```pycon476>>> httpx.get("https://example.com", auth=("my_user", "password123"))477```478479To provide credentials for Digest authentication you'll need to instantiate480a `DigestAuth` object with the plaintext username and password as arguments.481This object can be then passed as the `auth` argument to the request methods482as above:483484```pycon485>>> auth = httpx.DigestAuth("my_user", "password123")486>>> httpx.get("https://example.com", auth=auth)487<Response [200 OK]>488```489490## Exceptions491492HTTPX will raise exceptions if an error occurs.493494The most important exception classes in HTTPX are `RequestError` and `HTTPStatusError`.495496The `RequestError` class is a superclass that encompasses any exception that occurs497while issuing an HTTP request. These exceptions include a `.request` attribute.498499```python500try:501 response = httpx.get("https://www.example.com/")502except httpx.RequestError as exc:503 print(f"An error occurred while requesting {exc.request.url!r}.")504```505506The `HTTPStatusError` class is raised by `response.raise_for_status()` on responses which are not a 2xx success code.507These exceptions include both a `.request` and a `.response` attribute.508509```python510response = httpx.get("https://www.example.com/")511try:512 response.raise_for_status()513except httpx.HTTPStatusError as exc:514 print(f"Error response {exc.response.status_code} while requesting {exc.request.url!r}.")515```516517There is also a base class `HTTPError` that includes both of these categories, and can be used518to catch either failed requests, or 4xx and 5xx responses.519520You can either use this base class to catch both categories...521522```python523try:524 response = httpx.get("https://www.example.com/")525 response.raise_for_status()526except httpx.HTTPError as exc:527 print(f"Error while requesting {exc.request.url!r}.")528```529530Or handle each case explicitly...531532```python533try:534 response = httpx.get("https://www.example.com/")535 response.raise_for_status()536except httpx.RequestError as exc:537 print(f"An error occurred while requesting {exc.request.url!r}.")538except httpx.HTTPStatusError as exc:539 print(f"Error response {exc.response.status_code} while requesting {exc.request.url!r}.")540```541542For a full list of available exceptions, see [Exceptions (API Reference)](exceptions.md).