quickstart.rst
This file
Path
docs/user/quickstart.rst
463 lines · 14.0 KiB
Last changed by
Merge pull request #2493 from yasoob/masterCory Benfieldbefore adoptioncd3f7eb
History of this fileTake it
The walk stopped after 200 commits: lines older than b1c8fd3 point at it.
Merge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
lines 1–8why, one step back1.. _quickstart:23Quickstart4==========56.. module:: requests.models78Eager to get started? This page gives a good introduction in how to get startedMerge pull request #2138 from dpursehouse/more-doc-updatesCory Benfieldbefore adoption587a515
line 9why, one step back9with Requests.Merge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
lines 10–31why, one step back1011First, make sure that:1213* Requests is :ref:`installed <install>`14* Requests is :ref:`up-to-date <updates>`151617Let's get started with some simple examples.181920Make a Request21--------------2223Making a request with Requests is very simple.2425Begin by importing the Requests module::2627 >>> import requests2829Now, let's try to get a webpage. For this example, let's get GitHub's public30timeline ::31Merge pull request #2183 from Lukasa/docupdateKenneth Reitzbefore adoption7e24176
line 32why, one step back32 >>> r = requests.get('https://api.github.com/events')Merge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
line 33why, one step back33Merge pull request #2213 from kennethreitz/req-rspCory Benfieldbefore adoption2416e23
line 34why, one step back34Now, we have a :class:`Response <requests.Response>` object called ``r``. We canMerge pull request #2138 from dpursehouse/more-doc-updatesCory Benfieldbefore adoption587a515
line 35why, one step back35get all the information we need from this object.Merge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
lines 36–75why, one step back3637Requests' simple API means that all forms of HTTP request are as obvious. For38example, this is how you make an HTTP POST request::3940 >>> r = requests.post("http://httpbin.org/post")4142Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and43OPTIONS? These are all just as simple::4445 >>> r = requests.put("http://httpbin.org/put")46 >>> r = requests.delete("http://httpbin.org/delete")47 >>> r = requests.head("http://httpbin.org/get")48 >>> r = requests.options("http://httpbin.org/get")4950That's all well and good, but it's also only the start of what Requests can51do.525354Passing Parameters In URLs55--------------------------5657You often want to send some sort of data in the URL's query string. If58you were constructing the URL by hand, this data would be given as key/value59pairs in the URL after a question mark, e.g. ``httpbin.org/get?key=val``.60Requests allows you to provide these arguments as a dictionary, using the61``params`` keyword argument. As an example, if you wanted to pass62``key1=value1`` and ``key2=value2`` to ``httpbin.org/get``, you would use the63following code::6465 >>> payload = {'key1': 'value1', 'key2': 'value2'}66 >>> r = requests.get("http://httpbin.org/get", params=payload)6768You can see that the URL has been correctly encoded by printing the URL::6970 >>> print(r.url)71 http://httpbin.org/get?key2=value2&key1=value17273Note that any dictionary key whose value is ``None`` will not be added to the74URL's query string.75Merge pull request #2437 from tomscytale/docs_query_param_arrayCory Benfieldbefore adoptionc7beb70
lines 76–82why, one step back76In order to pass a list of items as a value you must mark the key as77referring to a list like string by appending ``[]`` to the key::7879 >>> payload = {'key1': 'value1', 'key2[]': ['value2', 'value3']}80 >>> r = requests.get("http://httpbin.org/get", params=payload)81 >>> print(r.url)82 http://httpbin.org/get?key1=value1&key2%5B%5D=value2&key2%5B%5D=value3Merge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
lines 83–90why, one step back8384Response Content85----------------8687We can read the content of the server's response. Consider the GitHub timeline88again::8990 >>> import requestsFixup the remaining references to timeline.json.Cory Benfieldbefore adoption466a70f
line 91why, one step back91 >>> r = requests.get('https://api.github.com/events')Merge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
lines 92–143why, one step back92 >>> r.text93 u'[{"repository":{"open_issues":0,"url":"https://github.com/...9495Requests will automatically decode content from the server. Most unicode96charsets are seamlessly decoded.9798When you make a request, Requests makes educated guesses about the encoding of99the response based on the HTTP headers. The text encoding guessed by Requests100is used when you access ``r.text``. You can find out what encoding Requests is101using, and change it, using the ``r.encoding`` property::102103 >>> r.encoding104 'utf-8'105 >>> r.encoding = 'ISO-8859-1'106107If you change the encoding, Requests will use the new value of ``r.encoding``108whenever you call ``r.text``. You might want to do this in any situation where109you can apply special logic to work out what the encoding of the content will110be. For example, HTTP and XML have the ability to specify their encoding in111their body. In situations like this, you should use ``r.content`` to find the112encoding, and then set ``r.encoding``. This will let you use ``r.text`` with113the correct encoding.114115Requests will also use custom encodings in the event that you need them. If116you have created your own encoding and registered it with the ``codecs``117module, you can simply use the codec name as the value of ``r.encoding`` and118Requests will handle the decoding for you.119120Binary Response Content121-----------------------122123You can also access the response body as bytes, for non-text requests::124125 >>> r.content126 b'[{"repository":{"open_issues":0,"url":"https://github.com/...127128The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.129130For example, to create an image from binary data returned by a request, you can131use the following code::132133 >>> from PIL import Image134 >>> from StringIO import StringIO135 >>> i = Image.open(StringIO(r.content))136137138JSON Response Content139---------------------140141There's also a builtin JSON decoder, in case you're dealing with JSON data::142143 >>> import requestsFixup the remaining references to timeline.json.Cory Benfieldbefore adoption466a70f
line 144why, one step back144 >>> r = requests.get('https://api.github.com/events')Merge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
lines 145–159why, one step back145 >>> r.json()146 [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...147148In case the JSON decoding fails, ``r.json`` raises an exception. For example, if149the response gets a 401 (Unauthorized), attempting ``r.json`` raises ``ValueError:150No JSON object could be decoded``151152153Raw Response Content154--------------------155156In the rare case that you'd like to get the raw socket response from the157server, you can access ``r.raw``. If you want to do this, make sure you set158``stream=True`` in your initial request. Once you do, you can do this::159Fixup the remaining references to timeline.json.Cory Benfieldbefore adoption466a70f
line 160why, one step back160 >>> r = requests.get('https://api.github.com/events', stream=True)Merge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
lines 161–188why, one step back161 >>> r.raw162 <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>163 >>> r.raw.read(10)164 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'165166In general, however, you should use a pattern like this to save what is being167streamed to a file::168169 with open(filename, 'wb') as fd:170 for chunk in r.iter_content(chunk_size):171 fd.write(chunk)172173Using ``Response.iter_content`` will handle a lot of what you would otherwise174have to handle when using ``Response.raw`` directly. When streaming a175download, the above is the preferred and recommended way to retrieve the176content.177178179Custom Headers180--------------181182If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the183``headers`` parameter.184185For example, we didn't specify our content-type in the previous example::186187 >>> import json188 >>> url = 'https://api.github.com/some/endpoint'Merge pull request #2493 from yasoob/masterCory Benfieldbefore adoptioncd3f7eb
line 189why, one step back189 >>> headers = {'user-agent': 'my-app/0.0.1'}Merge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
line 190why, one step back190Merge pull request #2493 from yasoob/masterCory Benfieldbefore adoptioncd3f7eb
line 191why, one step back191 >>> r = requests.get(url, headers=headers)Merge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
lines 192–202why, one step back192193194More complicated POST requests195------------------------------196197Typically, you want to send some form-encoded data — much like an HTML form.198To do this, simply pass a dictionary to the ``data`` argument. Your199dictionary of data will automatically be form-encoded when the request is made::200201 >>> payload = {'key1': 'value1', 'key2': 'value2'}202 >>> r = requests.post("http://httpbin.org/post", data=payload)Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a
line 203why, one step back203 >>> print(r.text)Merge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
lines 204–212why, one step back204 {205 ...206 "form": {207 "key2": "value2",208 "key1": "value1"209 },210 ...211 }212Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282
lines 213–214why, one step back213There are many times that you want to send data that is not form-encoded. If214you pass in a ``string`` instead of a ``dict``, that data will be posted directly.Merge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
lines 215–272why, one step back215216For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::217218 >>> import json219 >>> url = 'https://api.github.com/some/endpoint'220 >>> payload = {'some': 'data'}221222 >>> r = requests.post(url, data=json.dumps(payload))223224225POST a Multipart-Encoded File226-----------------------------227228Requests makes it simple to upload Multipart-encoded files::229230 >>> url = 'http://httpbin.org/post'231 >>> files = {'file': open('report.xls', 'rb')}232233 >>> r = requests.post(url, files=files)234 >>> r.text235 {236 ...237 "files": {238 "file": "<censored...binary...data>"239 },240 ...241 }242243You can set the filename, content_type and headers explicitly:244245 >>> url = 'http://httpbin.org/post'246 >>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}247248 >>> r = requests.post(url, files=files)249 >>> r.text250 {251 ...252 "files": {253 "file": "<censored...binary...data>"254 },255 ...256 }257258If you want, you can send strings to be received as files::259260 >>> url = 'http://httpbin.org/post'261 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}262263 >>> r = requests.post(url, files=files)264 >>> r.text265 {266 ...267 "files": {268 "file": "some,data,to,send\\nanother,row,to,send\\n"269 },270 ...271 }272Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a
lines 273–276why, one step back273In the event you are posting a very large file as a ``multipart/form-data``274request, you may want to stream the request. By default, ``requests`` does not275support this, but there is a separate package which does -276``requests-toolbelt``. You should read `the toolbelt's documentationMerge pull request #2440 from aquarion/patch-1Ian Cordascobefore adoption69d9594
line 277why, one step back277<https://toolbelt.readthedocs.org>`_ for more details about how to use it.Merge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
line 278why, one step back278Merge pull request #2227 from mjul/masterKenneth Reitzbefore adoption082c8d0
lines 279–281why, one step back279For sending multiple files in one request refer to the :ref:`advanced <advanced>`280section.281Merge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
lines 282–297why, one step back282283Response Status Codes284---------------------285286We can check the response status code::287288 >>> r = requests.get('http://httpbin.org/get')289 >>> r.status_code290 200291292Requests also comes with a built-in status code lookup object for easy293reference::294295 >>> r.status_code == requests.codes.ok296 True297Merge pull request #2138 from dpursehouse/more-doc-updatesCory Benfieldbefore adoption587a515
lines 298–300why, one step back298If we made a bad request (a 4XX client error or 5XX server error response), we299can raise it with300:meth:`Response.raise_for_status() <requests.Response.raise_for_status>`::Merge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
lines 301–337why, one step back301302 >>> bad_r = requests.get('http://httpbin.org/status/404')303 >>> bad_r.status_code304 404305306 >>> bad_r.raise_for_status()307 Traceback (most recent call last):308 File "requests/models.py", line 832, in raise_for_status309 raise http_error310 requests.exceptions.HTTPError: 404 Client Error311312But, since our ``status_code`` for ``r`` was ``200``, when we call313``raise_for_status()`` we get::314315 >>> r.raise_for_status()316 None317318All is well.319320321Response Headers322----------------323324We can view the server's response headers using a Python dictionary::325326 >>> r.headers327 {328 'content-encoding': 'gzip',329 'transfer-encoding': 'chunked',330 'connection': 'close',331 'server': 'nginx/1.0.4',332 'x-runtime': '148ms',333 'etag': '"e1ca502697e5c9317743dc078f67693f"',334 'content-type': 'application/json'335 }336337The dictionary is special, though: it's made just for HTTP headers. According toMerge pull request #2087 from Lukasa/2616Ian Cordascobefore adoption326f6ad
lines 338–339why, one step back338`RFC 7230 <http://tools.ietf.org/html/rfc7230#section-3.2>`_, HTTP Header names339are case-insensitive.Merge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
lines 340–348why, one step back340341So, we can access the headers using any capitalization we want::342343 >>> r.headers['Content-Type']344 'application/json'345346 >>> r.headers.get('content-type')347 'application/json'348Merge pull request #2453 from requiredfield/masterCory Benfieldbefore adoption6f3c91b
lines 349–357why, one step back349It is also special in that the server could have sent the same header multiple350times with different values, but requests combines them so they can be351represented in the dictionary within a single mapping, as per352`RFC 7230 <http://tools.ietf.org/html/rfc7230#section-3.2>`_:353354 > A recipient MAY combine multiple header fields with the same field name355 > into one "field-name: field-value" pair, without changing the semantics356 > of the message, by appending each subsequent field value to the combined357 > field value in order, separated by a comma.Merge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
lines 358–361why, one step back358359Cookies360-------361Merge pull request #2131 from dpursehouse/quickstart-doc-updatesCory Benfieldbefore adoption127ab0a
line 362why, one step back362If a response contains some Cookies, you can quickly access them::Merge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
lines 363–383why, one step back363364 >>> url = 'http://example.com/some/cookie/setting/url'365 >>> r = requests.get(url)366367 >>> r.cookies['example_cookie_name']368 'example_cookie_value'369370To send your own cookies to the server, you can use the ``cookies``371parameter::372373 >>> url = 'http://httpbin.org/cookies'374 >>> cookies = dict(cookies_are='working')375376 >>> r = requests.get(url, cookies=cookies)377 >>> r.text378 '{"cookies": {"cookies_are": "working"}}'379380381Redirection and History382-----------------------383Merge pull request #2131 from dpursehouse/quickstart-doc-updatesCory Benfieldbefore adoption127ab0a
line 384why, one step back384By default Requests will perform location redirection for all verbs exceptMerge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
lines 385–386why, one step back385HEAD.386Merge pull request #2131 from dpursehouse/quickstart-doc-updatesCory Benfieldbefore adoption127ab0a
line 387why, one step back387We can use the ``history`` property of the Response object to track redirection.Merge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
line 388why, one step back388Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
line 389why, one step back389The :meth:`Response.history <requests.Response.history>` list contains theMerge pull request #2245 from sigmavirus24/doc-fixCory Benfieldbefore adoptione0d88c2
line 390why, one step back390:class:`Response <requests.Response>` objects that were created in order toMerge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
line 391why, one step back391complete the request. The list is sorted from the oldest to the most recentMerge pull request #2245 from sigmavirus24/doc-fixCory Benfieldbefore adoptione0d88c2
line 392why, one step back392response.Merge pull request #2131 from dpursehouse/quickstart-doc-updatesCory Benfieldbefore adoption127ab0a
lines 393–395why, one step back393394For example, GitHub redirects all HTTP requests to HTTPS::395Merge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
lines 396–415why, one step back396 >>> r = requests.get('http://github.com')397 >>> r.url398 'https://github.com/'399 >>> r.status_code400 200401 >>> r.history402 [<Response [301]>]403404405If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable406redirection handling with the ``allow_redirects`` parameter::407408 >>> r = requests.get('http://github.com', allow_redirects=False)409 >>> r.status_code410 301411 >>> r.history412 []413414If you're using HEAD, you can enable redirection as well::415Merge pull request #2112 from np-csu/patch-1Ian Cordascobefore adoptionde2cd2e
line 416why, one step back416 >>> r = requests.head('http://github.com', allow_redirects=True)Merge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
lines 417–448why, one step back417 >>> r.url418 'https://github.com/'419 >>> r.history420 [<Response [301]>]421422423Timeouts424--------425426You can tell Requests to stop waiting for a response after a given number of427seconds with the ``timeout`` parameter::428429 >>> requests.get('http://github.com', timeout=0.001)430 Traceback (most recent call last):431 File "<stdin>", line 1, in <module>432 requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)433434435.. admonition:: Note436437 ``timeout`` is not a time limit on the entire response download;438 rather, an exception is raised if the server has not issued a439 response for ``timeout`` seconds (more precisely, if no bytes have been440 received on the underlying socket for ``timeout`` seconds).441442443Errors and Exceptions444---------------------445446In the event of a network problem (e.g. DNS failure, refused connection, etc),447Requests will raise a :class:`~requests.exceptions.ConnectionError` exception.448Merge pull request #2131 from dpursehouse/quickstart-doc-updatesCory Benfieldbefore adoption127ab0a
line 449why, one step back449In the rare event of an invalid HTTP response, Requests will raise anMerge pull request #1888 from longaccess/handle301Kenneth Reitzbefore adoptionb1c8fd3
lines 450–463why, one step back450:class:`~requests.exceptions.HTTPError` exception.451452If a request times out, a :class:`~requests.exceptions.Timeout` exception is453raised.454455If a request exceeds the configured number of maximum redirections, a456:class:`~requests.exceptions.TooManyRedirects` exception is raised.457458All exceptions that Requests explicitly raises inherit from459:class:`requests.exceptions.RequestException`.460461-----------------------462463Ready for more? Check out the :ref:`advanced <advanced>` section.