Skip to content
Myr

quickstart.rst

This file

Path

docs/user/quickstart.rst

439 lines · 12.3 KiB

Last changed by

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

History of this file

Take it

The walk stopped after 200 commits: lines older than e7efce9 point at it.

models cleanupKenneth Reitzbefore adoptione7efce9

lines 1–17why, one step back
1.. _quickstart:
23Quickstart4==========56.. module:: requests.models78Eager to get started? This page gives a good introduction in how to get started9with Requests. This assumes you already have Requests installed. If you do not,10head over to the :ref:`Installation <install>` section.1112First, make sure that:1314* Requests is :ref:`installed <install>`15* Requests is :ref:`up-to-date <updates>`1617

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

line 18why, one step back
18Let's get started with some simple examples.

models cleanupKenneth Reitzbefore adoptione7efce9

lines 19–20why, one step back
19
20

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

line 21why, one step back
21Make a Request

models cleanupKenneth Reitzbefore adoptione7efce9

lines 22–23why, one step back
22------------------
23

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

models cleanupKenneth Reitzbefore adoptione7efce9

line 25why, one step back
25

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 26–28why, one step back
26Begin by importing the Requests module::
27 28 >>> import requests

models cleanupKenneth Reitzbefore adoptione7efce9

line 29why, one step back
29

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 30–31why, one step back
30Now, let's try to get a webpage. For this example, let's get GitHub's public
31timeline ::

models cleanupKenneth Reitzbefore adoptione7efce9

line 32why, one step back
32

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 33–34why, one step back
33 >>> r = requests.get('https://github.com/timeline.json')
34

models cleanupKenneth Reitzbefore adoptione7efce9

line 35why, one step back
35Now, we have a :class:`Response` object called ``r``. We can get all the

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

line 36why, one step back
36information we need from this object.

models cleanupKenneth Reitzbefore adoptione7efce9

line 37why, one step back
37

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 38–41why, one step back
38Requests' simple API means that all forms of HTTP request are as obvious. For
39example, this is how you make an HTTP POST request::40 41 >>> r = requests.post("http://httpbin.org/post")

Merge branch 'develop' of github.com:kennethreitz/requests into developKenneth Reitzbefore adoption4c1852f

line 42why, one step back
42

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 43–65why, one step back
43Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and
44OPTIONS? These are all just as simple::45 46 >>> r = requests.put("http://httpbin.org/put")47 >>> r = requests.delete("http://httpbin.org/delete")48 >>> r = requests.head("http://httpbin.org/get")49 >>> r = requests.options("http://httpbin.org/get")5051That's all well and good, but it's also only the start of what Requests can52do.535455Passing Parameters In URLs56--------------------------5758You often want to send some sort of data in the URL's query string. If59you were constructing the URL by hand, this data would be given as key/value60pairs in the URL after a question mark, e.g. ``httpbin.org/get?key=val``.61Requests allows you to provide these arguments as a dictionary, using the62``params`` keyword argument. As an example, if you wanted to pass63``key1=value1`` and ``key2=value2`` to ``httpbin.org/get``, you would use the64following code::65

Merge branch 'develop' of github.com:kennethreitz/requests into developKenneth Reitzbefore adoption4c1852f

lines 66–68why, one step back
66 >>> payload = {'key1': 'value1', 'key2': 'value2'}
67 >>> r = requests.get("http://httpbin.org/get", params=payload)68

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

line 69why, one step back
69You can see that the URL has been correctly encoded by printing the URL::

Merge branch 'develop' of github.com:kennethreitz/requests into developKenneth Reitzbefore adoption4c1852f

line 70why, one step back
70

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 71–73why, one step back
71 >>> print r.url
72 u'http://httpbin.org/get?key2=value2&key1=value1'73

models cleanupKenneth Reitzbefore adoptione7efce9

lines 74–77why, one step back
74
75Response Content76----------------77

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 78–79why, one step back
78We can read the content of the server's response. Consider the GitHub timeline
79again::

models cleanupKenneth Reitzbefore adoptione7efce9

line 80why, one step back
80

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 81–82why, one step back
81 >>> import requests
82 >>> r = requests.get('https://github.com/timeline.json')

models cleanupKenneth Reitzbefore adoptione7efce9

