Skip to content
Myr

quickstart.md

This file

Path

docs/quickstart.md

387 lines · 9.4 KiB · Markdown

Last changed by

Add multipart docsTom Christiebefore adoptiond21e3ab

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–163why, 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```163

Add multipart docsTom Christiebefore adoptiond21e3ab

lines 164–196why, one step back
164## Sending Multipart File Uploads
165166You can also upload files, using HTTP multipart encoding:167168```python169>>> files = {'upload-file': open('report.xls', 'rb')}170>>> r = http3.post("https://httpbin.org/post", files=files)171>>> print(r.text)172{173 ...174 "files": {175 "upload-file": "<... binary content ...>"176 },177 ...178}179```180181You can also explicitly set the filename and content type, by using a tuple182of items for the file value:183184```python185>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}186>>> r = http3.post("https://httpbin.org/post", files=files)187>>> print(r.text)188{189 ...190 "files": {191 "upload-file": "<... binary content ...>"192 },193 ...194}195```196

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 197–303why, one step back
197## Sending JSON Encoded Data
198199Form encoded data is okay if all you need is simple key-value data structure.200For more complicated data structures you'll often want to use JSON encoding instead.201202```python203>>> data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']}204>>> r = http3.post("https://httpbin.org/post", json=data)205>>> print(r.text)206{207 ...208 "json": {209 "boolean": true,210 "integer": 123,211 "list": [212 "a",213 "b",214 "c"215 ]216 },217 ...218}219```220221## Sending Binary Request Data222223For other encodings you should use either a `bytes` type, or a generator224that yields `bytes`.225226You'll probably also want to set a custom `Content-Type` header when uploading227binary data.228229## Response Status Codes230231We can inspect the HTTP status code of the response:232233```python234>>> r = http3.get('https://httpbin.org/get')235>>> r.status_code236<StatusCode.OK: 200>237```238239The status code is an integer enum, meaning that the Python representation gives240use some descriptive information, but the value itself can be used as a regular integer.241242```python243>>> r.status_code == 200244True245```246247HTTP3 also includes an easy shortcut for accessing status codes by their text phrase.248249```python250>>> r.status_code == requests.codes.OK251True252```253254We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):255256```python257>>> not_found = http3.get('https://httpbin.org/status/404')258>>> not_found.status_code259<StatusCode.NOT_FOUND: 404>260>>> not_found.raise_for_status()261Traceback (most recent call last):262 File "/Users/tomchristie/GitHub/encode/httpcore/http3/models.py", line 776, in raise_for_status263 raise HttpError(message)264http3.exceptions.HttpError: 404 Not Found265```266267Any successful response codes will simply return `None` rather than raising an exception.268269``` python270>>> r.raise_for_status()271```272273## Response Headers274275The response headers are available as a dictionary-like interface.276277```python278>>> r.headers279Headers({280 'content-encoding': 'gzip',281 'transfer-encoding': 'chunked',282 'connection': 'close',283 'server': 'nginx/1.0.4',284 'x-runtime': '148ms',285 'etag': '"e1ca502697e5c9317743dc078f67693f"',286 'content-type': 'application/json'287})288```289290The `Headers` data type is case-insensitive, so you can use any capitalization.291292```python293>>> r.headers['Content-Type']294'application/json'295296>>> r.headers.get('content-type')297'application/json'298```299300Multiple values for a single response header are represented as a single comma separated301value, as per [RFC 7230](https://tools.ietf.org/html/rfc7230#section-3.2):302303> 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 304–324why, one step back
304
305## Cookies306307Any cookies that are set on the response can be easily accessed:308309```python310>>> r = http3.get('http://httpbin.org/cookies/set?chocolate=chip', allow_redirects=False)311>>> r.cookies['chocolate']312'chip'313```314315To include cookies in an outgoing request, use the `cookies` parameter:316317```python318>>> cookies = {"peanut": "butter"}319>>> r = http3.get('http://httpbin.org/cookies', cookies=cookies)320>>> r.json()321{'cookies': {'peanut': 'butter'}}322```323324Cookies are returned in a `Cookies` instance, which is a dict-like data structure

Tweaks (#89)Tom Christiebefore adoption7c6fb5c

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

Add Cookies docsTom Christiebefore adoptiond5d726f

lines 326–333why, one step back
326
327```python328>>> cookies = http3.Cookies()329>>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')330>>> cookies.set('cookie_off_domain', 'nope.', domain='example.org')331>>> r = http3.get('http://httpbin.org/cookies', cookies=cookies)332>>> r.json()333{'cookies': {'cookie_on_domain': 'hello, there!'}}

Tweaks (#89)Tom Christiebefore adoption7c6fb5c

lines 334–386why, one step back
334```
335336## Redirection and History337338By default HTTP3 will follow redirects for anything except `HEAD` requests.339340The `history` property of the response can be used to inspect any followed redirects.341It contains a list of all any redirect responses that were followed, in the order342in which they were made.343344For example, GitHub redirects all HTTP requests to HTTPS.345346```python347>>> r = http3.get('http://github.com/')348>>> r.url349URL('https://github.com/')350>>> r.status_code351<StatusCode.OK: 200>352>>> r.history353[<Response [301]>]354```355356You can modify the default redirection handling with the allow_redirects parameter:357358```python359>>> r = http3.get('http://github.com/', allow_redirects=False)360>>> r.status_code361301362>>> r.history363[]364```365366If you’re making a `HEAD` request, you can use this to enable redirection:367368```python369>>> r = http3.head('http://github.com/', allow_redirects=True)370>>> r.url371'https://github.com/'372>>> r.history373[<Response [301]>]374```375376## Timeouts377378HTTP3 defaults to including reasonable timeouts for all network operations,379meaning that if a connection is not properly established then it should always380raise an error rather than hanging indefinitely.381382The default timeout for network inactivity is five seconds. You can modify the383value to be more or less strict:384385```python386>>> http3.get('https://github.com/', timeout=0.001)

Add Cookies docsTom Christiebefore adoptiond5d726f

line 387why, one step back
387```