Skip to content
Myr

quickstart.rst

This file

Path

docs/user/quickstart.rst

351 lines · 9.5 KiB

Last changed by

Merge pull request #280 from darkrho/58e018af136190a2c757b13bf9371cecc2d51273Kenneth Reitzbefore adoption2a72235

History of this file

Take it

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 1why, one step back
1.. _quickstart:

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 2why, one step back
2

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 3–4why, one step back
3Quickstart
4==========

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 5why, one step back
5

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 6why, one step back
6.. module:: requests.models

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 7why, one step back
7

Migrate new docs over.Kenneth Reitzbefore adoption4a7fdef

lines 8–10why, one step back
8Eager to get started? This page gives a good introduction in how to get started
9with Requests. This assumes you already have Requests installed. If you do not,10head over to the :ref:`Installation <install>` section.

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 11why, one step back
11

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 12why, one step back
12First, make sure that:

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 13why, one step back
13

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 14–15why, one step back
14* Requests is :ref:`installed <install>`
15* Requests is :ref:`up-to-date <updates>`

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

lines 16–17why, one step back
16
17

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 18why, one step back
18Lets gets started with some simple use cases and examples.

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

lines 19–20why, one step back
19
20

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 21–22why, one step back
21Make a GET Request
22------------------

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 23why, one step back
23

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 24why, one step back
24Making a standard request with Requests is very simple.

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 25why, one step back
25

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 26why, one step back
26Let's get GitHub's public timeline ::

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 27why, one step back
27

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 28why, one step back
28 r = requests.get('https://github.com/timeline.json')

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 29why, one step back
29

Migrate new docs over.Kenneth Reitzbefore adoption4a7fdef

lines 30–31why, one step back
30Now, we have a :class:`Response` object called ``r``. We can get all the
31information we need from this.

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

lines 32–33why, one step back
32
33

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 34–35why, one step back
34Response Content
35----------------

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 36why, one step back
36

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 37why, one step back
37We can read the content of the server's response::

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 38why, one step back
38

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 39–40why, one step back
39 >>> r.content
40 '[{"repository":{"open_issues":0,"url":"https://github.com/...

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 41why, one step back
41

sp Kenneth Reitzbefore adoption3d49eb4

lines 42–43why, one step back
42Requests does its best to decode content from the server. Most unicode
43charsets, ``gzip``, and ``deflate`` encodings are all seamlessly decoded.

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 44why, one step back
44

big quick start updatesKenneth Reitzbefore adoption60558fd

line 45why, one step back
45

Merge branch 'develop' of https://github.com/joequery/requests into developKenneth Reitzbefore adoption3d6937a

line 46why, one step back
46Make a POST Request

big quick start updatesKenneth Reitzbefore adoption60558fd

line 47why, one step back
47-------------------

Merge branch 'develop' of https://github.com/joequery/requests into developKenneth Reitzbefore adoption3d6937a

line 48why, one step back
48

big quick start updatesKenneth Reitzbefore adoption60558fd

line 49why, one step back
49POST requests are equally simple::

Merge branch 'develop' of https://github.com/joequery/requests into developKenneth Reitzbefore adoption3d6937a

line 50why, one step back
50

big quick start updatesKenneth Reitzbefore adoption60558fd

line 51why, one step back
51 r = requests.post("http://httpbin.org/post")

Merge branch 'develop' of https://github.com/joequery/requests into developKenneth Reitzbefore adoption3d6937a

lines 52–53why, one step back
52
53

big quick start updatesKenneth Reitzbefore adoption60558fd

line 54why, one step back
54Typically, you want to send some form-encoded data — much like an HTML form.

sp Kenneth Reitzbefore adoption3d49eb4

lines 55–56why, one step back
55To do this, simply pass a dictionary to the `data` argument. Your
56dictionary of data will automatically be form-encoded when the request is made::

big quick start updatesKenneth Reitzbefore adoption60558fd

lines 57–113why, one step back
57
58 >>> payload = {'key1': 'value1', 'key2': 'value2'}59 >>> r = requests.post("http://httpbin.org/post", data=payload)60 >>> print r.content61 {62 "origin": "179.13.100.4",63 "files": {},64 "form": {65 "key2": "value2",66 "key1": "value1"67 },68 "url": "http://httpbin.org/post",69 "args": {},70 "headers": {71 "Content-Length": "23",72 "Accept-Encoding": "identity, deflate, compress, gzip",73 "Accept": "*/*",74 "User-Agent": "python-requests/0.8.0",75 "Host": "127.0.0.1:7077",76 "Content-Type": "application/x-www-form-urlencoded"77 },78 "data": ""79 }8081There are many times that you want to send data that is not form-encoded. If you pass in a ``string`` instead of a ``dict``, that data will be posted directly.8283For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::8485 url = 'https://api.github.com/some/endpoint'86 payload = {'some': 'data'}8788 r = requests.post(url, data=json.dumps(payload))899091Custom Headers92--------------9394If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the95``headers`` parameter.9697For example, we didn't specify our content-type in the previous example::9899 url = 'https://api.github.com/some/endpoint'100 payload = {'some': 'data'}101 headers = {'content-type': 'application/json'}102103 r = requests.post(url, data=json.dumps(payload), headers=headers)104105106POST a Multipart-Encoded File107-----------------------------108109Requests makes it simple to upload Multipart-encoded files::110111 >>> url = 'http://httpbin.org/post'112 >>> files = {'report.xls': open('report.xls', 'rb')}113