lines 83–105why, one step back
83 >>> r.text
84 '[{"repository":{"open_issues":0,"url":"https://github.com/...8586Requests will automatically decode content from the server. Most unicode87charsets are seamlessly decoded.8889When you make a request, ``r.encoding`` is set, based on the HTTP headers.90Requests will use that encoding when you access ``r.text``. If ``r.encoding``91is ``None``, Requests will make an extremely educated guess of the encoding92of the response body. You can manually set ``r.encoding`` to any encoding93you'd like, and that charset will be used.949596Binary Response Content97-----------------------9899You can also access the response body as bytes, for non-text requests::100101 >>> r.content102 b'[{"repository":{"open_issues":0,"url":"https://github.com/...103104The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.105

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

line 106why, one step back
106For example, to create an image from binary data returned by a request, you can

Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoption14f57f6

lines 107–112why, one step back
107use the following code:
108109 >>> from PIL import Image110 >>> from StringIO import StringIO111 >>> i = Image.open(StringIO(r.content))112

models cleanupKenneth Reitzbefore adoptione7efce9

lines 113–126why, one step back
113
114Raw Response Content115--------------------116117In the rare case that you'd like to get the absolute raw socket response from the server,118you can access ``r.raw``::119120 >>> r.raw121 <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>122123 >>> r.raw.read(10)124 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'125126

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 127–128why, one step back
127Custom Headers
128--------------

models cleanupKenneth Reitzbefore adoptione7efce9

line 129why, one step back
129

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 130–131why, one step back
130If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the
131``headers`` parameter.

models cleanupKenneth Reitzbefore adoptione7efce9

line 132why, one step back
132

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

line 133why, one step back
133For example, we didn't specify our content-type in the previous example::

models cleanupKenneth Reitzbefore adoptione7efce9

line 134why, one step back
134

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 135–138why, one step back
135 >>> import json
136 >>> url = 'https://api.github.com/some/endpoint'137 >>> payload = {'some': 'data'}138 >>> headers = {'content-type': 'application/json'}

models cleanupKenneth Reitzbefore adoptione7efce9

line 139why, one step back
139

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

line 140why, one step back
140 >>> r = requests.post(url, data=json.dumps(payload), headers=headers)

models cleanupKenneth Reitzbefore adoptione7efce9

line 141why, one step back
141

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 142–145why, one step back
142
143More complicated POST requests144------------------------------145

models cleanupKenneth Reitzbefore adoptione7efce9

lines 146–153why, one step back
146Typically, you want to send some form-encoded data — much like an HTML form.
147To do this, simply pass a dictionary to the `data` argument. Your148dictionary of data will automatically be form-encoded when the request is made::149150 >>> payload = {'key1': 'value1', 'key2': 'value2'}151 >>> r = requests.post("http://httpbin.org/post", data=payload)152 >>> print r.text153 {

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

line 154why, one step back
154 // ...snip... //

models cleanupKenneth Reitzbefore adoptione7efce9

lines 155–158why, one step back
155 "form": {
156 "key2": "value2",157 "key1": "value1"158 },

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

line 159why, one step back
159 // ...snip... //

models cleanupKenneth Reitzbefore adoptione7efce9

lines 160–165why, one step back
160 }
161162There 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.163164For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::165

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 166–168why, one step back
166 >>> import json
167 >>> url = 'https://api.github.com/some/endpoint'168 >>> payload = {'some': 'data'}

models cleanupKenneth Reitzbefore adoptione7efce9

line 169why, one step back
169

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

line 170why, one step back
170 >>> r = requests.post(url, data=json.dumps(payload))

models cleanupKenneth Reitzbefore adoptione7efce9

lines 171–183why, one step back
171
172173POST a Multipart-Encoded File174-----------------------------175176Requests makes it simple to upload Multipart-encoded files::177178 >>> url = 'http://httpbin.org/post'179 >>> files = {'report.xls': open('report.xls', 'rb')}180181 >>> r = requests.post(url, files=files)182 >>> r.text183 {

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

line 184why, one step back
184 // ...snip... //

models cleanupKenneth Reitzbefore adoptione7efce9

lines 185–187why, one step back
185 "files": {
186 "report.xls": "<censored...binary...data>"187 },

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

line 188why, one step back
188 // ...snip... //

models cleanupKenneth Reitzbefore adoptione7efce9

lines 189–190why, one step back
189 }
190

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

line 191why, one step back
191You can set the filename explicitly::

models cleanupKenneth Reitzbefore adoptione7efce9

