quickstart.rst
This file
Path
docs/user/quickstart.rst
435 lines · 12.7 KiB
Last changed by
Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233
History of this fileTake it
The walk stopped after 200 commits: lines older than f2be5fa point at it.
Merge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
lines 1–70why, 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 Request22--------------2324Making 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::70Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption011f6da
line 71why, one step back71 >>> print(r.url)Merge pull request #1466 from s7v7nislands/fix_docCory Benfieldbefore adoptione0df4b5
line 72why, one step back72 http://httpbin.org/get?key2=value2&key1=value1Merge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
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.76Merge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
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/...Merge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
lines 88–101why, 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``Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233
lines 102–107why, one step back102whenever you call ``r.text``. You might want to do this in any situation where103you can apply special logic to work out what the encoding of the content will104be. For example, HTTP and XML have the ability to specify their encoding in105their body. In situations like this, you should use ``r.content`` to find the106encoding, and then set ``r.encoding``. This will let you use ``r.text`` with107the correct encoding.Merge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
lines 108–124why, one step back108109Requests will also use custom encodings in the event that you need them. If110you have created your own encoding and registered it with the ``codecs``111module, you can simply use the codec name as the value of ``r.encoding`` and112Requests will handle the decoding for you.113114Binary Response Content115-----------------------116117You can also access the response body as bytes, for non-text requests::118119 >>> r.content120 b'[{"repository":{"open_issues":0,"url":"https://github.com/...121122The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.123124For example, to create an image from binary data returned by a request, you canMerge pull request #1474 from Kwpolska/docfixKenneth Reitzbefore adoptiond83919a
line 125why, one step back125use the following code::Merge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
lines 126–141why, one step back126127 >>> from PIL import Image128 >>> from StringIO import StringIO129 >>> i = Image.open(StringIO(r.content))130131132JSON Response Content133---------------------134135There's also a builtin JSON decoder, in case you're dealing with JSON data::136137 >>> import requests138 >>> r = requests.get('https://github.com/timeline.json')139 >>> r.json()140 [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...141Merge pull request #1296 from sursh/masterKenneth Reitzbefore adoption5b937b3
lines 142–144why, one step back142In case the JSON decoding fails, ``r.json`` raises an exception. For example, if143the response gets a 401 (Unauthorized), attempting ``r.json`` raises ``ValueError:144No JSON object could be decoded``Merge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
lines 145–153why, one step back145146147Raw Response Content148--------------------149150In the rare case that you'd like to get the raw socket response from the151server, you can access ``r.raw``. If you want to do this, make sure you set152``stream=True`` in your initial request. Once you do, you can do this::153Merge pull request #1230 from davidfischer/trivial-docs-fixKenneth Reitzbefore adoption98ff29f
line 154why, one step back154 >>> r = requests.get('https://github.com/timeline.json', stream=True)Merge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
lines 155–159why, one step back155 >>> r.raw156 <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>157 >>> r.raw.read(10)158 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'159Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233
line 160why, one step back160In general, however, you should use a pattern like this to save what is beingMerge pull request #1695 from sigmavirus24/docsCory Benfieldbefore adoptionff2b496
lines 161–166why, one step back161streamed to a file::162163 with open(filename, 'wb') as fd:164 for chunk in r.iter_content(chunk_size):165 fd.write(chunk)166Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233
lines 167–169why, one step back167Using ``Response.iter_content`` will handle a lot of what you would otherwise168have to handle when using ``Response.raw`` directly. When streaming a169download, the above is the preferred and recommended way to retrieve theMerge pull request #1695 from sigmavirus24/docsCory Benfieldbefore adoptionff2b496
lines 170–171why, one step back170content.171Merge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
lines 172–192why, one step back172173Custom Headers174--------------175176If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the177``headers`` parameter.178179For example, we didn't specify our content-type in the previous example::180181 >>> import json182 >>> url = 'https://api.github.com/some/endpoint'183 >>> payload = {'some': 'data'}184 >>> headers = {'content-type': 'application/json'}185186 >>> r = requests.post(url, data=json.dumps(payload), headers=headers)187188189More complicated POST requests190------------------------------191192Typically, you want to send some form-encoded data — much like an HTML form.Merge pull request #1474 from Kwpolska/docfixKenneth Reitzbefore adoptiond83919a
line 193why, one step back193To do this, simply pass a dictionary to the ``data`` argument. YourMerge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
lines 194–282why, one step back194dictionary of data will automatically be form-encoded when the request is made::195196 >>> payload = {'key1': 'value1', 'key2': 'value2'}197 >>> r = requests.post("http://httpbin.org/post", data=payload)198 >>> print r.text199 {200 ...201 "form": {202 "key2": "value2",203 "key1": "value1"204 },205 ...206 }207208There 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.209210For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::211212 >>> import json213 >>> url = 'https://api.github.com/some/endpoint'214 >>> payload = {'some': 'data'}215216 >>> r = requests.post(url, data=json.dumps(payload))217218219POST a Multipart-Encoded File220-----------------------------221222Requests makes it simple to upload Multipart-encoded files::223224 >>> url = 'http://httpbin.org/post'225 >>> files = {'file': open('report.xls', 'rb')}226227 >>> r = requests.post(url, files=files)228 >>> r.text229 {230 ...231 "files": {232 "file": "<censored...binary...data>"233 },234 ...235 }236237You can set the filename explicitly::238239 >>> url = 'http://httpbin.org/post'240 >>> files = {'file': ('report.xls', open('report.xls', 'rb'))}241242 >>> r = requests.post(url, files=files)243 >>> r.text244 {245 ...246 "files": {247 "file": "<censored...binary...data>"248 },249 ...250 }251252If you want, you can send strings to be received as files::253254 >>> url = 'http://httpbin.org/post'255 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}256257 >>> r = requests.post(url, files=files)258 >>> r.text259 {260 ...261 "files": {262 "file": "some,data,to,send\\nanother,row,to,send\\n"263 },264 ...265 }266267268Response Status Codes269---------------------270271We can check the response status code::272273 >>> r = requests.get('http://httpbin.org/get')274 >>> r.status_code275 200276277Requests also comes with a built-in status code lookup object for easy278reference::279280 >>> r.status_code == requests.codes.ok281 True282Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptione0df216
line 283why, one step back283If we made a bad request (a 4XX client error or 5XX server error response), we can raise it withMerge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
lines 284–317why, one step back284:class:`Response.raise_for_status()`::285286 >>> bad_r = requests.get('http://httpbin.org/status/404')287 >>> bad_r.status_code288 404289290 >>> bad_r.raise_for_status()291 Traceback (most recent call last):292 File "requests/models.py", line 832, in raise_for_status293 raise http_error294 requests.exceptions.HTTPError: 404 Client Error295296But, since our ``status_code`` for ``r`` was ``200``, when we call297``raise_for_status()`` we get::298299 >>> r.raise_for_status()300 None301302All is well.303304305Response Headers306----------------307308We can view the server's response headers using a Python dictionary::309310 >>> r.headers311 {312 'content-encoding': 'gzip',313 'transfer-encoding': 'chunked',314 'connection': 'close',315 'server': 'nginx/1.0.4',316 'x-runtime': '148ms',317 'etag': '"e1ca502697e5c9317743dc078f67693f"',Merge pull request #1470 from Lukasa/carsetCory Benfieldbefore adoption949a29c
line 318why, one step back318 'content-type': 'application/json'Merge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
lines 319–327why, one step back319 }320321The dictionary is special, though: it's made just for HTTP headers. According to322`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTP323Headers are case-insensitive.324325So, we can access the headers using any capitalization we want::326327 >>> r.headers['Content-Type']Merge pull request #1470 from Lukasa/carsetCory Benfieldbefore adoption949a29c
line 328why, one step back328 'application/json'Merge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
lines 329–330why, one step back329330 >>> r.headers.get('content-type')Merge pull request #1470 from Lukasa/carsetCory Benfieldbefore adoption949a29c
line 331why, one step back331 'application/json'Merge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
lines 332–358why, one step back332333334Cookies335-------336337If a response contains some Cookies, you can get quick access to them::338339 >>> url = 'http://example.com/some/cookie/setting/url'340 >>> r = requests.get(url)341342 >>> r.cookies['example_cookie_name']343 'example_cookie_value'344345To send your own cookies to the server, you can use the ``cookies``346parameter::347348 >>> url = 'http://httpbin.org/cookies'349 >>> cookies = dict(cookies_are='working')350351 >>> r = requests.get(url, cookies=cookies)352 >>> r.text353 '{"cookies": {"cookies_are": "working"}}'354355356Redirection and History357-----------------------358Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption011f6da
lines 359–360why, one step back359Requests will automatically perform location redirection for all verbs except360HEAD.Merge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
lines 361–362why, one step back361362GitHub redirects all HTTP requests to HTTPS. We can use the ``history`` methodMerge pull request #1474 from Kwpolska/docfixKenneth Reitzbefore adoptiond83919a
line 363why, one step back363of the Response object to track redirection. Let's see what GitHub does::Merge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
lines 364–372why, one step back364365 >>> r = requests.get('http://github.com')366 >>> r.url367 'https://github.com/'368 >>> r.status_code369 200370 >>> r.history371 [<Response [301]>]372Merge pull request #1474 from Kwpolska/docfixKenneth Reitzbefore adoptiond83919a
lines 373–375why, one step back373The :class:`Response.history` list contains the :class:`Request` objects that374were created in order to complete the request. The list is sorted from the375oldest to the most recent request.Merge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
line 376why, one step back376Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption011f6da
lines 377–378why, one step back377If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable378redirection handling with the ``allow_redirects`` parameter::Merge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
lines 379–385why, one step back379380 >>> r = requests.get('http://github.com', allow_redirects=False)381 >>> r.status_code382 301383 >>> r.history384 []385Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption011f6da
line 386why, one step back386If you're using HEAD, you can enable redirection as well::Merge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
lines 387–397why, one step back387388 >>> r = requests.post('http://github.com', allow_redirects=True)389 >>> r.url390 'https://github.com/'391 >>> r.history392 [<Response [301]>]393394395Timeouts396--------397Merge pull request #1474 from Kwpolska/docfixKenneth Reitzbefore adoptiond83919a
line 398why, one step back398You can tell Requests to stop waiting for a response after a given number ofMerge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
lines 399–406why, one step back399seconds with the ``timeout`` parameter::400401 >>> requests.get('http://github.com', timeout=0.001)402 Traceback (most recent call last):403 File "<stdin>", line 1, in <module>404 requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)405406Merge pull request #1538 from enkore/patch-1Cory Benfieldbefore adoption0f40290
line 407why, one step back407.. admonition:: NoteMerge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
line 408why, one step back408Merge pull request #1579 from yang/patch-1Cory Benfieldbefore adoptionc1eb702
lines 409–412why, one step back409 ``timeout`` is not a time limit on the entire response download;410 rather, an exception is raised if the server has not issued a411 response for ``timeout`` seconds (more precisely, if no bytes have been412 received on the underlying socket for ``timeout`` seconds).Merge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
lines 413–418why, one step back413414415Errors and Exceptions416---------------------417418In the event of a network problem (e.g. DNS failure, refused connection, etc),Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptione0df216
line 419why, one step back419Requests will raise a :class:`~requests.exceptions.ConnectionError` exception.Merge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
line 420why, one step back420Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptione0df216
lines 421–422why, one step back421In the event of the rare invalid HTTP response, Requests will raise an422:class:`~requests.exceptions.HTTPError` exception.Merge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
line 423why, one step back423Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptione0df216
lines 424–425why, one step back424If a request times out, a :class:`~requests.exceptions.Timeout` exception is425raised.Merge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
lines 426–427why, one step back426427If a request exceeds the configured number of maximum redirections, aMerge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptione0df216
line 428why, one step back428:class:`~requests.exceptions.TooManyRedirects` exception is raised.Merge pull request #1161 from sigmavirus24/fix1159Kenneth Reitzbefore adoptionf2be5fa
lines 429–435why, one step back429430All exceptions that Requests explicitly raises inherit from431:class:`requests.exceptions.RequestException`.432433-----------------------434435Ready for more? Check out the :ref:`advanced <advanced>` section.