Skip to content
Myr

quickstart.md

This file

Path

docs/quickstart.md

547 lines · 14.4 KiB · Markdown

Last changed by

Fixed a syntax error in the file upload example (#3692)ZProgerbefore adoptiondef4778

History of this file

Take it

Show it rendered

1# QuickStart23First, 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 be supported. If `zstandard` is installed, then `zstd`104response encodings will also be supported.105106For example, to create an image from binary data returned by a request, you can use the following code:107108```pycon109>>> from PIL import Image110>>> from io import BytesIO111>>> i = Image.open(BytesIO(r.content))112```113114## JSON Response Content115116Often Web API responses will be encoded as JSON.117118```pycon119>>> r = httpx.get('https://api.github.com/events')120>>> r.json()121[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...' ...  }}]122```123124## Custom Headers125126To include additional headers in the outgoing request, use the `headers` keyword argument:127128```pycon129>>> url = 'https://httpbin.org/headers'130>>> headers = {'user-agent': 'my-app/0.0.1'}131>>> r = httpx.get(url, headers=headers)132```133134## Sending Form Encoded Data135136Some types of HTTP requests, such as `POST` and `PUT` requests, can include data137in the request body. One common way of including that is as form-encoded data,138which is used for HTML forms.139140```pycon141>>> data = {'key1': 'value1', 'key2': 'value2'}142>>> r = httpx.post("https://httpbin.org/post", data=data)143>>> print(r.text)144{145  ...146  "form": {147    "key2": "value2",148    "key1": "value1"149  },150  ...151}152```153154Form encoded data can also include multiple values from a given key.155156```pycon157>>> data = {'key1': ['value1', 'value2']}158>>> r = httpx.post("https://httpbin.org/post", data=data)159>>> print(r.text)160{161  ...162  "form": {163    "key1": [164      "value1",165      "value2"166    ]167  },168  ...169}170```171172## Sending Multipart File Uploads173174You can also upload files, using HTTP multipart encoding:175176```pycon177>>> with open('report.xls', 'rb') as report_file:178...     files = {'upload-file': report_file}179...     r = httpx.post("https://httpbin.org/post", files=files)180>>> print(r.text)181{182  ...183  "files": {184    "upload-file": "<... binary content ...>"185  },186  ...187}188```189190You can also explicitly set the filename and content type, by using a tuple191of items for the file value:192193```pycon194>>> with open('report.xls', 'rb') as report_file:195...     files = {'upload-file': ('report.xls', report_file, '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:208209```pycon210>>> data = {'message': 'Hello, world!'}211>>> with open('report.xls', 'rb') as report_file:212...     files = {'file': report_file}213...     r = httpx.post("https://httpbin.org/post", data=data, files=files)214>>> print(r.text)215{216  ...217  "files": {218    "file": "<... binary content ...>"219  },220  "form": {221    "message": "Hello, world!",222  },223  ...224}225```226227## Sending JSON Encoded Data228229Form encoded data is okay if all you need is a simple key-value data structure.230For more complicated data structures you'll often want to use JSON encoding instead.231232```pycon233>>> data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']}234>>> r = httpx.post("https://httpbin.org/post", json=data)235>>> print(r.text)236{237  ...238  "json": {239    "boolean": true,240    "integer": 123,241    "list": [242      "a",243      "b",244      "c"245    ]246  },247  ...248}249```250251## Sending Binary Request Data252253For other encodings, you should use the `content=...` parameter, passing254either a `bytes` type or a generator that yields `bytes`.255256```pycon257>>> content = b'Hello, world'258>>> r = httpx.post("https://httpbin.org/post", content=content)259```260261You may also want to set a custom `Content-Type` header when uploading262binary data.263264## Response Status Codes265266We can inspect the HTTP status code of the response:267268```pycon269>>> r = httpx.get('https://httpbin.org/get')270>>> r.status_code271200272```273274HTTPX also includes an easy shortcut for accessing status codes by their text phrase.275276```pycon277>>> r.status_code == httpx.codes.OK278True279```280281We can raise an exception for any responses which are not a 2xx success code:282283```pycon284>>> not_found = httpx.get('https://httpbin.org/status/404')285>>> not_found.status_code286404287>>> not_found.raise_for_status()288Traceback (most recent call last):289  File "/Users/tomchristie/GitHub/encode/httpcore/httpx/models.py", line 837, in raise_for_status290    raise HTTPStatusError(message, response=self)291httpx._exceptions.HTTPStatusError: 404 Client Error: Not Found for url: https://httpbin.org/status/404292For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404293```294295Any successful response codes will return the `Response` instance rather than raising an exception.296297```pycon298>>> r.raise_for_status()299```300301The method returns the response instance, allowing you to use it inline. For example:302303```pycon304>>> r = httpx.get('...').raise_for_status()305>>> data = httpx.get('...').raise_for_status().json()306```307308## Response Headers309310The response headers are available as a dictionary-like interface.311312```pycon313>>> r.headers314Headers({315    'content-encoding': 'gzip',316    'transfer-encoding': 'chunked',317    'connection': 'close',318    'server': 'nginx/1.0.4',319    'x-runtime': '148ms',320    'etag': '"e1ca502697e5c9317743dc078f67693f"',321    'content-type': 'application/json'322})323```324325The `Headers` data type is case-insensitive, so you can use any capitalization.326327```pycon328>>> r.headers['Content-Type']329'application/json'330331>>> r.headers.get('content-type')332'application/json'333```334335Multiple 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):336337> 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.338339## Streaming Responses340341For large downloads you may want to use streaming responses that do not load the entire response body into memory at once.342343You can stream the binary content of the response...344345```pycon346>>> with httpx.stream("GET", "https://www.example.com") as r:347...     for data in r.iter_bytes():348...         print(data)349```350351Or the text of the response...352353```pycon354>>> with httpx.stream("GET", "https://www.example.com") as r:355...     for text in r.iter_text():356...         print(text)357```358359Or stream the text, on a line-by-line basis...360361```pycon362>>> with httpx.stream("GET", "https://www.example.com") as r:363...     for line in r.iter_lines():364...         print(line)365```366367HTTPX will use universal line endings, normalising all cases to `\n`.368369In 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`, `brotli`, or `zstd` will370not be automatically decoded.371372```pycon373>>> with httpx.stream("GET", "https://www.example.com") as r:374...     for chunk in r.iter_raw():375...         print(chunk)376```377378If 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:379380```pycon381>>> with httpx.stream("GET", "https://www.example.com") as r:382...     if int(r.headers['Content-Length']) < TOO_LONG:383...         r.read()384...         print(r.text)385```386387## Cookies388389Any cookies that are set on the response can be easily accessed:390391```pycon392>>> r = httpx.get('https://httpbin.org/cookies/set?chocolate=chip')393>>> r.cookies['chocolate']394'chip'395```396397To include cookies in an outgoing request, use the `cookies` parameter:398399```pycon400>>> cookies = {"peanut": "butter"}401>>> r = httpx.get('https://httpbin.org/cookies', cookies=cookies)402>>> r.json()403{'cookies': {'peanut': 'butter'}}404```405406Cookies are returned in a `Cookies` instance, which is a dict-like data structure407with additional API for accessing cookies by their domain or path.408409```pycon410>>> cookies = httpx.Cookies()411>>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')412>>> cookies.set('cookie_off_domain', 'nope.', domain='example.org')413>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)414>>> r.json()415{'cookies': {'cookie_on_domain': 'hello, there!'}}416```417418## Redirection and History419420By default, HTTPX will **not** follow redirects for all HTTP methods, although421this can be explicitly enabled.422423For example, GitHub redirects all HTTP requests to HTTPS.424425```pycon426>>> r = httpx.get('http://github.com/')427>>> r.status_code428301429>>> r.history430[]431>>> r.next_request432<Request('GET', 'https://github.com/')>433```434435You can modify the default redirection handling with the `follow_redirects` parameter:436437```pycon438>>> r = httpx.get('http://github.com/', follow_redirects=True)439>>> r.url440URL('https://github.com/')441>>> r.status_code442200443>>> r.history444[<Response [301 Moved Permanently]>]445```446447The `history` property of the response can be used to inspect any followed redirects.448It contains a list of any redirect responses that were followed, in the order449in which they were made.450451## Timeouts452453HTTPX defaults to including reasonable timeouts for all network operations,454meaning that if a connection is not properly established then it should always455raise an error rather than hanging indefinitely.456457The default timeout for network inactivity is five seconds. You can modify the458value to be more or less strict:459460```pycon461>>> httpx.get('https://github.com/', timeout=0.001)462```463464You can also disable the timeout behavior completely...465466```pycon467>>> httpx.get('https://github.com/', timeout=None)468```469470For advanced timeout management, see [Timeout fine-tuning](advanced/timeouts.md#fine-tuning-the-configuration).471472## Authentication473474HTTPX supports Basic and Digest HTTP authentication.475476To provide Basic authentication credentials, pass a 2-tuple of477plaintext `str` or `bytes` objects as the `auth` argument to the request478functions:479480```pycon481>>> httpx.get("https://example.com", auth=("my_user", "password123"))482```483484To provide credentials for Digest authentication you'll need to instantiate485a `DigestAuth` object with the plaintext username and password as arguments.486This object can be then passed as the `auth` argument to the request methods487as above:488489```pycon490>>> auth = httpx.DigestAuth("my_user", "password123")491>>> httpx.get("https://example.com", auth=auth)492<Response [200 OK]>493```494495## Exceptions496497HTTPX will raise exceptions if an error occurs.498499The most important exception classes in HTTPX are `RequestError` and `HTTPStatusError`.500501The `RequestError` class is a superclass that encompasses any exception that occurs502while issuing an HTTP request. These exceptions include a `.request` attribute.503504```python505try:506    response = httpx.get("https://www.example.com/")507except httpx.RequestError as exc:508    print(f"An error occurred while requesting {exc.request.url!r}.")509```510511The `HTTPStatusError` class is raised by `response.raise_for_status()` on responses which are not a 2xx success code.512These exceptions include both a `.request` and a `.response` attribute.513514```python515response = httpx.get("https://www.example.com/")516try:517    response.raise_for_status()518except httpx.HTTPStatusError as exc:519    print(f"Error response {exc.response.status_code} while requesting {exc.request.url!r}.")520```521522There is also a base class `HTTPError` that includes both of these categories, and can be used523to catch either failed requests, or 4xx and 5xx responses.524525You can either use this base class to catch both categories...526527```python528try:529    response = httpx.get("https://www.example.com/")530    response.raise_for_status()531except httpx.HTTPError as exc:532    print(f"Error while requesting {exc.request.url!r}.")533```534535Or handle each case explicitly...536537```python538try:539    response = httpx.get("https://www.example.com/")540    response.raise_for_status()541except httpx.RequestError as exc:542    print(f"An error occurred while requesting {exc.request.url!r}.")543except httpx.HTTPStatusError as exc:544    print(f"Error response {exc.response.status_code} while requesting {exc.request.url!r}.")545```546547For a full list of available exceptions, see [Exceptions (API Reference)](exceptions.md).