Rewrite quickstart docs.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This should help with issue #503.
authored by Cory Benfield · committed by Cory Benfield · parent c477f6e · Browse files · 1 file·+102 added−123 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+102 added−123 removed
- other:+102 added−123 removed
Provenance
- Commit
45506d1- Tree
0689079- Author
Cory Benfield <lukasaoz@gmail.com>- Committer
Cory Benfield <lukasaoz@gmail.com>- Parent
c477f6e
1 file changed+102 added−123 removed
modified:docs/user/quickstart.rst+102 added-123 removed
13 unmodified lines14 * Requests is :ref:`installed <install>`15 * Requests is :ref:`up-to-date <updates>`16 17 18-Lets gets started with some simple use cases and examples.18+Let's get started with some simple examples.19 20 21-Make a GET Request21+Make a Request22 ------------------23 24-Making a standard request with Requests is very simple.24+Making a request with Requests is very simple.25 26-Let's get GitHub's public timeline ::26+Begin by importing the Requests module::27+ 28+ >>> import requests29 28- r = requests.get('https://github.com/timeline.json')30+Now, let's try to get a webpage. For this example, let's get GitHub's public31+timeline ::32 33+ >>> r = requests.get('https://github.com/timeline.json')34+35 Now, we have a :class:`Response` object called ``r``. We can get all the31-information we need from this.36+information we need from this object.37 33-Typically, you want to send some sort of data in the urls query string.34-To do this, simply pass a dictionary to the `params` argument. Your35-dictionary of data will automatically be encoded when the request is made::38+Requests' simple API means that all forms of HTTP request are as obvious. For39+example, this is how you make an HTTP POST request::40+ 41+ >>> r = requests.post("http://httpbin.org/post")42 43+Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and44+OPTIONS? These are all just as simple::45+ 46+ >>> 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")50+51+That's all well and good, but it's also only the start of what Requests can52+do.53+54+55+Passing Parameters In URLs56+--------------------------57+58+You often want to send some sort of data in the URL's query string. If59+you were constructing the URL by hand, this data would be given as key/value60+pairs in the URL after a question mark, e.g. ``httpbin.org/get?key=val``.61+Requests 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 the64+following code::65+66 >>> payload = {'key1': 'value1', 'key2': 'value2'}67 >>> r = requests.get("http://httpbin.org/get", params=payload)39- >>> print r.text40- {41- "origin": "179.13.100.4",42- "args": {43- "key2": "value2",44- "key1": "value1"45- },46- "url": "http://httpbin.org/get",47- "headers": {48- "Connections": "keep-alive",49- "Content-Length": "",50- "Accept-Encoding": "identity, deflate, compress, gzip",51- "Accept": "*/*",52- "User-Agent": "python-requests/0.11.0",53- "Host": httpbin.org",54- "Content-Type": ""55- },56- }68 69+You can see that the URL has been correctly encoded by printing the URL::70 71+ >>> print r.url72+ u'http://httpbin.org/get?key2=value2&key1=value1'73+ 74 75 Response Content76 ----------------77 63-We can read the content of the server's response::78+We can read the content of the server's response. Consider the GitHub timeline79+again::80 81+ >>> import requests82+ >>> r = requests.get('https://github.com/timeline.json')83 >>> r.text84 '[{"repository":{"open_issues":0,"url":"https://github.com/...85 86 Requests will automatically decode content from the server. Most unicode15 unmodified lines102 b'[{"repository":{"open_issues":0,"url":"https://github.com/...103 104 The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.105 88-For example to create an image from binary data returned by a request, you can106+For example, to create an image from binary data returned by a request, you can107 use the following code:108 109 >>> from PIL import Image110 >>> from StringIO import StringIO12 unmodified lines123 >>> r.raw.read(10)124 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'125 126 127+Custom Headers128+--------------129 110-Make a POST Request111--------------------130+If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the131+``headers`` parameter.132 113-POST requests are equally simple::133+For example, we didn't specify our content-type in the previous example::134 115- r = requests.post("http://httpbin.org/post")135+ >>> import json136+ >>> url = 'https://api.github.com/some/endpoint'137+ >>> payload = {'some': 'data'}138+ >>> headers = {'content-type': 'application/json'}139 140+ >>> r = requests.post(url, data=json.dumps(payload), headers=headers)141 142+143+More complicated POST requests144+------------------------------145+146 Typically, you want to send some form-encoded data — much like an HTML form.147 To do this, simply pass a dictionary to the `data` argument. Your148 dictionary of data will automatically be form-encoded when the request is made::149 150 >>> payload = {'key1': 'value1', 'key2': 'value2'}151 >>> r = requests.post("http://httpbin.org/post", data=payload)152 >>> print r.text153 {126- "origin": "179.13.100.4",127- "files": {},154+ // ...snip... //155 "form": {156 "key2": "value2",157 "key1": "value1"158 },132- "url": "http://httpbin.org/post",133- "args": {},134- "headers": {135- "Content-Length": "23",136- "Accept-Encoding": "identity, deflate, compress, gzip",137- "Accept": "*/*",138- "User-Agent": "python-requests/0.8.0",139- "Host": "127.0.0.1:7077",140- "Content-Type": "application/x-www-form-urlencoded"141- },142- "data": ""159+ // ...snip... //160 }161 162 There 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.163 164 For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::165 166+ >>> import json149- url = 'https://api.github.com/some/endpoint'150- payload = {'some': 'data'}167+ >>> url = 'https://api.github.com/some/endpoint'168+ >>> payload = {'some': 'data'}169 152- r = requests.post(url, data=json.dumps(payload))170+ >>> r = requests.post(url, data=json.dumps(payload))171 172 155-Custom Headers156---------------157-158-If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the159-``headers`` parameter.160-161-For example, we didn't specify our content-type in the previous example::162-163- url = 'https://api.github.com/some/endpoint'164- payload = {'some': 'data'}165- headers = {'content-type': 'application/json'}166-167- r = requests.post(url, data=json.dumps(payload), headers=headers)168-169-173 POST a Multipart-Encoded File174 -----------------------------175 176 Requests makes it simple to upload Multipart-encoded files::3 unmodified lines180 181 >>> r = requests.post(url, files=files)182 >>> r.text183 {181- "origin": "179.13.100.4",184+ // ...snip... //185 "files": {186 "report.xls": "<censored...binary...data>"187 },185- "form": {},186- "url": "http://httpbin.org/post",187- "args": {},188- "headers": {189- "Content-Length": "3196",190- "Accept-Encoding": "identity, deflate, compress, gzip",191- "Accept": "*/*",192- "User-Agent": "python-requests/0.8.0",193- "Host": "httpbin.org:80",194- "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"195- },196- "data": ""188+ // ...snip... //189 }190 199-Setting filename explicitly::191+You can set the filename explicitly::192 193 >>> url = 'http://httpbin.org/post'194 >>> files = {'file': ('report.xls', open('report.xls', 'rb'))}195 196 >>> r = requests.post(url, files=files)197 >>> r.text198 {207- "origin": "179.13.100.4",199+ // ...snip... //200 "files": {201 "file": "<censored...binary...data>"202 },211- "form": {},212- "url": "http://httpbin.org/post",213- "args": {},214- "headers": {215- "Content-Length": "3196",216- "Accept-Encoding": "identity, deflate, compress, gzip",217- "Accept": "*/*",218- "User-Agent": "python-requests/0.8.0",219- "Host": "httpbin.org:80",220- "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"221- },222- "data": ""203+ // ...snip... //204 }205 225-Sending strings to be received as files::206+If you want, you can send strings to be received as files::207 208 >>> url = 'http://httpbin.org/post'209 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')} 210 211 >>> r = requests.post(url, files=files)212 >>> r.text213 {233- "origin": "179.13.100.4",214+ // ...snip... //215 "files": {216 "file": "some,data,to,send\\nanother,row,to,send\\n"217 },237- "form": {},238- "url": "http://httpbin.org/post",239- "args": {},240- "headers": {241- "Content-Length": "216",242- "Accept-Encoding": "identity, deflate, compress, gzip",243- "Connection": "keep-alive",244- "Accept": "*/*",245- "User-Agent": "python-requests/0.11.1",246- "Host": "httpbin.org", 247- "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.41433.1335385481.788.1"248- }, 249- "json": null,250- "data": ""218+ // ...snip... //219 }220 221 222 Response Status Codes223 ---------------------224 225 We can check the response status code::226 227+ >>> r = requests.get("http://httpbin.org/get')228 >>> r.status_code229 200230 231 Requests also comes with a built-in status code lookup object for easy14 unmodified lines246 File "requests/models.py", line 394, in raise_for_status247 raise self.error248 urllib2.HTTPError: HTTP Error 404: NOT FOUND249 281-But, since our ``status_code`` was ``200``, when we call it::250+But, since our ``status_code`` for ``r`` was ``200``, when we call251+``raise_for_status()`` we get::252 253 >>> r.raise_for_status()254 None255 2 unmodified lines258 259 Response Headers260 ----------------261 292-We can view the server's response headers with a simple Python dictionary293-interface::262+We can view the server's response headers using a Python dictionary::263 264 >>> r.headers265 {266 'status': '200 OK',48 unmodified lines315 316 Basic Authentication317 --------------------318 350-Most web services require authentication. There many different types of319+Many web services require authentication. There many different types of320 authentication, but the most common is HTTP Basic Auth.321 322 Making requests with Basic Auth is extremely simple::323 24 unmodified lines348 349 OAuth Authentication350 --------------------351 383-Miguel Araujo's `requests-oauth <http://pypi.python.org/pypi/requests-oauth>`_ project provides a simple interface for384-establishing OAuth connections. Documentation and examples can be found on the requests-oauth `git repository <https://github.com/maraujop/requests-oauth>`_.352+Miguel Araujo's `requests-oauth <http://pypi.python.org/pypi/requests-oauth>`_353+project provides a simple interface for establishing OAuth connections.354+Documentation and examples can be found on the requests-oauth355+`git repository <https://github.com/maraujop/requests-oauth>`_.356 357 358 Redirection and History359 -----------------------360 390-Requests will automatically perform location redirection while using idempotent methods.361+Requests will automatically perform location redirection while using362+idempotent methods, such as GET.363 392-GitHub redirects all HTTP requests to HTTPS. Let's see what happens::364+GitHub redirects all HTTP requests to HTTPS. We can use the ``history`` method365+of the Response object to track redirection. Let's see what Github does::366 367 >>> r = requests.get('http://github.com')368 >>> r.url369 'https://github.com/'13 unmodified lines383 301384 >>> r.history385 []386 414-If you're using POST, PUT, PATCH, *&c*, you can also explicitly enable redirection as well::387+If you're using POST, PUT, PATCH, *&c*, you can also explicitly enable388+redirection as well::389 390 >>> r = requests.post('http://github.com', allow_redirects=True)391 >>> r.url392 'https://github.com/'3 unmodified lines396 397 Timeouts398 --------399 426-You can tell requests to stop waiting for a response after a given number of seconds with the ``timeout`` parameter::400+You can tell requests to stop waiting for a response after a given number of401+seconds with the ``timeout`` parameter::402 403 >>> requests.get('http://github.com', timeout=0.001)404 Traceback (most recent call last):405 File "<stdin>", line 1, in <module>406 requests.exceptions.Timeout: Request timed out.407 433-.. admonition:: Note408+.. admonition:: Note:409 435- ``timeout`` only effects the connection process itself, not the downloading of the response body.410+ ``timeout`` only effects the connection process itself, not the411+ downloading of the response body.412 413 414 Errors and Exceptions415 ---------------------5 unmodified lines421 an :class:`HTTPError` exception.422 423 If a request times out, a :class:`Timeout` exception is raised.424 449-If a request exceeds the configured number of maximum redirections, a :class:`TooManyRedirects` exception is raised.425+If a request exceeds the configured number of maximum redirections, a426+:class:`TooManyRedirects` exception is raised.427 428 All exceptions that Requests explicitly raises inherit from429 :class:`requests.exceptions.RequestException`.430 454-You can refer to :ref:`Configuration API Docs <configurations>` for immediate raising of :class:`HTTPError` exceptions455-via the ``danger_mode`` option or have Requests catch the majority of :class:`requests.exceptions.RequestException` exceptions456-with the ``safe_mode`` option.431+You can refer to :ref:`Configuration API Docs <configurations>` for immediate432+raising of :class:`HTTPError` exceptions via the ``danger_mode`` option or433+have Requests catch the majority of434+:class:`requests.exceptions.RequestException` exceptions with the ``safe_mode``435+option.436 437 -----------------------438 439 Ready for more? Check out the :ref:`advanced <advanced>` section.