quickstart.md
This file
Path
docs/quickstart.md
544 lines · 14.2 KiB · Markdown
Last changed by
Add support for zstd decoding (#3139)Michiel W. Beijenbefore adoption392dbe4
History of this fileTake it
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>>> files = {'upload-file': open('report.xls', 'rb')}178>>> r = httpx.post("https://httpbin.org/post", files=files)179>>> print(r.text)180{181 ...182 "files": {183 "upload-file": "<... binary content ...>"184 },185 ...186}187```188189You can also explicitly set the filename and content type, by using a tuple190of items for the file value:191192```pycon193>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}194>>> r = httpx.post("https://httpbin.org/post", files=files)195>>> print(r.text)196{197 ...198 "files": {199 "upload-file": "<... binary content ...>"200 },201 ...202}203```204205If you need to include non-file data fields in the multipart form, use the `data=...` parameter:206207```pycon208>>> data = {'message': 'Hello, world!'}209>>> files = {'file': open('report.xls', 'rb')}210>>> r = httpx.post("https://httpbin.org/post", data=data, files=files)211>>> print(r.text)212{213 ...214 "files": {215 "file": "<... binary content ...>"216 },217 "form": {218 "message": "Hello, world!",219 },220 ...221}222```223224## Sending JSON Encoded Data225226Form encoded data is okay if all you need is a simple key-value data structure.227For more complicated data structures you'll often want to use JSON encoding instead.228229```pycon230>>> data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']}231>>> r = httpx.post("https://httpbin.org/post", json=data)232>>> print(r.text)233{234 ...235 "json": {236 "boolean": true,237 "integer": 123,238 "list": [239 "a",240 "b",241 "c"242 ]243 },244 ...245}246```247248## Sending Binary Request Data249250For other encodings, you should use the `content=...` parameter, passing251either a `bytes` type or a generator that yields `bytes`.252253```pycon254>>> content = b'Hello, world'255>>> r = httpx.post("https://httpbin.org/post", content=content)256```257258You may also want to set a custom `Content-Type` header when uploading259binary data.260261## Response Status Codes262263We can inspect the HTTP status code of the response:264265```pycon266>>> r = httpx.get('https://httpbin.org/get')267>>> r.status_code268200269```270271HTTPX also includes an easy shortcut for accessing status codes by their text phrase.272273```pycon274>>> r.status_code == httpx.codes.OK275True276```277278We can raise an exception for any responses which are not a 2xx success code:279280```pycon281>>> not_found = httpx.get('https://httpbin.org/status/404')282>>> not_found.status_code283404284>>> not_found.raise_for_status()285Traceback (most recent call last):286 File "/Users/tomchristie/GitHub/encode/httpcore/httpx/models.py", line 837, in raise_for_status287 raise HTTPStatusError(message, response=self)288httpx._exceptions.HTTPStatusError: 404 Client Error: Not Found for url: https://httpbin.org/status/404289For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404290```291292Any successful response codes will return the `Response` instance rather than raising an exception.293294```pycon295>>> r.raise_for_status()296```297298The method returns the response instance, allowing you to use it inline. For example:299300```pycon301>>> r = httpx.get('...').raise_for_status()302>>> data = httpx.get('...').raise_for_status().json()303```304305## Response Headers306307The response headers are available as a dictionary-like interface.308309```pycon310>>> r.headers311Headers({312 'content-encoding': 'gzip',313 'transfer-encoding': 'chunked',314 'connection': 'close',315 'server': 'nginx/1.0.4',316 'x-runtime': '148ms',317 'etag': '"e1ca502697e5c9317743dc078f67693f"',318 'content-type': 'application/json'319})320```321322The `Headers` data type is case-insensitive, so you can use any capitalization.323324```pycon325>>> r.headers['Content-Type']326'application/json'327328>>> r.headers.get('content-type')329'application/json'330```331332Multiple 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):333334> 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.335336## Streaming Responses337338For large downloads you may want to use streaming responses that do not load the entire response body into memory at once.339340You can stream the binary content of the response...341342```pycon343>>> with httpx.stream("GET", "https://www.example.com") as r:344... for data in r.iter_bytes():345... print(data)346```347348Or the text of the response...349350```pycon351>>> with httpx.stream("GET", "https://www.example.com") as r:352... for text in r.iter_text():353... print(text)354```355356Or stream the text, on a line-by-line basis...357358```pycon359>>> with httpx.stream("GET", "https://www.example.com") as r:360... for line in r.iter_lines():361... print(line)362```363364HTTPX will use universal line endings, normalising all cases to `\n`.365366In 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` will367not be automatically decoded.368369```pycon370>>> with httpx.stream("GET", "https://www.example.com") as r:371... for chunk in r.iter_raw():372... print(chunk)373```374375If 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:376377```pycon378>>> with httpx.stream("GET", "https://www.example.com") as r:379... if int(r.headers['Content-Length']) < TOO_LONG:380... r.read()381... print(r.text)382```383384## Cookies385386Any cookies that are set on the response can be easily accessed:387388```pycon389>>> r = httpx.get('https://httpbin.org/cookies/set?chocolate=chip')390>>> r.cookies['chocolate']391'chip'392```393394To include cookies in an outgoing request, use the `cookies` parameter:395396```pycon397>>> cookies = {"peanut": "butter"}398>>> r = httpx.get('https://httpbin.org/cookies', cookies=cookies)399>>> r.json()400{'cookies': {'peanut': 'butter'}}401```402403Cookies are returned in a `Cookies` instance, which is a dict-like data structure404with additional API for accessing cookies by their domain or path.405406```pycon407>>> cookies = httpx.Cookies()408>>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')409>>> cookies.set('cookie_off_domain', 'nope.', domain='example.org')410>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)411>>> r.json()412{'cookies': {'cookie_on_domain': 'hello, there!'}}413```414415## Redirection and History416417By default, HTTPX will **not** follow redirects for all HTTP methods, although418this can be explicitly enabled.419420For example, GitHub redirects all HTTP requests to HTTPS.421422```pycon423>>> r = httpx.get('http://github.com/')424>>> r.status_code425301426>>> r.history427[]428>>> r.next_request429<Request('GET', 'https://github.com/')>430```431432You can modify the default redirection handling with the `follow_redirects` parameter:433434```pycon435>>> r = httpx.get('http://github.com/', follow_redirects=True)436>>> r.url437URL('https://github.com/')438>>> r.status_code439200440>>> r.history441[<Response [301 Moved Permanently]>]442```443444The `history` property of the response can be used to inspect any followed redirects.445It contains a list of any redirect responses that were followed, in the order446in which they were made.447448## Timeouts449450HTTPX defaults to including reasonable timeouts for all network operations,451meaning that if a connection is not properly established then it should always452raise an error rather than hanging indefinitely.453454The default timeout for network inactivity is five seconds. You can modify the455value to be more or less strict:456457```pycon458>>> httpx.get('https://github.com/', timeout=0.001)459```460461You can also disable the timeout behavior completely...462463```pycon464>>> httpx.get('https://github.com/', timeout=None)465```466467For advanced timeout management, see [Timeout fine-tuning](advanced/timeouts.md#fine-tuning-the-configuration).468469## Authentication470471HTTPX supports Basic and Digest HTTP authentication.472473To provide Basic authentication credentials, pass a 2-tuple of474plaintext `str` or `bytes` objects as the `auth` argument to the request475functions:476477```pycon478>>> httpx.get("https://example.com", auth=("my_user", "password123"))479```480481To provide credentials for Digest authentication you'll need to instantiate482a `DigestAuth` object with the plaintext username and password as arguments.483This object can be then passed as the `auth` argument to the request methods484as above:485486```pycon487>>> auth = httpx.DigestAuth("my_user", "password123")488>>> httpx.get("https://example.com", auth=auth)489<Response [200 OK]>490```491492## Exceptions493494HTTPX will raise exceptions if an error occurs.495496The most important exception classes in HTTPX are `RequestError` and `HTTPStatusError`.497498The `RequestError` class is a superclass that encompasses any exception that occurs499while issuing an HTTP request. These exceptions include a `.request` attribute.500501```python502try:503 response = httpx.get("https://www.example.com/")504except httpx.RequestError as exc:505 print(f"An error occurred while requesting {exc.request.url!r}.")506```507508The `HTTPStatusError` class is raised by `response.raise_for_status()` on responses which are not a 2xx success code.509These exceptions include both a `.request` and a `.response` attribute.510511```python512response = httpx.get("https://www.example.com/")513try:514 response.raise_for_status()515except httpx.HTTPStatusError as exc:516 print(f"Error response {exc.response.status_code} while requesting {exc.request.url!r}.")517```518519There is also a base class `HTTPError` that includes both of these categories, and can be used520to catch either failed requests, or 4xx and 5xx responses.521522You can either use this base class to catch both categories...523524```python525try:526 response = httpx.get("https://www.example.com/")527 response.raise_for_status()528except httpx.HTTPError as exc:529 print(f"Error while requesting {exc.request.url!r}.")530```531532Or handle each case explicitly...533534```python535try:536 response = httpx.get("https://www.example.com/")537 response.raise_for_status()538except httpx.RequestError as exc:539 print(f"An error occurred while requesting {exc.request.url!r}.")540except httpx.HTTPStatusError as exc:541 print(f"Error response {exc.response.status_code} while requesting {exc.request.url!r}.")542```543544For a full list of available exceptions, see [Exceptions (API Reference)](exceptions.md).