Skip to content
Myr

quickstart.md

This file

Path

docs/quickstart.md

354 lines · 8.7 KiB · Markdown

Last changed by

Tweaks (#89)Tom Christiebefore adoption7c6fb5c

History of this file

Take it

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 1–13why, one step back
1# QuickStart
23!!! note4 This page closely follows the layout of the `requests` QuickStart documentation.5 The `http3` library is designed to be API compatible with `requests` wherever6 possible.78First start by importing HTTP3:910```11>>> import http312```13

Add Cookies docsTom Christiebefore adoptiond5d726f

line 14why, one step back
14Now, let’s try to get a webpage.

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 15–16why, one step back
15
16```python

Add Cookies docsTom Christiebefore adoptiond5d726f

line 17why, one step back
17>>> r = http3.get('https://httpbin.org/get')

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 18–270why, one step back
18```
1920Similarly, to make an HTTP POST request:2122```python23>>> r = http3.post('https://httpbin.org/post', data={'key': 'value'})24```2526The PUT, DELETE, HEAD, and OPTIONS requests all follow the same style:2728```python29>>> r = http3.put('https://httpbin.org/put', data={'key': 'value'})30>>> r = http3.delete('https://httpbin.org/delete')31>>> r = http3.head('https://httpbin.org/get')32>>> r = http3.options('https://httpbin.org/get')33```3435## Passing Parameters in URLs3637To include URL query parameters in the request, use the `params` keyword:3839```python40>>> params = {'key1': 'value1', 'key2': 'value2'}41>>> r = http3.get('https://httpbin.org/get', params=params)42```4344To see how the values get encoding into the URL string, we can inspect the45resulting URL that was used to make the request:4647```python48>>> r.url49URL('https://httpbin.org/get?key2=value2&key1=value1')50```5152You can also pass a list of items as a value:5354```python55>>> params = {'key1': 'value1', 'key2': ['value2', 'value3']}56>>> r = http3.get('https://httpbin.org/get', params=params)57>>> r.url58URL('https://httpbin.org/get?key1=value1&key2=value2&key2=value3')59```6061## Response Content6263HTTP3 will automatically handle decoding the response content into unicode text.6465```python66>>> r = http3.get('https://www.example.org/')67>>> r.text68'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'69```7071You can inspect what encoding has been used to decode the response.7273```python74>>> r.encoding75'UTF-8'76```7778If you need to override the standard behavior and explicitly set the encoding to79use, then you can do that too.8081```python82>>> r.encoding = 'ISO-8859-1'83```8485## Binary Response Content8687The response content can also be accessed as bytes, for non-text responses:8889```python90>>> r.content91b'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'92```9394Any `gzip` and `deflate` HTTP response encodings will automatically95be decoded for you. If `brotlipy` is installed, then the `brotli` response96encoding will also be supported.9798For example, to create an image from binary data returned by a request, you can use the following code:99100```python101>>> from PIL import Image102>>> from io import BytesIO103>>> i = Image.open(BytesIO(r.content))104```105106## JSON Response Content107108Often Web API responses will be encoded as JSON.109110```python111>>> r = http3.get('https://api.github.com/events')112>>> r.json()113[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...' ... }}]114```115116## Custom Headers117118To include additional headers in the outgoing request, use the `headers` keyword argument:119120```python121>>> url = 'http://httpbin.org/headers'122>>> headers = {'user-agent': 'my-app/0.0.1'}123>>> r = http3.get(url, headers=headers)124```125126## Sending Form Encoded Data127128Some types of HTTP requests, such as `POST` and `PUT` requests, can include data129in the request body. One common way of including that is as form encoded data,130which is used for HTML forms.131132```python133>>> data = {'key1': 'value1', 'key2': 'value2'}134>>> r = http3.post("https://httpbin.org/post", data=data)135>>> print(r.text)136{137 ...138 "form": {139 "key2": "value2",140 "key1": "value1"141 },142 ...143}144```145146Form encoded data can also include multiple values form a given key.147148```python149>>> data = {'key1': ['value1', 'value2']}150>>> r = http3.post("https://httpbin.org/post", data=data)151>>> print(r.text)152{153 ...154 "form": {155 "key1": [156 "value1",157 "value2"158 ]159 },160 ...161}162```163164## Sending JSON Encoded Data165166Form encoded data is okay if all you need is simple key-value data structure.167For more complicated data structures you'll often want to use JSON encoding instead.168169```python170>>> data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']}171>>> r = http3.post("https://httpbin.org/post", json=data)172>>> print(r.text)173{174 ...175 "json": {176 "boolean": true,177 "integer": 123,178 "list": [179 "a",180 "b",181 "c"182 ]183 },184 ...185}186```187188## Sending Binary Request Data189190For other encodings you should use either a `bytes` type, or a generator191that yields `bytes`.192193You'll probably also want to set a custom `Content-Type` header when uploading194binary data.195196## Response Status Codes197198We can inspect the HTTP status code of the response:199200```python201>>> r = http3.get('https://httpbin.org/get')202>>> r.status_code203<StatusCode.OK: 200>204```205206The status code is an integer enum, meaning that the Python representation gives207use some descriptive information, but the value itself can be used as a regular integer.208209```python210>>> r.status_code == 200211True212```213214HTTP3 also includes an easy shortcut for accessing status codes by their text phrase.215216```python217>>> r.status_code == requests.codes.OK218True219```220221We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):222223```python224>>> not_found = http3.get('https://httpbin.org/status/404')225>>> not_found.status_code226<StatusCode.NOT_FOUND: 404>227>>> not_found.raise_for_status()228Traceback (most recent call last):229 File "/Users/tomchristie/GitHub/encode/httpcore/http3/models.py", line 776, in raise_for_status230 raise HttpError(message)231http3.exceptions.HttpError: 404 Not Found232```233234Any successful response codes will simply return `None` rather than raising an exception.235236``` python237>>> r.raise_for_status()238```239240## Response Headers241242The response headers are available as a dictionary-like interface.243244```python245>>> r.headers246Headers({247 'content-encoding': 'gzip',248 'transfer-encoding': 'chunked',249 'connection': 'close',250 'server': 'nginx/1.0.4',251 'x-runtime': '148ms',252 'etag': '"e1ca502697e5c9317743dc078f67693f"',253 'content-type': 'application/json'254})255```256257The `Headers` data type is case-insensitive, so you can use any capitalization.258259```python260>>> r.headers['Content-Type']261'application/json'262263>>> r.headers.get('content-type')264'application/json'265```266267Multiple values for a single response header are represented as a single comma separated268value, as per [RFC 7230](https://tools.ietf.org/html/rfc7230#section-3.2):269270> 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.

Add Cookies docsTom Christiebefore adoptiond5d726f

lines 271–291why, one step back
271
272## Cookies273274Any cookies that are set on the response can be easily accessed:275276```python277>>> r = http3.get('http://httpbin.org/cookies/set?chocolate=chip', allow_redirects=False)278>>> r.cookies['chocolate']279'chip'280```281282To include cookies in an outgoing request, use the `cookies` parameter:283284```python285>>> cookies = {"peanut": "butter"}286>>> r = http3.get('http://httpbin.org/cookies', cookies=cookies)287>>> r.json()288{'cookies': {'peanut': 'butter'}}289```290291Cookies are returned in a `Cookies` instance, which is a dict-like data structure

Tweaks (#89)Tom Christiebefore adoption7c6fb5c

line 292why, one step back
292with additional API for accessing cookies by their domain or path.

Add Cookies docsTom Christiebefore adoptiond5d726f

lines 293–300why, one step back
293
294```python295>>> cookies = http3.Cookies()296>>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')297>>> cookies.set('cookie_off_domain', 'nope.', domain='example.org')298>>> r = http3.get('http://httpbin.org/cookies', cookies=cookies)299>>> r.json()300{'cookies': {'cookie_on_domain': 'hello, there!'}}

Tweaks (#89)Tom Christiebefore adoption7c6fb5c

lines 301–353why, one step back
301```
302303## Redirection and History304305By default HTTP3 will follow redirects for anything except `HEAD` requests.306307The `history` property of the response can be used to inspect any followed redirects.308It contains a list of all any redirect responses that were followed, in the order309in which they were made.310311For example, GitHub redirects all HTTP requests to HTTPS.312313```python314>>> r = http3.get('http://github.com/')315>>> r.url316URL('https://github.com/')317>>> r.status_code318<StatusCode.OK: 200>319>>> r.history320[<Response [301]>]321```322323You can modify the default redirection handling with the allow_redirects parameter:324325```python326>>> r = http3.get('http://github.com/', allow_redirects=False)327>>> r.status_code328301329>>> r.history330[]331```332333If you’re making a `HEAD` request, you can use this to enable redirection:334335```python336>>> r = http3.head('http://github.com/', allow_redirects=True)337>>> r.url338'https://github.com/'339>>> r.history340[<Response [301]>]341```342343## Timeouts344345HTTP3 defaults to including reasonable timeouts for all network operations,346meaning that if a connection is not properly established then it should always347raise an error rather than hanging indefinitely.348349The default timeout for network inactivity is five seconds. You can modify the350value to be more or less strict:351352```python353>>> http3.get('https://github.com/', timeout=0.001)

Add Cookies docsTom Christiebefore adoptiond5d726f

line 354why, one step back
354```