quickstart.md
This file
Path
docs/quickstart.md
270 lines · 6.5 KiB · Markdown
Last changed by
http3 (#86)Tom Christiebefore adoptionc9747aa
History of this fileTake it
http3 (#86)Tom Christiebefore adoptionc9747aa
lines 1–270why, one step back1# QuickStart23!!! 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```1314Now, let’s try to get a webpage. For this example, let’s get GitHub’s public timeline:1516```python17>>> r = http3.get('https://api.github.com/events')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.