Skip to content
Myr

quickstart.rst

This file

Path

docs/user/quickstart.rst

452 lines · 12.6 KiB

Last changed by

Merge pull request #683 from jkleint/patch-1Kenneth Reitzbefore adoption38db8c2

History of this file

Take it

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

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.

v0.10.6Kenneth Reitzbefore adoption0eb5b63

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

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.

v0.10.6Kenneth Reitzbefore adoption0eb5b63

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

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 ::

v0.10.6Kenneth Reitzbefore adoption0eb5b63

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

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.

v0.10.6Kenneth Reitzbefore adoption0eb5b63

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

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::

v0.10.6Kenneth Reitzbefore adoption0eb5b63

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

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

Added r.json documentation (document ALL the awesome features!)Danilo Bargenbefore adoption1164450

lines 114–126why, one step back
114JSON Response Content
115---------------------116117There's also a builtin JSON decoder, in case you're dealing with JSON data::118119 >>> import requests120 >>> r = requests.get('https://github.com/timeline.json')121 >>> r.json122 [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...123124In case the JSON decoding fails, ``r.json`` simply returns ``None``.125126

v0.10.6Kenneth Reitzbefore adoption0eb5b63

lines 127–139why, one step back
127Raw Response Content
128--------------------129130In the rare case that you'd like to get the absolute raw socket response from the server,131you can access ``r.raw``::132133 >>> r.raw134 <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>135136 >>> r.raw.read(10)137 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'138139

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 140–141why, one step back
140Custom Headers
141--------------

v0.10.6Kenneth Reitzbefore adoption0eb5b63

line 142why, one step back
142

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

line 145why, one step back
145

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

line 147why, one step back
147

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 148–151why, one step back
148 >>> import json
149 >>> url = 'https://api.github.com/some/endpoint'150 >>> payload = {'some': 'data'}151 >>> headers = {'content-type': 'application/json'}

v0.10.6Kenneth Reitzbefore adoption0eb5b63

line 152why, one step back
152

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

line 154why, one step back
154

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 155–158why, one step back
155
156More complicated POST requests157------------------------------158

v0.10.6Kenneth Reitzbefore adoption0eb5b63

lines 159–166why, one step back
159Typically, you want to send some form-encoded data — much like an HTML form.
160To do this, simply pass a dictionary to the `data` argument. Your161dictionary of data will automatically be form-encoded when the request is made::162163 >>> payload = {'key1': 'value1', 'key2': 'value2'}164 >>> r = requests.post("http://httpbin.org/post", data=payload)165 >>> print r.text166 {

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

lines 168–171why, one step back
168 "form": {
169 "key2": "value2",170 "key1": "value1"171 },

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

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

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

line 182why, one step back
182

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

lines 184–196why, one step back
184
185186POST a Multipart-Encoded File187-----------------------------188189Requests makes it simple to upload Multipart-encoded files::190191 >>> url = 'http://httpbin.org/post'192 >>> files = {'report.xls': open('report.xls', 'rb')}193194 >>> r = requests.post(url, files=files)195 >>> r.text196 {

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

lines 198–200why, one step back
198 "files": {
199 "report.xls": "<censored...binary...data>"200 },

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

lines 202–203why, one step back
202 }
203

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

lines 205–211why, one step back
205
206 >>> url = 'http://httpbin.org/post'207 >>> files = {'file': ('report.xls', open('report.xls', 'rb'))}208209 >>> r = requests.post(url, files=files)210 >>> r.text211 {

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

lines 213–215why, one step back
213 "files": {
214 "file": "<censored...binary...data>"215 },

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

lines 217–218why, one step back
217 }
218

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

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

lines 220–226why, one step back
220
221 >>> url = 'http://httpbin.org/post'222 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')} 223224 >>> r = requests.post(url, files=files)225 >>> r.text226 {

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

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

lines 228–230why, one step back
228 "files": {
229 "file": "some,data,to,send\\nanother,row,to,send\\n"230 },

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

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

lines 232–233why, one step back
232 }
233

v0.10.6Kenneth Reitzbefore adoption0eb5b63

lines 234–239why, one step back
234
235Response Status Codes236---------------------237238We can check the response status code::239

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

lines 241–258why, one step back
241 >>> r.status_code
242 200243244Requests also comes with a built-in status code lookup object for easy245reference::246247 >>> r.status_code == requests.codes.ok248 True249250If we made a bad request (non-200 response), we can raise it with251:class:`Response.raise_for_status()`::252253 >>> _r = requests.get('http://httpbin.org/status/404')254 >>> _r.status_code255 404256257 >>> _r.raise_for_status()258 Traceback (most recent call last):

Merge pull request #683 from jkleint/patch-1Kenneth Reitzbefore adoption38db8c2

lines 259–261why, one step back
259 File "requests/models.py", line 832, in raise_for_status
260 raise http_error261 requests.exceptions.HTTPError: 404 Client Error

v0.10.6Kenneth Reitzbefore adoption0eb5b63

line 262why, one step back
262

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

lines 265–274why, one step back
265
266 >>> r.raise_for_status()267 None268269All is well.270271272Response Headers273----------------274

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

lines 276–314why, one step back
276
277 >>> r.headers278 {279 'status': '200 OK',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; charset=utf-8'287 }288289The dictionary is special, though: it's made just for HTTP headers. According to290`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTP291Headers are case-insensitive.292293So, we can access the headers using any capitalization we want::294295 >>> r.headers['Content-Type']296 'application/json; charset=utf-8'297298 >>> r.headers.get('content-type')299 'application/json; charset=utf-8'300301If a header doesn't exist in the Response, its value defaults to ``None``::302303 >>> r.headers['X-Random']304 None305306307Cookies308-------309310If a response contains some Cookies, you can get quick access to them::311312 >>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'313 >>> r = requests.get(url)314

update documentation to correspond to new cookie APIShivaram Lingamnenibefore adoptionfdd0821

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

lines 317–331why, one step back
317
318To send your own cookies to the server, you can use the ``cookies``319parameter::320321 >>> url = 'http://httpbin.org/cookies'322 >>> cookies = dict(cookies_are='working')323324 >>> r = requests.get(url, cookies=cookies)325 >>> r.text326 '{"cookies": {"cookies_are": "working"}}'327328329Basic Authentication330--------------------331

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

lines 333–364why, one step back
333authentication, but the most common is HTTP Basic Auth.
334335Making requests with Basic Auth is extremely simple::336337 >>> from requests.auth import HTTPBasicAuth338 >>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))339 <Response [200]>340341Due to the prevalence of HTTP Basic Auth, requests provides a shorthand for342this authentication method::343344 >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))345 <Response [200]>346347Providing the credentials as a tuple in this fashion is functionally equivalent348to the ``HTTPBasicAuth`` example above.349350351Digest Authentication352---------------------353354Another popular form of web service protection is Digest Authentication::355356 >>> from requests.auth import HTTPDigestAuth357 >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'358 >>> requests.get(url, auth=HTTPDigestAuth('user', 'pass'))359 <Response [200]>360361362OAuth Authentication363--------------------364

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

lines 369–373why, one step back
369
370371Redirection and History372-----------------------373

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

line 376why, one step back
376

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

lines 379–390why, one step back
379
380 >>> r = requests.get('http://github.com')381 >>> r.url382 'https://github.com/'383 >>> r.status_code384 200385 >>> r.history386 [<Response [301]>]387388The :class:`Response.history` list contains a list of the389:class:`Request` objects that were created in order to complete the request.390

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

lines 393–399why, one step back
393
394 >>> r = requests.get('http://github.com', allow_redirects=False)395 >>> r.status_code396 301397 >>> r.history398 []399

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

lines 402–412why, one step back
402
403 >>> r = requests.post('http://github.com', allow_redirects=True)404 >>> r.url405 'https://github.com/'406 >>> r.history407 [<Response [301]>]408409410Timeouts411--------412

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

lines 415–420why, one step back
415
416 >>> requests.get('http://github.com', timeout=0.001)417 Traceback (most recent call last):418 File "<stdin>", line 1, in <module>419 requests.exceptions.Timeout: Request timed out.420

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

line 422why, one step back
422

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

lines 425–437why, one step back
425
426427Errors and Exceptions428---------------------429430In the event of a network problem (e.g. DNS failure, refused connection, etc),431Requests will raise a :class:`ConnectionError` exception.432433In the event of the rare invalid HTTP response, Requests will raise434an :class:`HTTPError` exception.435436If a request times out, a :class:`Timeout` exception is raised.437

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

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

v0.10.6Kenneth Reitzbefore adoption0eb5b63

lines 440–443why, one step back
440
441All exceptions that Requests explicitly raises inherit from442:class:`requests.exceptions.RequestException`.443

Merge pull request #619 from Lukasa/developKenneth Reitzbefore adoptionad8205f

lines 444–448why, one step back
444You can refer to :ref:`Configuration API Docs <configurations>` for immediate
445raising of :class:`HTTPError` exceptions via the ``danger_mode`` option or446have Requests catch the majority of447:class:`requests.exceptions.RequestException` exceptions with the ``safe_mode``448option.

v0.10.6Kenneth Reitzbefore adoption0eb5b63

lines 449–452why, one step back
449
450-----------------------451452Ready for more? Check out the :ref:`advanced <advanced>` section.