file uploadsKenneth Reitzbefore adoption40c5480

line 114why, one step back
114 >>> r = requests.post(url, files=files)

Merge branch 'develop' of https://github.com/joequery/requests into developKenneth Reitzbefore adoption3d6937a

line 115why, one step back
115 >>> r.content

file uploadsKenneth Reitzbefore adoption40c5480

lines 116–118why, one step back
116 {
117 "origin": "179.13.100.4",118 "files": {

sp Kenneth Reitzbefore adoption3d49eb4

line 119why, one step back
119 "report.xls": "<censored...binary...data>"

file uploadsKenneth Reitzbefore adoption40c5480

lines 120–133why, one step back
120 },
121 "form": {},122 "url": "http://httpbin.org/post",123 "args": {},124 "headers": {125 "Content-Length": "3196",126 "Accept-Encoding": "identity, deflate, compress, gzip",127 "Accept": "*/*",128 "User-Agent": "python-requests/0.8.0",129 "Host": "httpbin.org:80",130 "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"131 },132 "data": ""133 }

Merge branch 'develop' of https://github.com/joequery/requests into developKenneth Reitzbefore adoption3d6937a

line 134why, one step back
134

Merge pull request #280 from darkrho/58e018af136190a2c757b13bf9371cecc2d51273Kenneth Reitzbefore adoption2a72235

lines 135–159why, one step back
135Setting filename explicitly::
136137 >>> url = 'http://httpbin.org/post'138 >>> files = {'file': ('report.xls', open('report.xls', 'rb'))}139140 >>> r = requests.post(url, files=files)141 >>> r.content142 {143 "origin": "179.13.100.4",144 "files": {145 "file": "<censored...binary...data>"146 },147 "form": {},148 "url": "http://httpbin.org/post",149 "args": {},150 "headers": {151 "Content-Length": "3196",152 "Accept-Encoding": "identity, deflate, compress, gzip",153 "Accept": "*/*",154 "User-Agent": "python-requests/0.8.0",155 "Host": "httpbin.org:80",156 "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"157 },158 "data": ""159 }

big quick start updatesKenneth Reitzbefore adoption60558fd

lines 160–161why, one step back
160
161

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 162–163why, one step back
162Response Status Codes
163---------------------

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 164why, one step back
164

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 165why, one step back
165We can check the response status code::

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 166why, one step back
166

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 167–168why, one step back
167 >>> r.status_code
168 200

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 169why, one step back
169

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 170–171why, one step back
170Requests also comes with a built-in status code lookup object for easy
171reference::

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 172why, one step back
172

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 173–174why, one step back
173 >>> r.status_code == requests.codes.ok
174 True

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 175why, one step back
175

big quick start updatesKenneth Reitzbefore adoption60558fd

line 176why, one step back
176If we made a bad request (non-200 response), we can raise it with

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 177why, one step back
177:class:`Response.raise_for_status()`::

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 178why, one step back
178

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 179–181why, one step back
179 >>> _r = requests.get('http://httpbin.org/status/404')
180 >>> _r.status_code181 404

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 182why, one step back
182

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 183–187why, one step back
183 >>> _r.raise_for_status()
184 Traceback (most recent call last):185 File "requests/models.py", line 394, in raise_for_status186 raise self.error187 urllib2.HTTPError: HTTP Error 404: NOT FOUND

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 188why, one step back
188

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 189why, one step back
189But, since our ``status_code`` was ``200``, when we call it::

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 190why, one step back
190

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 191–192why, one step back
191 >>> r.raise_for_status()
192 None

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 193why, one step back
193

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 194why, one step back
194All is well.

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

lines 195–196why, one step back
195
196

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 197–198why, one step back
197Response Headers
198----------------

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 199why, one step back
199

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 200–201why, one step back
200We can view the server's response headers with a simple Python dictionary
201interface::

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 202why, one step back
202

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 203–213why, one step back
203 >>> r.headers
204 {205 'status': '200 OK',206 'content-encoding': 'gzip',207 'transfer-encoding': 'chunked',208 'connection': 'close',209 'server': 'nginx/1.0.4',210 'x-runtime': '148ms',211 'etag': '"e1ca502697e5c9317743dc078f67693f"',212 'content-type': 'application/json; charset=utf-8'213 }

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 214why, one step back
214

Migrate new docs over.Kenneth Reitzbefore adoption4a7fdef