lines 192–198why, one step back
192
193 >>> url = 'http://httpbin.org/post'194 >>> files = {'file': ('report.xls', open('report.xls', 'rb'))}195196 >>> r = requests.post(url, files=files)197 >>> r.text198 {

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

line 199why, one step back
199 // ...snip... //

models cleanupKenneth Reitzbefore adoptione7efce9

lines 200–202why, one step back
200 "files": {
201 "file": "<censored...binary...data>"202 },

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

line 203why, one step back
203 // ...snip... //

models cleanupKenneth Reitzbefore adoptione7efce9

lines 204–205why, one step back
204 }
205

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

line 206why, one step back
206If you want, you can send strings to be received as files::

Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoption2a7811b

lines 207–213why, one step back
207
208 >>> url = 'http://httpbin.org/post'209 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')} 210211 >>> r = requests.post(url, files=files)212 >>> r.text213 {

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

line 214why, one step back
214 // ...snip... //

Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoption2a7811b

lines 215–217why, one step back
215 "files": {
216 "file": "some,data,to,send\\nanother,row,to,send\\n"217 },

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

line 218why, one step back
218 // ...snip... //

Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoption2a7811b

lines 219–220why, one step back
219 }
220

models cleanupKenneth Reitzbefore adoptione7efce9

lines 221–226why, one step back
221
222Response Status Codes223---------------------224225We can check the response status code::226

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

line 227why, one step back
227 >>> r = requests.get("http://httpbin.org/get')

models cleanupKenneth Reitzbefore adoptione7efce9

lines 228–249why, one step back
228 >>> r.status_code
229 200230231Requests also comes with a built-in status code lookup object for easy232reference::233234 >>> r.status_code == requests.codes.ok235 True236237If we made a bad request (non-200 response), we can raise it with238:class:`Response.raise_for_status()`::239240 >>> _r = requests.get('http://httpbin.org/status/404')241 >>> _r.status_code242 404243244 >>> _r.raise_for_status()245 Traceback (most recent call last):246 File "requests/models.py", line 394, in raise_for_status247 raise self.error248 urllib2.HTTPError: HTTP Error 404: NOT FOUND249

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 250–251why, one step back
250But, since our ``status_code`` for ``r`` was ``200``, when we call
251``raise_for_status()`` we get::

models cleanupKenneth Reitzbefore adoptione7efce9

lines 252–261why, one step back
252
253 >>> r.raise_for_status()254 None255256All is well.257258259Response Headers260----------------261

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

line 262why, one step back
262We can view the server's response headers using a Python dictionary::

models cleanupKenneth Reitzbefore adoptione7efce9

lines 263–301why, one step back
263
264 >>> r.headers265 {266 'status': '200 OK',267 'content-encoding': 'gzip',268 'transfer-encoding': 'chunked',269 'connection': 'close',270 'server': 'nginx/1.0.4',271 'x-runtime': '148ms',272 'etag': '"e1ca502697e5c9317743dc078f67693f"',273 'content-type': 'application/json; charset=utf-8'274 }275276The dictionary is special, though: it's made just for HTTP headers. According to277`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTP278Headers are case-insensitive.279280So, we can access the headers using any capitalization we want::281282 >>> r.headers['Content-Type']283 'application/json; charset=utf-8'284285 >>> r.headers.get('content-type')286 'application/json; charset=utf-8'287288If a header doesn't exist in the Response, its value defaults to ``None``::289290 >>> r.headers['X-Random']291 None292293294Cookies295-------296297If a response contains some Cookies, you can get quick access to them::298299 >>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'300 >>> r = requests.get(url)301

update documentation to correspond to new cookie APIShivaram Lingamnenibefore adoptionfdd0821

lines 302–303why, one step back
302 >>> r.cookies['requests-is']
303 'awesome'

models cleanupKenneth Reitzbefore adoptione7efce9

lines 304–318why, one step back
304
305To send your own cookies to the server, you can use the ``cookies``306parameter::307308 >>> url = 'http://httpbin.org/cookies'309 >>> cookies = dict(cookies_are='working')310311 >>> r = requests.get(url, cookies=cookies)312 >>> r.text313 '{"cookies": {"cookies_are": "working"}}'314315316Basic Authentication317--------------------318

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

line 319why, one step back
319Many web services require authentication. There many different types of

models cleanupKenneth Reitzbefore adoptione7efce9

lines 320–351why, one step back
320authentication, but the most common is HTTP Basic Auth.
321322Making requests with Basic Auth is extremely simple::323324 >>> from requests.auth import HTTPBasicAuth325 >>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))326 <Response [200]>327328Due to the prevalence of HTTP Basic Auth, requests provides a shorthand for329this authentication method::330331 >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))332 <Response [200]>333334Providing the credentials as a tuple in this fashion is functionally equivalent335to the ``HTTPBasicAuth`` example above.336337338Digest Authentication339---------------------340341Another popular form of web service protection is Digest Authentication::342343 >>> from requests.auth import HTTPDigestAuth344 >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'345 >>> requests.get(url, auth=HTTPDigestAuth('user', 'pass'))346 <Response [200]>347348349OAuth Authentication350--------------------351

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 352–355why, one step back
352Miguel Araujo's `requests-oauth <http://pypi.python.org/pypi/requests-oauth>`_
353project provides a simple interface for establishing OAuth connections.354Documentation and examples can be found on the requests-oauth355`git repository <https://github.com/maraujop/requests-oauth>`_.

