quickstart.rst
This file
Path
docs/user/quickstart.rst
419 lines · 11.9 KiB
Last changed by
Merge pull request #1579 from yang/patch-1Cory Benfieldbefore adoptionc1eb702
History of this fileTake it
The walk stopped after 200 commits: lines older than 6e780fa point at it.
remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 1–21why, one step back1.. _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>`161718Let's get started with some simple examples.192021Make a Requestupdate docsKenneth Reitzbefore adoption5b5ff69
line 22why, one step back22--------------remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 23–71why, one step back2324Making a request with Requests is very simple.2526Begin by importing the Requests module::2728 >>> import requests2930Now, let's try to get a webpage. For this example, let's get GitHub's public31timeline ::3233 >>> r = requests.get('https://github.com/timeline.json')3435Now, we have a :class:`Response` object called ``r``. We can get all the36information we need from this object.3738Requests' simple API means that all forms of HTTP request are as obvious. For39example, this is how you make an HTTP POST request::4041 >>> r = requests.post("http://httpbin.org/post")4243Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and44OPTIONS? These are all just as simple::4546 >>> 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::6566 >>> payload = {'key1': 'value1', 'key2': 'value2'}67 >>> r = requests.get("http://httpbin.org/get", params=payload)6869You can see that the URL has been correctly encoded by printing the URL::7071 >>> print r.urlMerge pull request #1466 from s7v7nislands/fix_docCory Benfieldbefore adoptione0df4b5
line 72why, one step back72 http://httpbin.org/get?key2=value2&key1=value1remove unused timeoutKenneth Reitzbefore adoption6e780fa
line 73why, one step back73Merge pull request #1464 from dpursehouse/document-none-not-sentCory Benfieldbefore adoption3229365
lines 74–76why, one step back74Note that any dictionary key whose value is ``None`` will not be added to the75URL's query string.76remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 77–86why, one step back7778Response Content79----------------8081We can read the content of the server's response. Consider the GitHub timeline82again::8384 >>> import requests85 >>> r = requests.get('https://github.com/timeline.json')86 >>> r.textMerge pull request #1466 from s7v7nislands/fix_docCory Benfieldbefore adoptione0df4b5
line 87why, one step back87 u'[{"repository":{"open_issues":0,"url":"https://github.com/...remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 88–119why, one step back8889Requests will automatically decode content from the server. Most unicode90charsets are seamlessly decoded.9192When you make a request, Requests makes educated guesses about the encoding of93the response based on the HTTP headers. The text encoding guessed by Requests94is used when you access ``r.text``. You can find out what encoding Requests is95using, and change it, using the ``r.encoding`` property::9697 >>> r.encoding98 'utf-8'99 >>> r.encoding = 'ISO-8859-1'100101If you change the encoding, Requests will use the new value of ``r.encoding``102whenever you call ``r.text``.103104Requests will also use custom encodings in the event that you need them. If105you have created your own encoding and registered it with the ``codecs``106module, you can simply use the codec name as the value of ``r.encoding`` and107Requests will handle the decoding for you.108109Binary Response Content110-----------------------111112You can also access the response body as bytes, for non-text requests::113114 >>> r.content115 b'[{"repository":{"open_issues":0,"url":"https://github.com/...116117The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.118119For example, to create an image from binary data returned by a request, you canMerge pull request #1474 from Kwpolska/docfixKenneth Reitzbefore adoptiond83919a
line 120why, one step back120use the following code::remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 121–136why, one step back121122 >>> from PIL import Image123 >>> from StringIO import StringIO124 >>> i = Image.open(StringIO(r.content))125126127JSON Response Content128---------------------129130There's also a builtin JSON decoder, in case you're dealing with JSON data::131132 >>> import requests133 >>> r = requests.get('https://github.com/timeline.json')134 >>> r.json()135 [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...136Merge pull request #1296 from sursh/masterKenneth Reitzbefore adoption5b937b3
lines 137–139why, one step back137In case the JSON decoding fails, ``r.json`` raises an exception. For example, if138the response gets a 401 (Unauthorized), attempting ``r.json`` raises ``ValueError:139No JSON object could be decoded``remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 140–148why, one step back140141142Raw Response Content143--------------------144145In the rare case that you'd like to get the raw socket response from the146server, you can access ``r.raw``. If you want to do this, make sure you set147``stream=True`` in your initial request. Once you do, you can do this::148Merge pull request #1230 from davidfischer/trivial-docs-fixKenneth Reitzbefore adoption98ff29f
line 149why, one step back149 >>> r = requests.get('https://github.com/timeline.json', stream=True)remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 150–175why, one step back150 >>> r.raw151 <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>152 >>> r.raw.read(10)153 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'154155156Custom Headers157--------------158159If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the160``headers`` parameter.161162For example, we didn't specify our content-type in the previous example::163164 >>> import json165 >>> url = 'https://api.github.com/some/endpoint'166 >>> payload = {'some': 'data'}167 >>> headers = {'content-type': 'application/json'}168169 >>> r = requests.post(url, data=json.dumps(payload), headers=headers)170171172More complicated POST requests173------------------------------174175Typically, you want to send some form-encoded data — much like an HTML form.Merge pull request #1474 from Kwpolska/docfixKenneth Reitzbefore adoptiond83919a
line 176why, one step back176To do this, simply pass a dictionary to the ``data`` argument. Yourremove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 177–182why, one step back177dictionary of data will automatically be form-encoded when the request is made::178179 >>> payload = {'key1': 'value1', 'key2': 'value2'}180 >>> r = requests.post("http://httpbin.org/post", data=payload)181 >>> print r.text182 {update docsKenneth Reitzbefore adoption5b5ff69
line 183why, one step back183 ...remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 184–187why, one step back184 "form": {185 "key2": "value2",186 "key1": "value1"187 },update docsKenneth Reitzbefore adoption5b5ff69
line 188why, one step back188 ...remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 189–212why, one step back189 }190191There 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.192193For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::194195 >>> import json196 >>> url = 'https://api.github.com/some/endpoint'197 >>> payload = {'some': 'data'}198199 >>> r = requests.post(url, data=json.dumps(payload))200201202POST a Multipart-Encoded File203-----------------------------204205Requests makes it simple to upload Multipart-encoded files::206207 >>> url = 'http://httpbin.org/post'208 >>> files = {'file': open('report.xls', 'rb')}209210 >>> r = requests.post(url, files=files)211 >>> r.text212 {update docsKenneth Reitzbefore adoption5b5ff69
line 213why, one step back213 ...remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 214–216why, one step back214 "files": {215 "file": "<censored...binary...data>"216 },update docsKenneth Reitzbefore adoption5b5ff69
line 217why, one step back217 ...remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 218–227why, one step back218 }219220You can set the filename explicitly::221222 >>> url = 'http://httpbin.org/post'223 >>> files = {'file': ('report.xls', open('report.xls', 'rb'))}224225 >>> r = requests.post(url, files=files)226 >>> r.text227 {update docsKenneth Reitzbefore adoption5b5ff69
line 228why, one step back228 ...remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 229–231why, one step back229 "files": {230 "file": "<censored...binary...data>"231 },update docsKenneth Reitzbefore adoption5b5ff69
line 232why, one step back232 ...remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 233–242why, one step back233 }234235If you want, you can send strings to be received as files::236237 >>> url = 'http://httpbin.org/post'238 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}239240 >>> r = requests.post(url, files=files)241 >>> r.text242 {update docsKenneth Reitzbefore adoption5b5ff69
line 243why, one step back243 ...remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 244–246why, one step back244 "files": {245 "file": "some,data,to,send\\nanother,row,to,send\\n"246 },update docsKenneth Reitzbefore adoption5b5ff69
line 247why, one step back247 ...remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 248–265why, one step back248 }249250251Response Status Codes252---------------------253254We can check the response status code::255256 >>> r = requests.get('http://httpbin.org/get')257 >>> r.status_code258 200259260Requests also comes with a built-in status code lookup object for easy261reference::262263 >>> r.status_code == requests.codes.ok264 True265Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptione0df216
line 266why, one step back266If we made a bad request (a 4XX client error or 5XX server error response), we can raise it withremove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 267–300why, one step back267:class:`Response.raise_for_status()`::268269 >>> bad_r = requests.get('http://httpbin.org/status/404')270 >>> bad_r.status_code271 404272273 >>> bad_r.raise_for_status()274 Traceback (most recent call last):275 File "requests/models.py", line 832, in raise_for_status276 raise http_error277 requests.exceptions.HTTPError: 404 Client Error278279But, since our ``status_code`` for ``r`` was ``200``, when we call280``raise_for_status()`` we get::281282 >>> r.raise_for_status()283 None284285All is well.286287288Response Headers289----------------290291We can view the server's response headers using a Python dictionary::292293 >>> r.headers294 {295 'content-encoding': 'gzip',296 'transfer-encoding': 'chunked',297 'connection': 'close',298 'server': 'nginx/1.0.4',299 'x-runtime': '148ms',300 'etag': '"e1ca502697e5c9317743dc078f67693f"',Merge pull request #1470 from Lukasa/carsetCory Benfieldbefore adoption949a29c
line 301why, one step back301 'content-type': 'application/json'remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 302–310why, one step back302 }303304The dictionary is special, though: it's made just for HTTP headers. According to305`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTP306Headers are case-insensitive.307308So, we can access the headers using any capitalization we want::309310 >>> r.headers['Content-Type']Merge pull request #1470 from Lukasa/carsetCory Benfieldbefore adoption949a29c
line 311why, one step back311 'application/json'remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 312–313why, one step back312313 >>> r.headers.get('content-type')Merge pull request #1470 from Lukasa/carsetCory Benfieldbefore adoption949a29c
line 314why, one step back314 'application/json'remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 315–321why, one step back315316317Cookies318-------319320If a response contains some Cookies, you can get quick access to them::321Merge pull request #1107 from Lukasa/masterKenneth Reitzbefore adoptionf038f68
line 322why, one step back322 >>> url = 'http://example.com/some/cookie/setting/url'remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 323–324why, one step back323 >>> r = requests.get(url)324Merge pull request #1107 from Lukasa/masterKenneth Reitzbefore adoptionf038f68
lines 325–326why, one step back325 >>> r.cookies['example_cookie_name']326 'example_cookie_value'remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 327–345why, one step back327328To send your own cookies to the server, you can use the ``cookies``329parameter::330331 >>> url = 'http://httpbin.org/cookies'332 >>> cookies = dict(cookies_are='working')333334 >>> r = requests.get(url, cookies=cookies)335 >>> r.text336 '{"cookies": {"cookies_are": "working"}}'337338339Redirection and History340-----------------------341342Requests will automatically perform location redirection while using the GET343and OPTIONS verbs.344345GitHub redirects all HTTP requests to HTTPS. We can use the ``history`` methodMerge pull request #1474 from Kwpolska/docfixKenneth Reitzbefore adoptiond83919a
line 346why, one step back346of the Response object to track redirection. Let's see what GitHub does::remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 347–355why, one step back347348 >>> r = requests.get('http://github.com')349 >>> r.url350 'https://github.com/'351 >>> r.status_code352 200353 >>> r.history354 [<Response [301]>]355Merge pull request #1474 from Kwpolska/docfixKenneth Reitzbefore adoptiond83919a
lines 356–358why, one step back356The :class:`Response.history` list contains the :class:`Request` objects that357were created in order to complete the request. The list is sorted from the358oldest to the most recent request.remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 359–381why, one step back359360If you're using GET or OPTIONS, you can disable redirection handling with the361``allow_redirects`` parameter::362363 >>> r = requests.get('http://github.com', allow_redirects=False)364 >>> r.status_code365 301366 >>> r.history367 []368369If you're using POST, PUT, PATCH, DELETE or HEAD, you can enable370redirection as well::371372 >>> r = requests.post('http://github.com', allow_redirects=True)373 >>> r.url374 'https://github.com/'375 >>> r.history376 [<Response [301]>]377378379Timeouts380--------381Merge pull request #1474 from Kwpolska/docfixKenneth Reitzbefore adoptiond83919a
line 382why, one step back382You can tell Requests to stop waiting for a response after a given number ofremove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 383–387why, one step back383seconds with the ``timeout`` parameter::384385 >>> requests.get('http://github.com', timeout=0.001)386 Traceback (most recent call last):387 File "<stdin>", line 1, in <module>timeoutKenneth Reitzbefore adoptionf1d51aa
lines 388–389why, one step back388 requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)389remove unused timeoutKenneth Reitzbefore adoption6e780fa
line 390why, one step back390Merge pull request #1538 from enkore/patch-1Cory Benfieldbefore adoption0f40290
line 391why, one step back391.. admonition:: Noteremove unused timeoutKenneth Reitzbefore adoption6e780fa
line 392why, one step back392Merge pull request #1579 from yang/patch-1Cory Benfieldbefore adoptionc1eb702
lines 393–396why, one step back393 ``timeout`` is not a time limit on the entire response download;394 rather, an exception is raised if the server has not issued a395 response for ``timeout`` seconds (more precisely, if no bytes have been396 received on the underlying socket for ``timeout`` seconds).remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 397–402why, one step back397398399Errors and Exceptions400---------------------401402In the event of a network problem (e.g. DNS failure, refused connection, etc),Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptione0df216
line 403why, one step back403Requests will raise a :class:`~requests.exceptions.ConnectionError` exception.remove unused timeoutKenneth Reitzbefore adoption6e780fa
line 404why, one step back404Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptione0df216
lines 405–406why, one step back405In the event of the rare invalid HTTP response, Requests will raise an406:class:`~requests.exceptions.HTTPError` exception.remove unused timeoutKenneth Reitzbefore adoption6e780fa
line 407why, one step back407Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptione0df216
lines 408–409why, one step back408If a request times out, a :class:`~requests.exceptions.Timeout` exception is409raised.remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 410–411why, one step back410411If a request exceeds the configured number of maximum redirections, aMerge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptione0df216
line 412why, one step back412:class:`~requests.exceptions.TooManyRedirects` exception is raised.remove unused timeoutKenneth Reitzbefore adoption6e780fa
lines 413–419why, one step back413414All exceptions that Requests explicitly raises inherit from415:class:`requests.exceptions.RequestException`.416417-----------------------418419Ready for more? Check out the :ref:`advanced <advanced>` section.