quickstart.rst
This file
Path
docs/user/quickstart.rst
351 lines · 9.5 KiB
Last changed by
Merge pull request #280 from darkrho/58e018af136190a2c757b13bf9371cecc2d51273Kenneth Reitzbefore adoption2a72235
History of this fileTake it
Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 1why, one step back1.. _quickstart:Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 2why, one step back2Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 3–4why, one step back3Quickstart4==========Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 5why, one step back5Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 6why, one step back6.. module:: requests.modelsMerge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 7why, one step back7Migrate new docs over.Kenneth Reitzbefore adoption4a7fdef
lines 8–10why, one step back8Eager 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.Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 11why, one step back11Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 12why, one step back12First, make sure that:Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 13why, one step back13Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 14–15why, one step back14* Requests is :ref:`installed <install>`15* Requests is :ref:`up-to-date <updates>`Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
lines 16–17why, one step back1617Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 18why, one step back18Lets gets started with some simple use cases and examples.Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
lines 19–20why, one step back1920Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 21–22why, one step back21Make a GET Request22------------------Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 23why, one step back23Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 24why, one step back24Making a standard request with Requests is very simple.Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 25why, one step back25Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 26why, one step back26Let's get GitHub's public timeline ::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 27why, one step back27Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 28why, one step back28 r = requests.get('https://github.com/timeline.json')Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 29why, one step back29Migrate new docs over.Kenneth Reitzbefore adoption4a7fdef
lines 30–31why, one step back30Now, we have a :class:`Response` object called ``r``. We can get all the31information we need from this.Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
lines 32–33why, one step back3233Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 34–35why, one step back34Response Content35----------------Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 36why, one step back36Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 37why, one step back37We can read the content of the server's response::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 38why, one step back38Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 39–40why, one step back39 >>> r.content40 '[{"repository":{"open_issues":0,"url":"https://github.com/...Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 41why, one step back41sp Kenneth Reitzbefore adoption3d49eb4
lines 42–43why, one step back42Requests does its best to decode content from the server. Most unicode43charsets, ``gzip``, and ``deflate`` encodings are all seamlessly decoded.Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 44why, one step back44big quick start updatesKenneth Reitzbefore adoption60558fd
line 45why, one step back45Merge branch 'develop' of https://github.com/joequery/requests into developKenneth Reitzbefore adoption3d6937a
line 46why, one step back46Make a POST Requestbig quick start updatesKenneth Reitzbefore adoption60558fd
line 47why, one step back47-------------------Merge branch 'develop' of https://github.com/joequery/requests into developKenneth Reitzbefore adoption3d6937a
line 48why, one step back48big quick start updatesKenneth Reitzbefore adoption60558fd
line 49why, one step back49POST requests are equally simple::Merge branch 'develop' of https://github.com/joequery/requests into developKenneth Reitzbefore adoption3d6937a
line 50why, one step back50big quick start updatesKenneth Reitzbefore adoption60558fd
line 51why, one step back51 r = requests.post("http://httpbin.org/post")Merge branch 'develop' of https://github.com/joequery/requests into developKenneth Reitzbefore adoption3d6937a
lines 52–53why, one step back5253big quick start updatesKenneth Reitzbefore adoption60558fd
line 54why, one step back54Typically, you want to send some form-encoded data — much like an HTML form.sp Kenneth Reitzbefore adoption3d49eb4
lines 55–56why, one step back55To do this, simply pass a dictionary to the `data` argument. Your56dictionary of data will automatically be form-encoded when the request is made::big quick start updatesKenneth Reitzbefore adoption60558fd
lines 57–113why, one step back5758 >>> payload = {'key1': 'value1', 'key2': 'value2'}59 >>> r = requests.post("http://httpbin.org/post", data=payload)60 >>> print r.content61 {62 "origin": "179.13.100.4",63 "files": {},64 "form": {65 "key2": "value2",66 "key1": "value1"67 },68 "url": "http://httpbin.org/post",69 "args": {},70 "headers": {71 "Content-Length": "23",72 "Accept-Encoding": "identity, deflate, compress, gzip",73 "Accept": "*/*",74 "User-Agent": "python-requests/0.8.0",75 "Host": "127.0.0.1:7077",76 "Content-Type": "application/x-www-form-urlencoded"77 },78 "data": ""79 }8081There 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.8283For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::8485 url = 'https://api.github.com/some/endpoint'86 payload = {'some': 'data'}8788 r = requests.post(url, data=json.dumps(payload))899091Custom Headers92--------------9394If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the95``headers`` parameter.9697For example, we didn't specify our content-type in the previous example::9899 url = 'https://api.github.com/some/endpoint'100 payload = {'some': 'data'}101 headers = {'content-type': 'application/json'}102103 r = requests.post(url, data=json.dumps(payload), headers=headers)104105106POST a Multipart-Encoded File107-----------------------------108109Requests makes it simple to upload Multipart-encoded files::110111 >>> url = 'http://httpbin.org/post'112 >>> files = {'report.xls': open('report.xls', 'rb')}113file uploadsKenneth Reitzbefore adoption40c5480
line 114why, one step back114 >>> r = requests.post(url, files=files)Merge branch 'develop' of https://github.com/joequery/requests into developKenneth Reitzbefore adoption3d6937a
line 115why, one step back115 >>> r.contentfile uploadsKenneth Reitzbefore adoption40c5480
lines 116–118why, one step back116 {117 "origin": "179.13.100.4",118 "files": {sp Kenneth Reitzbefore adoption3d49eb4
line 119why, one step back119 "report.xls": "<censored...binary...data>"file uploadsKenneth Reitzbefore adoption40c5480
lines 120–133why, one step back120 },121 "form": {},122 "url": "http://httpbin.org/post",123 "args": {},124 "headers": {125 "Content-Length": "3196",126 "Accept-Encoding": "identity, deflate, compress, gzip",127 "Accept": "*/*",128 "User-Agent": "python-requests/0.8.0",129 "Host": "httpbin.org:80",130 "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"131 },132 "data": ""133 }Merge branch 'develop' of https://github.com/joequery/requests into developKenneth Reitzbefore adoption3d6937a
line 134why, one step back134Merge pull request #280 from darkrho/58e018af136190a2c757b13bf9371cecc2d51273Kenneth Reitzbefore adoption2a72235
lines 135–159why, one step back135Setting filename explicitly::136137 >>> url = 'http://httpbin.org/post'138 >>> files = {'file': ('report.xls', open('report.xls', 'rb'))}139140 >>> r = requests.post(url, files=files)141 >>> r.content142 {143 "origin": "179.13.100.4",144 "files": {145 "file": "<censored...binary...data>"146 },147 "form": {},148 "url": "http://httpbin.org/post",149 "args": {},150 "headers": {151 "Content-Length": "3196",152 "Accept-Encoding": "identity, deflate, compress, gzip",153 "Accept": "*/*",154 "User-Agent": "python-requests/0.8.0",155 "Host": "httpbin.org:80",156 "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"157 },158 "data": ""159 }big quick start updatesKenneth Reitzbefore adoption60558fd
lines 160–161why, one step back160161Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 162–163why, one step back162Response Status Codes163---------------------Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 164why, one step back164Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 165why, one step back165We can check the response status code::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 166why, one step back166Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 167–168why, one step back167 >>> r.status_code168 200Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 169why, one step back169Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 170–171why, one step back170Requests also comes with a built-in status code lookup object for easy171reference::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 172why, one step back172Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 173–174why, one step back173 >>> r.status_code == requests.codes.ok174 TrueMerge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 175why, one step back175big quick start updatesKenneth Reitzbefore adoption60558fd
line 176why, one step back176If we made a bad request (non-200 response), we can raise it withMerge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 177why, one step back177:class:`Response.raise_for_status()`::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 178why, one step back178Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 179–181why, one step back179 >>> _r = requests.get('http://httpbin.org/status/404')180 >>> _r.status_code181 404Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 182why, one step back182Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 183–187why, one step back183 >>> _r.raise_for_status()184 Traceback (most recent call last):185 File "requests/models.py", line 394, in raise_for_status186 raise self.error187 urllib2.HTTPError: HTTP Error 404: NOT FOUNDMerge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 188why, one step back188Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 189why, one step back189But, since our ``status_code`` was ``200``, when we call it::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 190why, one step back190Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 191–192why, one step back191 >>> r.raise_for_status()192 NoneMerge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 193why, one step back193Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 194why, one step back194All is well.Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
lines 195–196why, one step back195196Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 197–198why, one step back197Response Headers198----------------Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 199why, one step back199Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 200–201why, one step back200We can view the server's response headers with a simple Python dictionary201interface::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 202why, one step back202Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 203–213why, one step back203 >>> r.headers204 {205 'status': '200 OK',206 'content-encoding': 'gzip',207 'transfer-encoding': 'chunked',208 'connection': 'close',209 'server': 'nginx/1.0.4',210 'x-runtime': '148ms',211 'etag': '"e1ca502697e5c9317743dc078f67693f"',212 'content-type': 'application/json; charset=utf-8'213 }Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 214why, one step back214Migrate new docs over.Kenneth Reitzbefore adoption4a7fdef
lines 215–216why, one step back215The dictionary is special, though: it's made just for HTTP headers. According to216`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTPMerge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 217why, one step back217Headers are case-insensitive.Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 218why, one step back218Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 219why, one step back219So, we can access the headers using any capitalization we want::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 220why, one step back220Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 221–252why, one step back221 >>> r.headers['Content-Type']222 'application/json; charset=utf-8'223224 >>> r.headers.get('content-type')225 'application/json; charset=utf-8'226227If a header doesn't exist in the Response, its value defaults to ``None``::228229 >>> r.headers['X-Random']230 None231232233Cookies234-------235236If a response contains some Cookies, you can get quick access to them::237238 >>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'239 >>> r = requests.get(url)240241 >>> print r.cookies242 {'requests-is': 'awesome'}243244To send your own cookies to the server, you can use the ``cookies``245parameter::246247 >>> url = 'http://httpbin.org/cookies'248 >>> cookies = dict(cookies_are='working')249250 >>> r = requests.get(url, cookies=cookies)251 >>> r.content252 '{"cookies": {"cookies_are": "working"}}'Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 253–258why, one step back253254255Basic Authentication256--------------------257258Most web services require authentication. There many different types ofquicker startKenneth Reitzbefore adoption58c77ba
line 259why, one step back259authentication, but the most common is HTTP Basic Auth.Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
line 260why, one step back260big quick start updatesKenneth Reitzbefore adoption60558fd
line 261why, one step back261Making requests with Basic Auth is extremely simple::Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 262–265why, one step back262263 >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))264 <Response [200]>265Merge pull request #260 from joequery/doc_changesKenneth Reitzbefore adoptionfc0565f
lines 266–270why, one step back266OAuth Authentication267--------------------268269Miguel Araujo's `requests-oauth <http://pypi.python.org/pypi/requests-oauth>`_ project provides a simple interface for270establishing OAuth connections. Documentation and examples can be found on the requests-oauth `git repository <https://github.com/maraujop/requests-oauth>`_.Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 271–274why, one step back271272Digest Authentication273---------------------274quicker startKenneth Reitzbefore adoption58c77ba
line 275why, one step back275Another popular form of web service protection is Digest Authentication::Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 276–281why, one step back276277 >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'278 >>> requests.get(url, auth=('digest', 'user', 'pass'))279 <Response [200]>280281redirection docsKenneth Reitzbefore adoption30377ca
lines 282–288why, one step back282Redirection and History283-----------------------284285Requests will automatically perform location redirection while using impodotent methods.286287GitHub redirects all HTTP requests to HTTPS. Let's see what happens::288sp Kenneth Reitzbefore adoption3d49eb4
line 289why, one step back289 >>> r = requests.get('http://github.com')redirection docsKenneth Reitzbefore adoption30377ca
lines 290–302why, one step back290 >>> r.url291 'https://github.com/'292 >>> r.status_code293 200294 >>> r.history295 [<Response [301]>]296297The :class:`Response.history` list contains a list of the298:class:`Request` objects that were created in order to complete the request.299300If you're using GET, HEAD, or OPTIONS, you can disable redirection301handling with the ``disable_redirects`` parameter::302sp Kenneth Reitzbefore adoption3d49eb4
line 303why, one step back303 >>> r = requests.get('http://github.com')redirection docsKenneth Reitzbefore adoption30377ca
lines 304–310why, one step back304 >>> r.status_code305 301306 >>> r.history307 []308309If you're using POST, PUT, PATCH, *&c*, you can also explicitly enable redirection as well::310missing param in quick startKenneth Reitzbefore adoption45c9ecc
line 311why, one step back311 >>> r = requests.post('http://github.com', allow_redirects=True)redirection docsKenneth Reitzbefore adoption30377ca
lines 312–317why, one step back312 >>> r.url313 'https://github.com/'314 >>> r.history315 [<Response [301]>]316317document timeoutsKenneth Reitzbefore adoption4ab7694
lines 318–347why, one step back318Timeouts319--------320321You can tell requests to stop waiting for a response after a given number of seconds with the ``timeout`` parameter::322323 >>> requests.get('http://github.com', timeout=0.001)324 Traceback (most recent call last):325 File "<stdin>", line 1, in <module>326 requests.exceptions.Timeout: Request timed out.327328.. admonition:: Note329330 ``timeout`` only effects the connection process itself, not the downloading of the respone body.331332333Errors and Exceptions334---------------------335336In the event of a network problem (e.g. DNS failure, refused connection, etc),337Requests will raise a :class:`ConnectionError` exception.338339In the event of the rare invalid HTTP response, Requests will raise340an :class:`HTTPError` exception.341342If a request times out, a :class:`Timeout` exception is raised.343344If a request exceeds the configured number of maximum redirections, a :class:`TooManyRedirects` exception is raised.345346All exceptions that Requests explicitly raises inherit from347:class:`requests.exceptions.RequestException`.redirection docsKenneth Reitzbefore adoption30377ca
line 348why, one step back348Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 349–350why, one step back349-----------------------350Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoptionc48f0d9
line 351why, one step back351Ready for more? Check out the :ref:`advanced <advanced>` section.