lines 215–216why, one step back
215The dictionary is special, though: it's made just for HTTP headers. According to
216`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTP

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 217why, one step back
217Headers are case-insensitive.

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 218why, one step back
218

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

line 219why, one step back
219So, we can access the headers using any capitalization we want::

Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea

line 220why, one step back
220

Merge branch 'develop'Kenneth Reitzbefore adoption81d5997

lines 221–252why, one step back
221 >>> r.headers['Content-Type']
222 'application/json; charset=utf-8'223224 >>> r.headers.get('content-type')225 'application/json; charset=utf-8'226227If a header doesn't exist in the Response, its value defaults to ``None``::228229 >>> r.headers['X-Random']230 None231232233Cookies234-------235236If a response contains some Cookies, you can get quick access to them::237238 >>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'239 >>> r = requests.get(url)240241 >>> print r.cookies242 {'requests-is': 'awesome'}243244To send your own cookies to the server, you can use the ``cookies``245parameter::246247 >>> url = 'http://httpbin.org/cookies'248 >>> cookies = dict(cookies_are='working')249250 >>> r = requests.get(url, cookies=cookies)251 >>> r.content252 '{"cookies": {"cookies_are": "working"}}'

Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0

lines 253–258why, one step back
253
254255Basic Authentication256--------------------257258Most web services require authentication. There many different types of

quicker startKenneth Reitzbefore adoption58c77ba

line 259why, one step back
259authentication, but the most common is HTTP Basic Auth.

Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0

line 260why, one step back
260

big quick start updatesKenneth Reitzbefore adoption60558fd

line 261why, one step back
261Making requests with Basic Auth is extremely simple::

Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0

lines 262–265why, one step back
262
263 >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))264 <Response [200]>265

Merge pull request #260 from joequery/doc_changesKenneth Reitzbefore adoptionfc0565f

lines 266–270why, one step back
266OAuth Authentication
267--------------------268269Miguel Araujo's `requests-oauth <http://pypi.python.org/pypi/requests-oauth>`_ project provides a simple interface for270establishing OAuth connections. Documentation and examples can be found on the requests-oauth `git repository <https://github.com/maraujop/requests-oauth>`_.

Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0

lines 271–274why, one step back
271
272Digest Authentication273---------------------274

quicker startKenneth Reitzbefore adoption58c77ba

line 275why, one step back
275Another popular form of web service protection is Digest Authentication::

Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0

lines 276–281why, one step back
276
277 >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'278 >>> requests.get(url, auth=('digest', 'user', 'pass'))279 <Response [200]>280281

redirection docsKenneth Reitzbefore adoption30377ca

lines 282–288why, one step back
282Redirection and History
283-----------------------284285Requests will automatically perform location redirection while using impodotent methods.286287GitHub redirects all HTTP requests to HTTPS. Let's see what happens::288

sp Kenneth Reitzbefore adoption3d49eb4

line 289why, one step back
289 >>> r = requests.get('http://github.com')

redirection docsKenneth Reitzbefore adoption30377ca

lines 290–302why, one step back
290 >>> r.url
291 'https://github.com/'292 >>> r.status_code293 200294 >>> r.history295 [<Response [301]>]296297The :class:`Response.history` list contains a list of the298:class:`Request` objects that were created in order to complete the request.299300If you're using GET, HEAD, or OPTIONS, you can disable redirection301handling with the ``disable_redirects`` parameter::302

sp Kenneth Reitzbefore adoption3d49eb4

line 303why, one step back
303 >>> r = requests.get('http://github.com')

redirection docsKenneth Reitzbefore adoption30377ca

lines 304–310why, one step back
304 >>> r.status_code
305 301306 >>> r.history307 []308309If you're using POST, PUT, PATCH, *&c*, you can also explicitly enable redirection as well::310

missing param in quick startKenneth Reitzbefore adoption45c9ecc

line 311why, one step back
311 >>> r = requests.post('http://github.com', allow_redirects=True)

redirection docsKenneth Reitzbefore adoption30377ca

lines 312–317why, one step back
312 >>> r.url
313 'https://github.com/'314 >>> r.history315 [<Response [301]>]316317

document timeoutsKenneth Reitzbefore adoption4ab7694

lines 318–347why, one step back
318Timeouts
319--------320321You can tell requests to stop waiting for a response after a given number of seconds with the ``timeout`` parameter::322323 >>> requests.get('http://github.com', timeout=0.001)324 Traceback (most recent call last):325 File "<stdin>", line 1, in <module>326 requests.exceptions.Timeout: Request timed out.327328.. admonition:: Note329330 ``timeout`` only effects the connection process itself, not the downloading of the respone body.331332333Errors and Exceptions334---------------------335336In the event of a network problem (e.g. DNS failure, refused connection, etc),337Requests will raise a :class:`ConnectionError` exception.338339In the event of the rare invalid HTTP response, Requests will raise340an :class:`HTTPError` exception.341342If a request times out, a :class:`Timeout` exception is raised.343344If a request exceeds the configured number of maximum redirections, a :class:`TooManyRedirects` exception is raised.345346All exceptions that Requests explicitly raises inherit from347:class:`requests.exceptions.RequestException`.

redirection docsKenneth Reitzbefore adoption30377ca

line 348why, one step back
348

Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0

lines 349–350why, one step back
349-----------------------
350

Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoptionc48f0d9

line 351why, one step back
351Ready for more? Check out the :ref:`advanced <advanced>` section.