quickstart.rst
This file
Path
docs/user/quickstart.rst
369 lines · 10.2 KiB
Last changed by
Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoptionfad9abf
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 back44quickstart for encodingKenneth Reitzbefore adoptionab23536
lines 45–49why, one step back45When you make a request, ``r.encoding`` is set, based on the HTTP headers.46Requests will attempt to use that encoding when you access ``r.content``. You47can manually set ``r.encoding`` to any encoding you'd like (including ``None``),48and that charset will be used.49big quick start updatesKenneth Reitzbefore adoption60558fd
line 50why, one step back50Merge branch 'develop' of https://github.com/joequery/requests into developKenneth Reitzbefore adoption3d6937a
line 51why, one step back51Make a POST Requestbig quick start updatesKenneth Reitzbefore adoption60558fd
line 52why, one step back52-------------------Merge branch 'develop' of https://github.com/joequery/requests into developKenneth Reitzbefore adoption3d6937a
line 53why, one step back53big quick start updatesKenneth Reitzbefore adoption60558fd
line 54why, one step back54POST requests are equally simple::Merge branch 'develop' of https://github.com/joequery/requests into developKenneth Reitzbefore adoption3d6937a
line 55why, one step back55big quick start updatesKenneth Reitzbefore adoption60558fd
line 56why, one step back56 r = requests.post("http://httpbin.org/post")Merge branch 'develop' of https://github.com/joequery/requests into developKenneth Reitzbefore adoption3d6937a
lines 57–58why, one step back5758big quick start updatesKenneth Reitzbefore adoption60558fd
line 59why, one step back59Typically, you want to send some form-encoded data — much like an HTML form.sp Kenneth Reitzbefore adoption3d49eb4
lines 60–61why, one step back60To do this, simply pass a dictionary to the `data` argument. Your61dictionary of data will automatically be form-encoded when the request is made::big quick start updatesKenneth Reitzbefore adoption60558fd
lines 62–118why, one step back6263 >>> payload = {'key1': 'value1', 'key2': 'value2'}64 >>> r = requests.post("http://httpbin.org/post", data=payload)65 >>> print r.content66 {67 "origin": "179.13.100.4",68 "files": {},69 "form": {70 "key2": "value2",71 "key1": "value1"72 },73 "url": "http://httpbin.org/post",74 "args": {},75 "headers": {76 "Content-Length": "23",77 "Accept-Encoding": "identity, deflate, compress, gzip",78 "Accept": "*/*",79 "User-Agent": "python-requests/0.8.0",80 "Host": "127.0.0.1:7077",81 "Content-Type": "application/x-www-form-urlencoded"82 },83 "data": ""84 }8586There 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.8788For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::8990 url = 'https://api.github.com/some/endpoint'91 payload = {'some': 'data'}9293 r = requests.post(url, data=json.dumps(payload))949596Custom Headers97--------------9899If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the100``headers`` parameter.101102For example, we didn't specify our content-type in the previous example::103104 url = 'https://api.github.com/some/endpoint'105 payload = {'some': 'data'}106 headers = {'content-type': 'application/json'}107108 r = requests.post(url, data=json.dumps(payload), headers=headers)109110111POST a Multipart-Encoded File112-----------------------------113114Requests makes it simple to upload Multipart-encoded files::115116 >>> url = 'http://httpbin.org/post'117 >>> files = {'report.xls': open('report.xls', 'rb')}118file uploadsKenneth Reitzbefore adoption40c5480
line 119why, one step back119 >>> r = requests.post(url, files=files)Merge branch 'develop' of https://github.com/joequery/requests into developKenneth Reitzbefore adoption3d6937a
line 120why, one step back120 >>> r.contentfile uploadsKenneth Reitzbefore adoption40c5480
lines 121–123why, one step back121 {122 "origin": "179.13.100.4",123 "files": {sp Kenneth Reitzbefore adoption3d49eb4
line 124why, one step back124 "report.xls": "<censored...binary...data>"file uploadsKenneth Reitzbefore adoption40c5480
lines 125–138why, one step back125 },126 "form": {},127 "url": "http://httpbin.org/post",128 "args": {},129 "headers": {130 "Content-Length": "3196",131 "Accept-Encoding": "identity, deflate, compress, gzip",132 "Accept": "*/*",133 "User-Agent": "python-requests/0.8.0",134 "Host": "httpbin.org:80",135 "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"136 },137 "data": ""138 }Merge branch 'develop' of https://github.com/joequery/requests into developKenneth Reitzbefore adoption3d6937a
line 139why, one step back139Merge pull request #280 from darkrho/58e018af136190a2c757b13bf9371cecc2d51273Kenneth Reitzbefore adoption2a72235
lines 140–164why, one step back140Setting filename explicitly::141142 >>> url = 'http://httpbin.org/post'143 >>> files = {'file': ('report.xls', open('report.xls', 'rb'))}144145 >>> r = requests.post(url, files=files)146 >>> r.content147 {148 "origin": "179.13.100.4",149 "files": {150 "file": "<censored...binary...data>"151 },152 "form": {},153 "url": "http://httpbin.org/post",154 "args": {},155 "headers": {156 "Content-Length": "3196",157 "Accept-Encoding": "identity, deflate, compress, gzip",158 "Accept": "*/*",159 "User-Agent": "python-requests/0.8.0",160 "Host": "httpbin.org:80",161 "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"162 },163 "data": ""164 }big quick start updatesKenneth Reitzbefore adoption60558fd
lines 165–166why, one step back165166Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 167–168why, one step back167Response Status Codes168---------------------Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 169why, one step back169Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 170why, one step back170We can check the response status code::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 171why, one step back171Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 172–173why, one step back172 >>> r.status_code173 200Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 174why, one step back174Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 175–176why, one step back175Requests also comes with a built-in status code lookup object for easy176reference::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 177why, one step back177Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 178–179why, one step back178 >>> r.status_code == requests.codes.ok179 TrueMerge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 180why, one step back180big quick start updatesKenneth Reitzbefore adoption60558fd
line 181why, one step back181If we made a bad request (non-200 response), we can raise it withMerge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 182why, one step back182:class:`Response.raise_for_status()`::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 183why, one step back183Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 184–186why, one step back184 >>> _r = requests.get('http://httpbin.org/status/404')185 >>> _r.status_code186 404Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 187why, one step back187Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 188–192why, one step back188 >>> _r.raise_for_status()189 Traceback (most recent call last):190 File "requests/models.py", line 394, in raise_for_status191 raise self.error192 urllib2.HTTPError: HTTP Error 404: NOT FOUNDMerge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 193why, one step back193Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 194why, one step back194But, since our ``status_code`` was ``200``, when we call it::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 195why, one step back195Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 196–197why, one step back196 >>> r.raise_for_status()197 NoneMerge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 198why, one step back198Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 199why, one step back199All is well.Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
lines 200–201why, one step back200201Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 202–203why, one step back202Response Headers203----------------Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 204why, one step back204Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 205–206why, one step back205We can view the server's response headers with a simple Python dictionary206interface::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 207why, one step back207Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 208–218why, one step back208 >>> r.headers209 {210 'status': '200 OK',211 'content-encoding': 'gzip',212 'transfer-encoding': 'chunked',213 'connection': 'close',214 'server': 'nginx/1.0.4',215 'x-runtime': '148ms',216 'etag': '"e1ca502697e5c9317743dc078f67693f"',217 'content-type': 'application/json; charset=utf-8'218 }Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 219why, one step back219Migrate new docs over.Kenneth Reitzbefore adoption4a7fdef
lines 220–221why, one step back220The dictionary is special, though: it's made just for HTTP headers. According to221`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTPMerge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 222why, one step back222Headers are case-insensitive.Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 223why, one step back223Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 224why, one step back224So, we can access the headers using any capitalization we want::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 225why, one step back225Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 226–257why, one step back226 >>> r.headers['Content-Type']227 'application/json; charset=utf-8'228229 >>> r.headers.get('content-type')230 'application/json; charset=utf-8'231232If a header doesn't exist in the Response, its value defaults to ``None``::233234 >>> r.headers['X-Random']235 None236237238Cookies239-------240241If a response contains some Cookies, you can get quick access to them::242243 >>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'244 >>> r = requests.get(url)245246 >>> print r.cookies247 {'requests-is': 'awesome'}248249To send your own cookies to the server, you can use the ``cookies``250parameter::251252 >>> url = 'http://httpbin.org/cookies'253 >>> cookies = dict(cookies_are='working')254255 >>> r = requests.get(url, cookies=cookies)256 >>> r.content257 '{"cookies": {"cookies_are": "working"}}'Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 258–263why, one step back258259260Basic Authentication261--------------------262263Most web services require authentication. There many different types ofquicker startKenneth Reitzbefore adoption58c77ba
line 264why, one step back264authentication, but the most common is HTTP Basic Auth.Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
line 265why, one step back265big quick start updatesKenneth Reitzbefore adoption60558fd
line 266why, one step back266Making requests with Basic Auth is extremely simple::Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
line 267why, one step back267Merge branch 'auth_callables' of https://github.com/idangazit/requests into developKenneth Reitzbefore adoptiona7a619b
lines 268–274why, one step back268 >>> from requests.auth import HTTPBasicAuth269 >>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))270 <Response [200]>271272Due to the prevalence of HTTP Basic Auth, requests provides a shorthand for273this authentication method::274Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 275–277why, one step back275 >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))276 <Response [200]>277Merge branch 'auth_callables' of https://github.com/idangazit/requests into developKenneth Reitzbefore adoptiona7a619b
lines 278–279why, one step back278Providing the credentials as a tuple in this fashion is functionally equivalent279to the ``HTTPBasicAuth`` example above.Merge pull request #260 from joequery/doc_changesKenneth Reitzbefore adoptionfc0565f
line 280why, one step back280Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 281–284why, one step back281282Digest Authentication283---------------------284quicker startKenneth Reitzbefore adoption58c77ba
line 285why, one step back285Another popular form of web service protection is Digest Authentication::Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
line 286why, one step back286Merge branch 'auth_callables' of https://github.com/idangazit/requests into developKenneth Reitzbefore adoptiona7a619b
line 287why, one step back287 >>> from requests.auth import HTTPDigestAuthMerge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
line 288why, one step back288 >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'Merge branch 'auth_callables' of https://github.com/idangazit/requests into developKenneth Reitzbefore adoptiona7a619b
line 289why, one step back289 >>> requests.get(url, auth=HTTPDigestAuth('user', 'pass'))Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
line 290why, one step back290 <Response [200]>Merge branch 'auth_callables' of https://github.com/idangazit/requests into developKenneth Reitzbefore adoptiona7a619b
lines 291–297why, one step back291292293OAuth Authentication294--------------------295296Miguel Araujo's `requests-oauth <http://pypi.python.org/pypi/requests-oauth>`_ project provides a simple interface for297establishing 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 298–299why, one step back298299redirection docsKenneth Reitzbefore adoption30377ca
lines 300–302why, one step back300Redirection and History301-----------------------302Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoptionfad9abf
line 303why, one step back303Requests will automatically perform location redirection while using idempotent methods.redirection docsKenneth Reitzbefore adoption30377ca
lines 304–306why, one step back304305GitHub redirects all HTTP requests to HTTPS. Let's see what happens::306sp Kenneth Reitzbefore adoption3d49eb4
line 307why, one step back307 >>> r = requests.get('http://github.com')redirection docsKenneth Reitzbefore adoption30377ca
lines 308–318why, one step back308 >>> r.url309 'https://github.com/'310 >>> r.status_code311 200312 >>> r.history313 [<Response [301]>]314315The :class:`Response.history` list contains a list of the316:class:`Request` objects that were created in order to complete the request.317318If you're using GET, HEAD, or OPTIONS, you can disable redirectionMerge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoption961f78a
line 319why, one step back319handling with the ``allow_redirects`` parameter::redirection docsKenneth Reitzbefore adoption30377ca
line 320why, one step back320Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoption961f78a
line 321why, one step back321 >>> r = requests.get('http://github.com', allow_redirects=False)redirection docsKenneth Reitzbefore adoption30377ca
lines 322–328why, one step back322 >>> r.status_code323 301324 >>> r.history325 []326327If you're using POST, PUT, PATCH, *&c*, you can also explicitly enable redirection as well::328missing param in quick startKenneth Reitzbefore adoption45c9ecc
line 329why, one step back329 >>> r = requests.post('http://github.com', allow_redirects=True)redirection docsKenneth Reitzbefore adoption30377ca
lines 330–335why, one step back330 >>> r.url331 'https://github.com/'332 >>> r.history333 [<Response [301]>]334335document timeoutsKenneth Reitzbefore adoption4ab7694
lines 336–347why, one step back336Timeouts337--------338339You can tell requests to stop waiting for a response after a given number of seconds with the ``timeout`` parameter::340341 >>> requests.get('http://github.com', timeout=0.001)342 Traceback (most recent call last):343 File "<stdin>", line 1, in <module>344 requests.exceptions.Timeout: Request timed out.345346.. admonition:: Note347sp Kenneth Reitzbefore adoptionf7e4832
line 348why, one step back348 ``timeout`` only effects the connection process itself, not the downloading of the response body.document timeoutsKenneth Reitzbefore adoption4ab7694
lines 349–365why, one step back349350351Errors and Exceptions352---------------------353354In the event of a network problem (e.g. DNS failure, refused connection, etc),355Requests will raise a :class:`ConnectionError` exception.356357In the event of the rare invalid HTTP response, Requests will raise358an :class:`HTTPError` exception.359360If a request times out, a :class:`Timeout` exception is raised.361362If a request exceeds the configured number of maximum redirections, a :class:`TooManyRedirects` exception is raised.363364All exceptions that Requests explicitly raises inherit from365:class:`requests.exceptions.RequestException`.redirection docsKenneth Reitzbefore adoption30377ca
line 366why, one step back366Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 367–368why, one step back367-----------------------368Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoptionc48f0d9
line 369why, one step back369Ready for more? Check out the :ref:`advanced <advanced>` section.