Skip to content
Myr

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

1 file+102 added−123 removed

modified:docs/user/quickstart.rst+102 added-123 removed
13 unmodified lines
14* Requests is :ref:`installed <install>`15* Requests is :ref:`up-to-date <updates>`161718Lets gets started with some simple use cases and examples.18Let's get started with some simple examples.192021Make a GET Request21Make a Request22------------------2324Making a standard request with Requests is very simple.24Making a request with Requests is very simple.2526Let's get GitHub's public timeline ::26Begin by importing the Requests module::27 28 >>> import requests2928 r = requests.get('https://github.com/timeline.json')30Now, let's try to get a webpage. For this example, let's get GitHub's public31timeline ::3233 >>> r = requests.get('https://github.com/timeline.json')3435Now, we have a :class:`Response` object called ``r``. We can get all the31information we need from this.36information we need from this object.3733Typically, you want to send some sort of data in the urls query string.34To do this, simply pass a dictionary to the `params` argument. Your35dictionary of data will automatically be encoded when the request is made::38Requests' simple API means that all forms of HTTP request are as obvious. For39example, this is how you make an HTTP POST request::40 41 >>> r = requests.post("http://httpbin.org/post")4243Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and44OPTIONS? 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")5051That's all well and good, but it's also only the start of what Requests can52do.535455Passing Parameters In URLs56--------------------------5758You often want to send some sort of data in the URL's query string. If59you were constructing the URL by hand, this data would be given as key/value60pairs in the URL after a question mark, e.g. ``httpbin.org/get?key=val``.61Requests 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 the64following code::6566 >>> 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 }6869You can see that the URL has been correctly encoded by printing the URL::7071 >>> print r.url72 u'http://httpbin.org/get?key2=value2&key1=value1'73 7475Response Content76----------------7763We can read the content of the server's response::78We can read the content of the server's response. Consider the GitHub timeline79again::8081 >>> import requests82 >>> r = requests.get('https://github.com/timeline.json')83 >>> r.text84 '[{"repository":{"open_issues":0,"url":"https://github.com/...8586Requests will automatically decode content from the server. Most unicode
15 unmodified lines
102 b'[{"repository":{"open_issues":0,"url":"https://github.com/...103104The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.10588For example to create an image from binary data returned by a request, you can106For example, to create an image from binary data returned by a request, you can107use the following code:108109 >>> from PIL import Image110 >>> from StringIO import StringIO
12 unmodified lines
123 >>> r.raw.read(10)124 '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'125126127Custom Headers128--------------129110Make a POST Request111-------------------130If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the131``headers`` parameter.132113POST requests are equally simple::133For example, we didn't specify our content-type in the previous example::134115 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'}139140 >>> r = requests.post(url, data=json.dumps(payload), headers=headers)141142143More complicated POST requests144------------------------------145146Typically, you want to send some form-encoded data — much like an HTML form.147To do this, simply pass a dictionary to the `data` argument. Your148dictionary of data will automatically be form-encoded when the request is made::149150 >>> 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 }161162There 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.163164For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data::165166 >>> 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'}169152 r = requests.post(url, data=json.dumps(payload))170 >>> r = requests.post(url, data=json.dumps(payload))171172155Custom Headers156--------------157158If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the159``headers`` parameter.160161For example, we didn't specify our content-type in the previous example::162163 url = 'https://api.github.com/some/endpoint'164 payload = {'some': 'data'}165 headers = {'content-type': 'application/json'}166167 r = requests.post(url, data=json.dumps(payload), headers=headers)168169173POST a Multipart-Encoded File174-----------------------------175176Requests makes it simple to upload Multipart-encoded files::
3 unmodified lines
180181 >>> 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 }190199Setting filename explicitly::191You can set the filename explicitly::192193 >>> url = 'http://httpbin.org/post'194 >>> files = {'file': ('report.xls', open('report.xls', 'rb'))}195196 >>> 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 }205225Sending strings to be received as files::206If you want, you can send strings to be received as files::207208 >>> url = 'http://httpbin.org/post'209 >>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')} 210211 >>> 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 }220221222Response Status Codes223---------------------224225We can check the response status code::226227 >>> r = requests.get("http://httpbin.org/get')228 >>> r.status_code229 200230231Requests also comes with a built-in status code lookup object for easy
14 unmodified lines
246 File "requests/models.py", line 394, in raise_for_status247 raise self.error248 urllib2.HTTPError: HTTP Error 404: NOT FOUND249281But, since our ``status_code`` was ``200``, when we call it::250But, since our ``status_code`` for ``r`` was ``200``, when we call251``raise_for_status()`` we get::252253 >>> r.raise_for_status()254 None255
2 unmodified lines
258259Response Headers260----------------261292We can view the server's response headers with a simple Python dictionary293interface::262We can view the server's response headers using a Python dictionary::263264 >>> r.headers265 {266 'status': '200 OK',
48 unmodified lines
315316Basic Authentication317--------------------318350Most web services require authentication. There many different types of319Many web services require authentication. There many different types of320authentication, but the most common is HTTP Basic Auth.321322Making requests with Basic Auth is extremely simple::323
24 unmodified lines
348349OAuth Authentication350--------------------351383Miguel Araujo's `requests-oauth <http://pypi.python.org/pypi/requests-oauth>`_ project provides a simple interface for384establishing OAuth connections. Documentation and examples can be found on the requests-oauth `git repository <https://github.com/maraujop/requests-oauth>`_.352Miguel Araujo's `requests-oauth <http://pypi.python.org/pypi/requests-oauth>`_353project provides a simple interface for establishing OAuth connections.354Documentation and examples can be found on the requests-oauth355`git repository <https://github.com/maraujop/requests-oauth>`_.356357358Redirection and History359-----------------------360390Requests will automatically perform location redirection while using idempotent methods.361Requests will automatically perform location redirection while using362idempotent methods, such as GET.363392GitHub redirects all HTTP requests to HTTPS. Let's see what happens::364GitHub redirects all HTTP requests to HTTPS. We can use the ``history`` method365of the Response object to track redirection. Let's see what Github does::366367 >>> r = requests.get('http://github.com')368 >>> r.url369 'https://github.com/'
13 unmodified lines
383 301384 >>> r.history385 []386414If you're using POST, PUT, PATCH, *&c*, you can also explicitly enable redirection as well::387If you're using POST, PUT, PATCH, *&c*, you can also explicitly enable388redirection as well::389390 >>> r = requests.post('http://github.com', allow_redirects=True)391 >>> r.url392 'https://github.com/'
3 unmodified lines
396397Timeouts398--------399426You can tell requests to stop waiting for a response after a given number of seconds with the ``timeout`` parameter::400You can tell requests to stop waiting for a response after a given number of401seconds with the ``timeout`` parameter::402403 >>> 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.407433.. admonition:: Note408.. admonition:: Note:409435 ``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.412413414Errors and Exceptions415---------------------
5 unmodified lines
421an :class:`HTTPError` exception.422423If a request times out, a :class:`Timeout` exception is raised.424449If a request exceeds the configured number of maximum redirections, a :class:`TooManyRedirects` exception is raised.425If a request exceeds the configured number of maximum redirections, a426:class:`TooManyRedirects` exception is raised.427428All exceptions that Requests explicitly raises inherit from429:class:`requests.exceptions.RequestException`.430454You can refer to :ref:`Configuration API Docs <configurations>` for immediate raising of :class:`HTTPError` exceptions455via the ``danger_mode`` option or have Requests catch the majority of :class:`requests.exceptions.RequestException` exceptions456with the ``safe_mode`` option.431You can refer to :ref:`Configuration API Docs <configurations>` for immediate432raising of :class:`HTTPError` exceptions via the ``danger_mode`` option or433have Requests catch the majority of434:class:`requests.exceptions.RequestException` exceptions with the ``safe_mode``435option.436437-----------------------438439Ready for more? Check out the :ref:`advanced <advanced>` section.