Skip to content
Myr

Merge pull request #619 from Lukasa/develop

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Rewrite quickstart docs.

authored by Kenneth Reitz · committed by Kenneth Reitz · parents f9dd485, 2b8e01b · Browse files · 2 files+260 added−125 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+260 added−125 removed

  • other:+260 added−125 removed

2 files+260 added−125 removed

modified:docs/user/advanced.rst+156 added
317 unmodified lines
318 $ export HTTPS_PROXY="10.10.1.10:1080"319 $ python320 >>> import requests321 >>> requests.get("http://example.org")322323HTTP Verbs324----------325326Requests provides access to almost the full range of HTTP verbs: GET, OPTIONS,327HEAD, POST, PUT, PATCH and DELETE. The following provides detailed examples of328using these various verbs in Requests, using the GitHub API.329330We will begin with the verb most commonly used: GET. HTTP GET is an idempotent331method that returns a resource from a given URL. As a result, it is the verb332you ought to use when attempting to retrieve data from a web location. An333example usage would be attempting to get information about a specific commit334from GitHub. Suppose we wanted commit ``a050faf`` on Requests. We would get it335like so::336337 >>> import requests338 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad')339340We should confirm that GitHub responded correctly. If it has, we want to work341out what type of content it is. Do this like so::342343 >>> if (r.status_code == requests.codes.ok):344 ... print r.headers['content-type']345 ...346 application/json; charset=utf-8347348So, GitHub returns JSON. That's great, we can use the JSON module to turn it349into Python objects. Because GitHub returned UTF-8, we should use the350``r.text`` method, not the ``r.content`` method. ``r.content`` returns a351bytestring, while ``r.text`` returns a Unicode-encoded string. I have no plans352to perform byte-manipulation on this response, so I want any Unicode code353points encoded.::354355 >>> import json356 >>> commit_data = json.loads(r.text)357 >>> print commit_data.keys()358 [u'committer', u'author', u'url', u'tree', u'sha', u'parents', u'message']359 >>> print commit_data[u'committer']360 {u'date': u'2012-05-10T11:10:50-07:00', u'email': u'me@kennethreitz.com', u'name': u'Kenneth Reitz'}361 >>> print commit_data[u'message']362 makin' history363364So far, so simple. Well, let's investigate the GitHub API a little bit. Now,365we could look at the documentation, but we might have a little more fun if we366use Requests instead. We can take advantage of the Requests OPTIONS verb to367see what kinds of HTTP methods are supported on the url we just used.::368369 >>> verbs = requests.options(r.url)370 >>> verbs.status_code371 500372373Uh, what? That's unhelpful! Turns out GitHub, like many API providers, don't374actually implement the OPTIONS method. This is an annoying oversight, but it's375OK, we can just use the boring documentation. If GitHub had correctly376implemented OPTIONS, however, they should return the allowed methods in the377headers, e.g.::378379 >>> verbs = requests.options('http://a-good-website.com/api/cats')380 >>> print verbs.headers['allow']381 GET,HEAD,POST,OPTIONS382383Turning to the documentation, we see that the only other method allowed for384commits is POST, which creates a new commit. As we're using the Requests repo,385we should probably avoid making ham-handed POSTS to it. Instead, let's play386with the Issues feature of GitHub.387388This documentation was added in response to Issue #482. Given that this issue389already exists, we will use it as an example. Let's start by getting it.::390391 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/issues/482')392 >>> r.status_code393 200394 >>> issue = json.loads(r.text)395 >>> print issue[u'title']396 Feature any http verb in docs397 >>> print issue[u'comments']398 3399400Cool, we have three comments. Let's take a look at the last of them.::401402 >>> r = requests.get(r.url + u'/comments')403 >>> r.status_code404 200405 >>> comments = json.loads(r.text)406 >>> print comments[0].keys()407 [u'body', u'url', u'created_at', u'updated_at', u'user', u'id']408 >>> print comments[2][u'body']409 Probably in the "advanced" section410411Well, that seems like a silly place. Let's post a comment telling the poster412that he's silly. Who is the poster, anyway?::413414 >>> print comments[2][u'user'][u'login']415 kennethreitz416417OK, so let's tell this Kenneth guy that we think this example should go in the418quickstart guide instead. According to the GitHub API doc, the way to do this419is to POST to the thread. Let's do it.::420421 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it!"})422 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/482/comments"423 >>> r = requests.post(url=url, data=body)424 >>> r.status_code425 404426427Huh, that's weird. We probably need to authenticate. That'll be a pain, right?428Wrong. Requests makes it easy to use many forms of authentication, including429the very common Basic Auth.::430431 >>> from requests.auth import HTTPBasicAuth432 >>> auth = HTTPBasicAuth('fake@example.com', 'not_a_real_password')433 >>> r = requests.post(url=url, data=body, auth=auth)434 >>> r.status_code435 201436 >>> content = json.loads(r.text)437 >>> print content[u'body']438 Sounds great! I'll get right on it.439440Brilliant. Oh, wait, no! I meant to add that it would take me a while, because441I had to go feed my cat. If only I could edit this comment! Happily, GitHub442allows us to use another HTTP verb, PATCH, to edit this comment. Let's do443that.::444445 >>> print content[u"id"]446 5804413447 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it once I feed my cat."})448 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/comments/5804413"449 >>> r = requests.patch(url=url, data=body, auth=auth)450 >>> r.status_code451 200452453Excellent. Now, just to torture this Kenneth guy, I've decided to let him454sweat and not tell him that I'm working on this. That means I want to delete455this comment. GitHub lets us delete comments using the incredibly aptly named456DELETE method. Let's get rid of it.::457458 >>> r = requests.delete(url=url, auth=auth)459 >>> r.status_code460 204461 >>> r.headers['status']462 '204 No Content'463464Excellent. All gone. The last thing I want to know is how much of my ratelimit465I've used. Let's find out. GitHub sends that information in the headers, so466rather than download the whole page I'll send a HEAD request to get the467headers.::468469 >>> r = requests.head(url=url, auth=auth)470 >>> print r.headers471 // ...snip... //472 'x-ratelimit-remaining': '4995'473 'x-ratelimit-limit': '5000'474 // ...snip... //475476Excellent. Time to write a Python program that abuses the GitHub API in all477kinds of exciting ways, 4995 more times.
modified:docs/user/quickstart.rst+104 added-125 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 using the GET362and OPTIONS verbs.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/'
4 unmodified lines
374375The :class:`Response.history` list contains a list of the376:class:`Request` objects that were created in order to complete the request.377405If you're using GET, HEAD, or OPTIONS, you can disable redirection406handling with the ``allow_redirects`` parameter::378If you're using GET or OPTIONS, you can disable redirection handling with the379``allow_redirects`` parameter::380381 >>> r = requests.get('http://github.com', allow_redirects=False)382 >>> r.status_code383 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, DELETE or HEAD, you can 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.