models cleanupKenneth Reitzbefore adoptione7efce9

lines 356–360why, one step back
356
357358Redirection and History359-----------------------360

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 361–362why, one step back
361Requests will automatically perform location redirection while using the GET
362and OPTIONS verbs.

models cleanupKenneth Reitzbefore adoptione7efce9

line 363why, one step back
363

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 364–365why, one step back
364GitHub redirects all HTTP requests to HTTPS. We can use the ``history`` method
365of the Response object to track redirection. Let's see what Github does::

models cleanupKenneth Reitzbefore adoptione7efce9

lines 366–377why, one step back
366
367 >>> r = requests.get('http://github.com')368 >>> r.url369 'https://github.com/'370 >>> r.status_code371 200372 >>> r.history373 [<Response [301]>]374375The :class:`Response.history` list contains a list of the376:class:`Request` objects that were created in order to complete the request.377

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 378–379why, one step back
378If you're using GET or OPTIONS, you can disable redirection handling with the
379``allow_redirects`` parameter::

models cleanupKenneth Reitzbefore adoptione7efce9

lines 380–386why, one step back
380
381 >>> r = requests.get('http://github.com', allow_redirects=False)382 >>> r.status_code383 301384 >>> r.history385 []386

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 387–388why, one step back
387If you're using POST, PUT, PATCH, DELETE or HEAD, you can enable
388redirection as well::

models cleanupKenneth Reitzbefore adoptione7efce9

lines 389–399why, one step back
389
390 >>> r = requests.post('http://github.com', allow_redirects=True)391 >>> r.url392 'https://github.com/'393 >>> r.history394 [<Response [301]>]395396397Timeouts398--------399

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 400–401why, one step back
400You can tell requests to stop waiting for a response after a given number of
401seconds with the ``timeout`` parameter::

models cleanupKenneth Reitzbefore adoptione7efce9

lines 402–407why, one step back
402
403 >>> requests.get('http://github.com', timeout=0.001)404 Traceback (most recent call last):405 File "<stdin>", line 1, in <module>406 requests.exceptions.Timeout: Request timed out.407

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

line 408why, one step back
408.. admonition:: Note:

models cleanupKenneth Reitzbefore adoptione7efce9

line 409why, one step back
409

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 410–411why, one step back
410 ``timeout`` only effects the connection process itself, not the
411 downloading of the response body.

models cleanupKenneth Reitzbefore adoptione7efce9

lines 412–424why, one step back
412
413414Errors and Exceptions415---------------------416417In the event of a network problem (e.g. DNS failure, refused connection, etc),418Requests will raise a :class:`ConnectionError` exception.419420In the event of the rare invalid HTTP response, Requests will raise421an :class:`HTTPError` exception.422423If a request times out, a :class:`Timeout` exception is raised.424

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 425–426why, one step back
425If a request exceeds the configured number of maximum redirections, a
426:class:`TooManyRedirects` exception is raised.

models cleanupKenneth Reitzbefore adoptione7efce9

lines 427–430why, one step back
427
428All exceptions that Requests explicitly raises inherit from429:class:`requests.exceptions.RequestException`.430

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 431–435why, one step back
431You can refer to :ref:`Configuration API Docs <configurations>` for immediate
432raising of :class:`HTTPError` exceptions via the ``danger_mode`` option or433have Requests catch the majority of434:class:`requests.exceptions.RequestException` exceptions with the ``safe_mode``435option.

models cleanupKenneth Reitzbefore adoptione7efce9

lines 436–439why, one step back
436
437-----------------------438439Ready for more? Check out the :ref:`advanced <advanced>` section.