quickstart.rst
This file
Path
docs/user/quickstart.rst
399 lines · 11.1 KiB
Last changed by
r.textKenneth Reitzbefore adoption1bc377b
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 back7Merge branch 'release/0.6.3'Kenneth Reitzbefore adoption1551158
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 back29Merge branch 'release/0.6.3'Kenneth Reitzbefore adoption1551158
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 back38explain binary response dataKenneth Reitzbefore adoptiona89530a
line 39why, one step back39 >>> r.textMerge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 40why, one step back40 '[{"repository":{"open_issues":0,"url":"https://github.com/...Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 41why, one step back41explain binary response dataKenneth Reitzbefore adoptiona89530a
lines 42–43why, one step back42Requests will automatically decode content from the server. Most unicode43charsets are seamlessly decoded.Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 44why, one step back44Merge branch 'develop'Kenneth Reitzbefore adoption42b33ae
line 45why, one step back45When you make a request, ``r.encoding`` is set, based on the HTTP headers.explain binary response dataKenneth Reitzbefore adoptiona89530a
lines 46–74why, one step back46Requests will use that encoding when you access ``r.text``. If ``r.encoding``47is ``None``, Requests will make an extremely educated guess of the encoding48of the response body. You can manually set ``r.encoding`` to any encoding49you'd like, and that charset will be used.505152Binary Response Content53-----------------------5455You can also access the response body as bytes, for non-text requests::5657 >>> r.content58 b'[{"repository":{"open_issues":0,"url":"https://github.com/...5960The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.616263Raw Response Content64--------------------6566In the rare case that you'd like to get the absolute raw socket response from the server,67you can access ``r.raw``::6869 >>> r.raw70 <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>7172 >>> r.raw.read(10)73 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'74Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
line 75why, one step back75Merge branch 'develop'Kenneth Reitzbefore adoption42b33ae
line 76why, one step back76Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
lines 77–85why, one step back77Make a POST Request78-------------------7980POST requests are equally simple::8182 r = requests.post("http://httpbin.org/post")838485Typically, you want to send some form-encoded data — much like an HTML form.Merge branch 'develop'Kenneth Reitzbefore adoption1165bec
lines 86–87why, one step back86To do this, simply pass a dictionary to the `data` argument. Your87dictionary of data will automatically be form-encoded when the request is made::Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
lines 88–90why, one step back8889 >>> payload = {'key1': 'value1', 'key2': 'value2'}90 >>> r = requests.post("http://httpbin.org/post", data=payload)r.textKenneth Reitzbefore adoption1bc377b
line 91why, one step back91 >>> print r.textMerge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
lines 92–145why, one step back92 {93 "origin": "179.13.100.4",94 "files": {},95 "form": {96 "key2": "value2",97 "key1": "value1"98 },99 "url": "http://httpbin.org/post",100 "args": {},101 "headers": {102 "Content-Length": "23",103 "Accept-Encoding": "identity, deflate, compress, gzip",104 "Accept": "*/*",105 "User-Agent": "python-requests/0.8.0",106 "Host": "127.0.0.1:7077",107 "Content-Type": "application/x-www-form-urlencoded"108 },109 "data": ""110 }111112There 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.113114For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::115116 url = 'https://api.github.com/some/endpoint'117 payload = {'some': 'data'}118119 r = requests.post(url, data=json.dumps(payload))120121122Custom Headers123--------------124125If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the126``headers`` parameter.127128For example, we didn't specify our content-type in the previous example::129130 url = 'https://api.github.com/some/endpoint'131 payload = {'some': 'data'}132 headers = {'content-type': 'application/json'}133134 r = requests.post(url, data=json.dumps(payload), headers=headers)135136137POST a Multipart-Encoded File138-----------------------------139140Requests makes it simple to upload Multipart-encoded files::141142 >>> url = 'http://httpbin.org/post'143 >>> files = {'report.xls': open('report.xls', 'rb')}144145 >>> r = requests.post(url, files=files)r.textKenneth Reitzbefore adoption1bc377b
line 146why, one step back146 >>> r.textMerge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
lines 147–149why, one step back147 {148 "origin": "179.13.100.4",149 "files": {Merge branch 'develop'Kenneth Reitzbefore adoption1165bec
line 150why, one step back150 "report.xls": "<censored...binary...data>"Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
lines 151–165why, one step back151 },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 }165Merge branch 'develop'Kenneth Reitzbefore adoption42b33ae
lines 166–171why, one step back166Setting filename explicitly::167168 >>> url = 'http://httpbin.org/post'169 >>> files = {'file': ('report.xls', open('report.xls', 'rb'))}170171 >>> r = requests.post(url, files=files)r.textKenneth Reitzbefore adoption1bc377b
line 172why, one step back172 >>> r.textMerge branch 'develop'Kenneth Reitzbefore adoption42b33ae
lines 173–190why, one step back173 {174 "origin": "179.13.100.4",175 "files": {176 "file": "<censored...binary...data>"177 },178 "form": {},179 "url": "http://httpbin.org/post",180 "args": {},181 "headers": {182 "Content-Length": "3196",183 "Accept-Encoding": "identity, deflate, compress, gzip",184 "Accept": "*/*",185 "User-Agent": "python-requests/0.8.0",186 "Host": "httpbin.org:80",187 "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"188 },189 "data": ""190 }Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
lines 191–192why, one step back191192Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 193–194why, one step back193Response Status Codes194---------------------Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 195why, one step back195Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 196why, one step back196We can check the response status code::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 197why, one step back197Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 198–199why, one step back198 >>> r.status_code199 200Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 200why, one step back200Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 201–202why, one step back201Requests also comes with a built-in status code lookup object for easy202reference::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 203why, one step back203Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 204–205why, one step back204 >>> r.status_code == requests.codes.ok205 TrueMerge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 206why, one step back206Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
line 207why, one step back207If we made a bad request (non-200 response), we can raise it withMerge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 208why, one step back208:class:`Response.raise_for_status()`::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 209why, one step back209Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 210–212why, one step back210 >>> _r = requests.get('http://httpbin.org/status/404')211 >>> _r.status_code212 404Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 213why, one step back213Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 214–218why, one step back214 >>> _r.raise_for_status()215 Traceback (most recent call last):216 File "requests/models.py", line 394, in raise_for_status217 raise self.error218 urllib2.HTTPError: HTTP Error 404: NOT FOUNDMerge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 219why, one step back219Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 220why, one step back220But, since our ``status_code`` was ``200``, when we call it::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 221why, one step back221Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 222–223why, one step back222 >>> r.raise_for_status()223 NoneMerge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 224why, one step back224Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 225why, one step back225All is well.Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
lines 226–227why, one step back226227Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 228–229why, one step back228Response Headers229----------------Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 230why, one step back230Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 231–232why, one step back231We can view the server's response headers with a simple Python dictionary232interface::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 233why, one step back233Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 234–244why, one step back234 >>> r.headers235 {236 'status': '200 OK',237 'content-encoding': 'gzip',238 'transfer-encoding': 'chunked',239 'connection': 'close',240 'server': 'nginx/1.0.4',241 'x-runtime': '148ms',242 'etag': '"e1ca502697e5c9317743dc078f67693f"',243 'content-type': 'application/json; charset=utf-8'244 }Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 245why, one step back245Merge branch 'release/0.6.3'Kenneth Reitzbefore adoption1551158
lines 246–247why, one step back246The dictionary is special, though: it's made just for HTTP headers. According to247`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html>`_, HTTPMerge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 248why, one step back248Headers are case-insensitive.Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 249why, one step back249Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 250why, one step back250So, we can access the headers using any capitalization we want::Merge branch 'release/0.4.1'Kenneth Reitzbefore adoptionadd6fea
line 251why, one step back251Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 252–281why, one step back252 >>> r.headers['Content-Type']253 'application/json; charset=utf-8'254255 >>> r.headers.get('content-type')256 'application/json; charset=utf-8'257258If a header doesn't exist in the Response, its value defaults to ``None``::259260 >>> r.headers['X-Random']261 None262263264Cookies265-------266267If a response contains some Cookies, you can get quick access to them::268269 >>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'270 >>> r = requests.get(url)271272 >>> print r.cookies273 {'requests-is': 'awesome'}274275To send your own cookies to the server, you can use the ``cookies``276parameter::277278 >>> url = 'http://httpbin.org/cookies'279 >>> cookies = dict(cookies_are='working')280281 >>> r = requests.get(url, cookies=cookies)r.textKenneth Reitzbefore adoption1bc377b
line 282why, one step back282 >>> r.textMerge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 283why, one step back283 '{"cookies": {"cookies_are": "working"}}'Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
lines 284–289why, one step back284285286Basic Authentication287--------------------288289Most web services require authentication. There many different types ofMerge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
line 290why, one step back290authentication, but the most common is HTTP Basic Auth.Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
line 291why, one step back291Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
line 292why, one step back292Making requests with Basic Auth is extremely simple::Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
line 293why, one step back293Merge branch 'develop'Kenneth Reitzbefore adoptiond1dfa02
lines 294–300why, one step back294 >>> from requests.auth import HTTPBasicAuth295 >>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))296 <Response [200]>297298Due to the prevalence of HTTP Basic Auth, requests provides a shorthand for299this authentication method::300Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
lines 301–303why, one step back301 >>> requests.get('https://api.github.com/user', auth=('user', 'pass'))302 <Response [200]>303Merge branch 'develop'Kenneth Reitzbefore adoptiond1dfa02
lines 304–305why, one step back304Providing the credentials as a tuple in this fashion is functionally equivalent305to the ``HTTPBasicAuth`` example above.Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
line 306why, one step back306Merge branch 'develop'Kenneth Reitzbefore adoption1165bec
line 307why, one step back307Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
lines 308–310why, one step back308Digest Authentication309---------------------310Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
line 311why, one step back311Another popular form of web service protection is Digest Authentication::Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
line 312why, one step back312Merge branch 'develop'Kenneth Reitzbefore adoptiond1dfa02
line 313why, one step back313 >>> from requests.auth import HTTPDigestAuthMerge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
line 314why, one step back314 >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'Merge branch 'develop'Kenneth Reitzbefore adoptiond1dfa02
line 315why, one step back315 >>> requests.get(url, auth=HTTPDigestAuth('user', 'pass'))Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
line 316why, one step back316 <Response [200]>Merge branch 'develop'Kenneth Reitzbefore adoptiond1dfa02
lines 317–323why, one step back317318319OAuth Authentication320--------------------321322Miguel Araujo's `requests-oauth <http://pypi.python.org/pypi/requests-oauth>`_ project provides a simple interface for323establishing OAuth connections. Documentation and examples can be found on the requests-oauth `git repository <https://github.com/maraujop/requests-oauth>`_.Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
line 324why, one step back324Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
lines 325–328why, one step back325326Redirection and History327-----------------------328Merge branch 'develop'Kenneth Reitzbefore adoption8c1fd5d
line 329why, one step back329Requests will automatically perform location redirection while using idempotent methods.Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
lines 330–332why, one step back330331GitHub redirects all HTTP requests to HTTPS. Let's see what happens::332Merge branch 'develop'Kenneth Reitzbefore adoption1165bec
line 333why, one step back333 >>> r = requests.get('http://github.com')Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
lines 334–344why, one step back334 >>> r.url335 'https://github.com/'336 >>> r.status_code337 200338 >>> r.history339 [<Response [301]>]340341The :class:`Response.history` list contains a list of the342:class:`Request` objects that were created in order to complete the request.343344If you're using GET, HEAD, or OPTIONS, you can disable redirectionMerge branch 'develop'Kenneth Reitzbefore adoption8c1fd5d
line 345why, one step back345handling with the ``allow_redirects`` parameter::Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
line 346why, one step back346Merge branch 'develop'Kenneth Reitzbefore adoption8c1fd5d
line 347why, one step back347 >>> r = requests.get('http://github.com', allow_redirects=False)Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
lines 348–354why, one step back348 >>> r.status_code349 301350 >>> r.history351 []352353If you're using POST, PUT, PATCH, *&c*, you can also explicitly enable redirection as well::354Merge branch 'develop'Kenneth Reitzbefore adoption1165bec
line 355why, one step back355 >>> r = requests.post('http://github.com', allow_redirects=True)Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
lines 356–373why, one step back356 >>> r.url357 'https://github.com/'358 >>> r.history359 [<Response [301]>]360361362Timeouts363--------364365You can tell requests to stop waiting for a response after a given number of seconds with the ``timeout`` parameter::366367 >>> requests.get('http://github.com', timeout=0.001)368 Traceback (most recent call last):369 File "<stdin>", line 1, in <module>370 requests.exceptions.Timeout: Request timed out.371372.. admonition:: Note373Merge branch 'develop'Kenneth Reitzbefore adoption8c1fd5d
line 374why, one step back374 ``timeout`` only effects the connection process itself, not the downloading of the response body.Merge branch 'develop'Kenneth Reitzbefore adoption6e9cb09
lines 375–391why, one step back375376377Errors and Exceptions378---------------------379380In the event of a network problem (e.g. DNS failure, refused connection, etc),381Requests will raise a :class:`ConnectionError` exception.382383In the event of the rare invalid HTTP response, Requests will raise384an :class:`HTTPError` exception.385386If a request times out, a :class:`Timeout` exception is raised.387388If a request exceeds the configured number of maximum redirections, a :class:`TooManyRedirects` exception is raised.389390All exceptions that Requests explicitly raises inherit from391:class:`requests.exceptions.RequestException`.Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
line 392why, one step back392Merge pull request #333 from bryanhelmig/developKenneth Reitzbefore adoption281e059
lines 393–396why, one step back393You can refer to :ref:`Configuration API Docs <configurations>` for immediate raising of :class:`HTTPError` exceptions394via the ``danger_mode`` option or have Requests catch the majority of :class:`requests.exceptions.RequestException` exceptions395with the ``safe_mode`` option.396Merge branch 'develop'Kenneth Reitzbefore adoption6b9cb05
lines 397–398why, one step back397-----------------------398Merge branch 'develop'Kenneth Reitzbefore adoptiond0b96f8
line 399why, one step back399Ready for more? Check out the :ref:`advanced <advanced>` section.