Skip to content
Myr

quickstart.md

This file

Path

docs/quickstart.md

381 lines · 9.2 KiB · Markdown

Last changed by

Int status codes (#92)Tom Christiebefore adoption56a7943

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')

Int status codes (#92)Tom Christiebefore adoption56a7943

lines 18–19why, one step back
18>>> r
19<Response [200 OK]>

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 20–165why, one step back
20```
2122Similarly, to make an HTTP POST request:2324```python25>>> r = http3.post('https://httpbin.org/post', data={'key': 'value'})26```2728The PUT, DELETE, HEAD, and OPTIONS requests all follow the same style:2930```python31>>> r = http3.put('https://httpbin.org/put', data={'key': 'value'})32>>> r = http3.delete('https://httpbin.org/delete')33>>> r = http3.head('https://httpbin.org/get')34>>> r = http3.options('https://httpbin.org/get')35```3637## Passing Parameters in URLs3839To include URL query parameters in the request, use the `params` keyword:4041```python42>>> params = {'key1': 'value1', 'key2': 'value2'}43>>> r = http3.get('https://httpbin.org/get', params=params)44```4546To see how the values get encoding into the URL string, we can inspect the47resulting URL that was used to make the request:4849```python50>>> r.url51URL('https://httpbin.org/get?key2=value2&key1=value1')52```5354You can also pass a list of items as a value:5556```python57>>> params = {'key1': 'value1', 'key2': ['value2', 'value3']}58>>> r = http3.get('https://httpbin.org/get', params=params)59>>> r.url60URL('https://httpbin.org/get?key1=value1&key2=value2&key2=value3')61```6263## Response Content6465HTTP3 will automatically handle decoding the response content into unicode text.6667```python68>>> r = http3.get('https://www.example.org/')69>>> r.text70'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'71```7273You can inspect what encoding has been used to decode the response.7475```python76>>> r.encoding77'UTF-8'78```7980If you need to override the standard behavior and explicitly set the encoding to81use, then you can do that too.8283```python84>>> r.encoding = 'ISO-8859-1'85```8687## Binary Response Content8889The response content can also be accessed as bytes, for non-text responses:9091```python92>>> r.content93b'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'94```9596Any `gzip` and `deflate` HTTP response encodings will automatically97be decoded for you. If `brotlipy` is installed, then the `brotli` response98encoding will also be supported.99100For example, to create an image from binary data returned by a request, you can use the following code:101102```python103>>> from PIL import Image104>>> from io import BytesIO105>>> i = Image.open(BytesIO(r.content))106```107108## JSON Response Content109110Often Web API responses will be encoded as JSON.111112```python113>>> r = http3.get('https://api.github.com/events')114>>> r.json()115[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...' ... }}]116```117118## Custom Headers119120To include additional headers in the outgoing request, use the `headers` keyword argument:121122```python123>>> url = 'http://httpbin.org/headers'124>>> headers = {'user-agent': 'my-app/0.0.1'}125>>> r = http3.get(url, headers=headers)126```127128## Sending Form Encoded Data129130Some types of HTTP requests, such as `POST` and `PUT` requests, can include data131in the request body. One common way of including that is as form encoded data,132which is used for HTML forms.133134```python135>>> data = {'key1': 'value1', 'key2': 'value2'}136>>> r = http3.post("https://httpbin.org/post", data=data)137>>> print(r.text)138{139 ...140 "form": {141 "key2": "value2",142 "key1": "value1"143 },144 ...145}146```147148Form encoded data can also include multiple values form a given key.149150```python151>>> data = {'key1': ['value1', 'value2']}152>>> r = http3.post("https://httpbin.org/post", data=data)153>>> print(r.text)154{155 ...156 "form": {157 "key1": [158 "value1",159 "value2"160 ]161 },162 ...163}164```165

Add multipart docsTom Christiebefore adoptiond21e3ab

lines 166–198why, one step back
166## Sending Multipart File Uploads
167168You can also upload files, using HTTP multipart encoding:169170```python171>>> files = {'upload-file': open('report.xls', 'rb')}172>>> r = http3.post("https://httpbin.org/post", files=files)173>>> print(r.text)174{175 ...176 "files": {177 "upload-file": "<... binary content ...>"178 },179 ...180}181```182183You can also explicitly set the filename and content type, by using a tuple184of items for the file value:185186```python187>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}188>>> r = http3.post("https://httpbin.org/post", files=files)189>>> print(r.text)190{191 ...192 "files": {193 "upload-file": "<... binary content ...>"194 },195 ...196}197```198

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 199–237why, one step back
199## Sending JSON Encoded Data
200201Form encoded data is okay if all you need is simple key-value data structure.202For more complicated data structures you'll often want to use JSON encoding instead.203204```python205>>> data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']}206>>> r = http3.post("https://httpbin.org/post", json=data)207>>> print(r.text)208{209 ...210 "json": {211 "boolean": true,212 "integer": 123,213 "list": [214 "a",215 "b",216 "c"217 ]218 },219 ...220}221```222223## Sending Binary Request Data224225For other encodings you should use either a `bytes` type, or a generator226that yields `bytes`.227228You'll probably also want to set a custom `Content-Type` header when uploading229binary data.230231## Response Status Codes232233We can inspect the HTTP status code of the response:234235```python236>>> r = http3.get('https://httpbin.org/get')237>>> r.status_code

Int status codes (#92)Tom Christiebefore adoption56a7943

line 238why, one step back
238200

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 239–243why, one step back
239```
240241HTTP3 also includes an easy shortcut for accessing status codes by their text phrase.242243```python

Int status codes (#92)Tom Christiebefore adoption56a7943

line 244why, one step back
244>>> r.status_code == http3.codes.OK

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 245–252why, one step back
245True
246```247248We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):249250```python251>>> not_found = http3.get('https://httpbin.org/status/404')252>>> not_found.status_code

Int status codes (#92)Tom Christiebefore adoption56a7943

line 253why, one step back
253404

http3 (#86)Tom Christiebefore adoptionc9747aa

lines 254–297why, one step back
254>>> not_found.raise_for_status()
255Traceback (most recent call last):256 File "/Users/tomchristie/GitHub/encode/httpcore/http3/models.py", line 776, in raise_for_status257 raise HttpError(message)258http3.exceptions.HttpError: 404 Not Found259```260261Any successful response codes will simply return `None` rather than raising an exception.262263``` python264>>> r.raise_for_status()265```266267## Response Headers268269The response headers are available as a dictionary-like interface.270271```python272>>> r.headers273Headers({274 'content-encoding': 'gzip',275 'transfer-encoding': 'chunked',276 'connection': 'close',277 'server': 'nginx/1.0.4',278 'x-runtime': '148ms',279 'etag': '"e1ca502697e5c9317743dc078f67693f"',280 'content-type': 'application/json'281})282```283284The `Headers` data type is case-insensitive, so you can use any capitalization.285286```python287>>> r.headers['Content-Type']288'application/json'289290>>> r.headers.get('content-type')291'application/json'292```293294Multiple values for a single response header are represented as a single comma separated295value, as per [RFC 7230](https://tools.ietf.org/html/rfc7230#section-3.2):296297> 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 298–318why, one step back
298
299## Cookies300301Any cookies that are set on the response can be easily accessed:302303```python304>>> r = http3.get('http://httpbin.org/cookies/set?chocolate=chip', allow_redirects=False)305>>> r.cookies['chocolate']306'chip'307```308309To include cookies in an outgoing request, use the `cookies` parameter:310311```python312>>> cookies = {"peanut": "butter"}313>>> r = http3.get('http://httpbin.org/cookies', cookies=cookies)314>>> r.json()315{'cookies': {'peanut': 'butter'}}316```317318Cookies are returned in a `Cookies` instance, which is a dict-like data structure

Tweaks (#89)Tom Christiebefore adoption7c6fb5c

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

Add Cookies docsTom Christiebefore adoptiond5d726f

lines 320–327why, one step back
320
321```python322>>> cookies = http3.Cookies()323>>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')324>>> cookies.set('cookie_off_domain', 'nope.', domain='example.org')325>>> r = http3.get('http://httpbin.org/cookies', cookies=cookies)326>>> r.json()327{'cookies': {'cookie_on_domain': 'hello, there!'}}

Tweaks (#89)Tom Christiebefore adoption7c6fb5c

lines 328–344why, one step back
328```
329330## Redirection and History331332By default HTTP3 will follow redirects for anything except `HEAD` requests.333334The `history` property of the response can be used to inspect any followed redirects.335It contains a list of all any redirect responses that were followed, in the order336in which they were made.337338For example, GitHub redirects all HTTP requests to HTTPS.339340```python341>>> r = http3.get('http://github.com/')342>>> r.url343URL('https://github.com/')344>>> r.status_code

Int status codes (#92)Tom Christiebefore adoption56a7943

line 345why, one step back
345200

Tweaks (#89)Tom Christiebefore adoption7c6fb5c

line 346why, one step back
346>>> r.history

Int status codes (#92)Tom Christiebefore adoption56a7943

line 347why, one step back
347[<Response [301 Moved Permanently]>]

Tweaks (#89)Tom Christiebefore adoption7c6fb5c

lines 348–366why, one step back
348```
349350You can modify the default redirection handling with the allow_redirects parameter:351352```python353>>> r = http3.get('http://github.com/', allow_redirects=False)354>>> r.status_code355301356>>> r.history357[]358```359360If you’re making a `HEAD` request, you can use this to enable redirection:361362```python363>>> r = http3.head('http://github.com/', allow_redirects=True)364>>> r.url365'https://github.com/'366>>> r.history

Int status codes (#92)Tom Christiebefore adoption56a7943

line 367why, one step back
367[<Response [301 Moved Permanently]>]

Tweaks (#89)Tom Christiebefore adoption7c6fb5c

lines 368–380why, one step back
368```
369370## Timeouts371372HTTP3 defaults to including reasonable timeouts for all network operations,373meaning that if a connection is not properly established then it should always374raise an error rather than hanging indefinitely.375376The default timeout for network inactivity is five seconds. You can modify the377value to be more or less strict:378379```python380>>> http3.get('https://github.com/', timeout=0.001)

Add Cookies docsTom Christiebefore adoptiond5d726f

line 381why, one step back
381```