Skip to content
Myr

advanced.rst

This file

Path

docs/user/advanced.rst

561 lines · 19.3 KiB

Last changed by

Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoptionffc72ac

History of this file

Take it

The walk stopped after 200 commits: lines older than 511b139 point at it.

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 1–53why, one step back
1.. _advanced:
23Advanced Usage4==============56This document covers some of Requests more advanced features.789Session Objects10---------------1112The Session object allows you to persist certain parameters across13requests. It also persists cookies across all requests made from the14Session instance.1516A session object has all the methods of the main Requests API.1718Let's persist some cookies across requests::1920 s = requests.session()2122 s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')23 r = s.get("http://httpbin.org/cookies")2425 print r.text26 # '{"cookies": {"sessioncookie": "123456789"}}'272829Sessions can also be used to provide default data to the request methods::3031 headers = {'x-test': 'true'}32 auth = ('user', 'pass')3334 with requests.session(auth=auth, headers=headers) as c:3536 # both 'x-test' and 'x-test2' are sent37 c.get('http://httpbin.org/headers', headers={'x-test2': 'true'})383940Any dictionaries that you pass to a request method will be merged with the session-level values that are set. The method-level parameters override session parameters.4142.. admonition:: Remove a Value From a Dict Parameter4344 Sometimes you'll want to omit session-level keys from a dict parameter. To do this, you simply set that key's value to ``None`` in the method-level parameter. It will automatically be omitted.4546All values that are contained within a session are directly available to you. See the :ref:`Session API Docs <sessionapi>` to learn more.4748Request and Response Objects49----------------------------5051Whenever a call is made to requests.*() you are doing two major things. First,52you are constructing a ``Request`` object which will be sent of to a server53to request or query some resource. Second, a ``Response`` object is generated

cleanup #676Kenneth Reitzbefore adoption6b1e81c

line 54why, one step back
54once ``requests`` gets a response back from the server. The response object

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 55–57why, one step back
55contains all of the information returned by the server and also contains the
56``Request`` object you created originally. Here is a simple request to get some57very important information from Wikipedia's servers::

cleanup #676Kenneth Reitzbefore adoption6b1e81c

line 58why, one step back
58

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 59–61why, one step back
59 >>> response = requests.get('http://en.wikipedia.org/wiki/Monty_Python')
6061If we want to access the headers the server sent back to us, we do this::

cleanup #676Kenneth Reitzbefore adoption6b1e81c

line 62why, one step back
62

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 63–64why, one step back
63 >>> response.headers
64 {'content-length': '56170', 'x-content-type-options': 'nosniff', 'x-cache':

cleanup #676Kenneth Reitzbefore adoption6b1e81c

line 65why, one step back
65 'HIT from cp1006.eqiad.wmnet, MISS from cp1010.eqiad.wmnet', 'content-encoding':

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 66–95why, one step back
66 'gzip', 'age': '3080', 'content-language': 'en', 'vary': 'Accept-Encoding,Cookie',
67 'server': 'Apache', 'last-modified': 'Wed, 13 Jun 2012 01:33:50 GMT',68 'connection': 'close', 'cache-control': 'private, s-maxage=0, max-age=0,69 must-revalidate', 'date': 'Thu, 14 Jun 2012 12:59:39 GMT', 'content-type':70 'text/html; charset=UTF-8', 'x-cache-lookup': 'HIT from cp1006.eqiad.wmnet:3128,71 MISS from cp1010.eqiad.wmnet:80'}7273However, if we want to get the headers we sent the server, we simply access the74request, and then the request's headers::7576 >>> response.request.headers77 {'Accept-Encoding': 'identity, deflate, compress, gzip',78 'Accept': '*/*', 'User-Agent': 'python-requests/0.13.1'}798081SSL Cert Verification82---------------------8384Requests can verify SSL certificates for HTTPS requests, just like a web browser. To check a host's SSL certificate, you can use the ``verify`` argument::8586 >>> requests.get('https://kennethreitz.com', verify=True)87 requests.exceptions.SSLError: hostname 'kennethreitz.com' doesn't match either of '*.herokuapp.com', 'herokuapp.com'8889I don't have SSL setup on this domain, so it fails. Excellent. Github does though::9091 >>> requests.get('https://github.com', verify=True)92 <Response [200]>9394You can also pass ``verify`` the path to a CA_BUNDLE file for private certs. You can also set the ``REQUESTS_CA_BUNDLE`` environment variable.95

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

line 96why, one step back
96Requests can also ignore verifying the SSL certficate if you set ``verify`` to False.

Merge pull request #714 from muhtasib/developKenneth Reitzbefore adoptionc19ff03

line 97why, one step back
97

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

lines 98–99why, one step back
98::
99

Merge pull request #714 from muhtasib/developKenneth Reitzbefore adoptionc19ff03

lines 100–114why, one step back
100 >>> requests.get('https://kennethreitz.com', verify=False)
101 <Response [200]>102103By default, ``verify`` is set to True. Option ``verify`` only applies to host certs.104105You can also specify the local cert file either as a path or key value pair::106107 >>> requests.get('https://kennethreitz.com', cert=('/path/server.crt', '/path/key'))108 <Response [200]>109110If you specify a wrong path or an invalid cert::111112 >>> requests.get('https://kennethreitz.com', cert='/wrong_path/server.pem')113 SSLError: [Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib114

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 115–118why, one step back
115
116Body Content Workflow117---------------------118

Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoptionc8f166f

line 119why, one step back
119By default, when you make a request, the body of the response is downloaded immediately. You can override this behavior and defer downloading the response body until you access the :class:`Response.content` attribute with the ``prefetch`` parameter::

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 120–121why, one step back
120
121 tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'

Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoptionc8f166f

line 122why, one step back
122 r = requests.get(tarball_url, prefetch=False)

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

line 123why, one step back
123

Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoptionc8f166f

line 124why, one step back
124At this point only the response headers have been downloaded and the connection remains open, hence allowing us to make content retrieval conditional::

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

line 125why, one step back
125

Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoptionc8f166f

lines 126–128why, one step back
126 if int(r.headers['content-length']) < TOO_LONG:
127 content = r.content128 ...

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

line 129why, one step back
129

Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoptionc8f166f

line 130why, one step back
130You can further control the workflow by use of the :class:`Response.iter_content` and :class:`Response.iter_lines` methods, or reading from the underlying urllib3 :class:`urllib3.HTTPResponse` at :class:`Response.raw`.

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

line 131why, one step back
131

Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoptionc8f166f

line 132why, one step back
132Note that in versions prior to 0.13.6 the ``prefetch`` default was set to ``False``.

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 133–279why, one step back
133
134Configuring Requests135--------------------136137Sometimes you may want to configure a request to customize its behavior. To do138this, you can pass in a ``config`` dictionary to a request or session. See the :ref:`Configuration API Docs <configurations>` to learn more.139140141Keep-Alive142----------143144Excellent news — thanks to urllib3, keep-alive is 100% automatic within a session! Any requests that you make within a session will automatically reuse the appropriate connection!145146Note that connections are only released back to the pool for reuse once all body data has been read; be sure to either set ``prefetch`` to ``True`` or read the ``content`` property of the ``Response`` object.147148If you'd like to disable keep-alive, you can simply set the ``keep_alive`` configuration to ``False``::149150 s = requests.session()151 s.config['keep_alive'] = False152153154Asynchronous Requests155----------------------156157158``requests.async`` has been removed from requests and is now its own repository named `GRequests <https://github.com/kennethreitz/grequests>`_.159160161Event Hooks162-----------163164Requests has a hook system that you can use to manipulate portions of165the request process, or signal event handling.166167Available hooks:168169``args``:170 A dictionary of the arguments being sent to Request().171172``pre_request``:173 The Request object, directly before being sent.174175``post_request``:176 The Request object, directly after being sent.177178``response``:179 The response generated from a Request.180181182You can assign a hook function on a per-request basis by passing a183``{hook_name: callback_function}`` dictionary to the ``hooks`` request184parameter::185186 hooks=dict(args=print_url)187188That ``callback_function`` will receive a chunk of data as its first189argument.190191::192193 def print_url(args):194 print args['url']195196If an error occurs while executing your callback, a warning is given.197198If the callback function returns a value, it is assumed that it is to199replace the data that was passed in. If the function doesn't return200anything, nothing else is effected.201202Let's print some request method arguments at runtime::203204 >>> requests.get('http://httpbin.org', hooks=dict(args=print_url))205 http://httpbin.org206 <Response [200]>207208Let's hijack some arguments this time with a new callback::209210 def hack_headers(args):211 if args.get('headers') is None:212 args['headers'] = dict()213214 args['headers'].update({'X-Testing': 'True'})215216 return args217218 hooks = dict(args=hack_headers)219 headers = dict(yo=dawg)220221And give it a try::222223 >>> requests.get('http://httpbin.org/headers', hooks=hooks, headers=headers)224 {225 "headers": {226 "Content-Length": "",227 "Accept-Encoding": "gzip",228 "Yo": "dawg",229 "X-Forwarded-For": "::ffff:24.127.96.129",230 "Connection": "close",231 "User-Agent": "python-requests.org",232 "Host": "httpbin.org",233 "X-Testing": "True",234 "X-Forwarded-Protocol": "",235 "Content-Type": ""236 }237 }238239240Custom Authentication241---------------------242243Requests allows you to use specify your own authentication mechanism.244245Any callable which is passed as the ``auth`` argument to a request method will246have the opportunity to modify the request before it is dispatched.247248Authentication implementations are subclasses of ``requests.auth.AuthBase``,249and are easy to define. Requests provides two common authentication scheme250implementations in ``requests.auth``: ``HTTPBasicAuth`` and ``HTTPDigestAuth``.251252Let's pretend that we have a web service that will only respond if the253``X-Pizza`` header is set to a password value. Unlikely, but just go with it.254255::256257 from requests.auth import AuthBase258 class PizzaAuth(AuthBase):259 """Attaches HTTP Pizza Authentication to the given Request object."""260 def __init__(self, username):261 # setup any auth-related data here262 self.username = username263264 def __call__(self, r):265 # modify and return the request266 r.headers['X-Pizza'] = self.username267 return r268269Then, we can make a request using our Pizza Auth::270271 >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))272 <Response [200]>273274Streaming Requests275------------------276277With ``requests.Response.iter_lines()`` you can easily iterate over streaming278APIs such as the `Twitter Streaming API <https://dev.twitter.com/docs/streaming-api>`_.279

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

line 280why, one step back
280To use the Twitter Streaming API to track the keyword "requests"::

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 281–285why, one step back
281
282 import requests283 import json284285 r = requests.post('https://stream.twitter.com/1/statuses/filter.json',

Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoptionffc72ac

line 286why, one step back
286 data={'track': 'requests'}, auth=('username', 'password'), prefetch=False)

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 287–310why, one step back
287
288 for line in r.iter_lines():289 if line: # filter out keep-alive new lines290 print json.loads(line)291292293Verbose Logging294---------------295296If you want to get a good look at what HTTP requests are being sent297by your application, you can turn on verbose logging.298299To do so, just configure Requests with a stream to write to::300301 >>> my_config = {'verbose': sys.stderr}302 >>> requests.get('http://httpbin.org/headers', config=my_config)303 2011-08-17T03:04:23.380175 GET http://httpbin.org/headers304 <Response [200]>305306307Proxies308-------309310If you need to use a proxy, you can configure individual requests with the

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

line 311why, one step back
311``proxies`` argument to any request method::

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 312–331why, one step back
312
313 import requests314315 proxies = {316 "http": "10.10.1.10:3128",317 "https": "10.10.1.10:1080",318 }319320 requests.get("http://example.org", proxies=proxies)321322You can also configure proxies by environment variables ``HTTP_PROXY`` and ``HTTPS_PROXY``.323324::325326 $ export HTTP_PROXY="10.10.1.10:3128"327 $ export HTTPS_PROXY="10.10.1.10:1080"328 $ python329 >>> import requests330 >>> requests.get("http://example.org")331

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

line 332why, one step back
332To use HTTP Basic Auth with your proxy, use the `http://user:password@host/` syntax::

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 333–337why, one step back
333
334 proxies = {335 "http": "http://user:pass@10.10.1.10:3128/",336 }337

Merge pull request #772 from Lukasa/developKenneth Reitzbefore adoption6464618

lines 338–361why, one step back
338Compliance
339----------340341Requests is intended to be compliant with all relevant specifications and342RFCs where that compliance will not cause difficulties for users. This343attention to the specification can lead to some behaviour that may seem344unusual to those not familiar with the relevant specification.345346Encodings347^^^^^^^^^348349When you receive a response, Requests makes a guess at the encoding to use for350decoding the response when you call the ``Response.text`` method. Requests351will first check for an encoding in the HTTP header, and if none is present,352will use `chardet <http://pypi.python.org/pypi/chardet>`_ to attempt to guess353the encoding.354355The only time Requests will not do this is if no explicit charset is present356in the HTTP headers **and** the ``Content-Type`` header contains ``text``. In357this situation,358`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_359specifies that the default charset must be ``ISO-8859-1``. Requests follows360the specification in this case. If you require a different encoding, you can361manually set the ``Response.encoding`` property, or use the raw

typoKenneth Reitzbefore adoptionb257b10

line 362why, one step back
362``Response.content``.

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 363–393why, one step back
363
364HTTP Verbs365----------366367Requests provides access to almost the full range of HTTP verbs: GET, OPTIONS,368HEAD, POST, PUT, PATCH and DELETE. The following provides detailed examples of369using these various verbs in Requests, using the GitHub API.370371We will begin with the verb most commonly used: GET. HTTP GET is an idempotent372method that returns a resource from a given URL. As a result, it is the verb373you ought to use when attempting to retrieve data from a web location. An374example usage would be attempting to get information about a specific commit375from GitHub. Suppose we wanted commit ``a050faf`` on Requests. We would get it376like so::377378 >>> import requests379 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad')380381We should confirm that GitHub responded correctly. If it has, we want to work382out what type of content it is. Do this like so::383384 >>> if (r.status_code == requests.codes.ok):385 ... print r.headers['content-type']386 ...387 application/json; charset=utf-8388389So, GitHub returns JSON. That's great, we can use the JSON module to turn it390into Python objects. Because GitHub returned UTF-8, we should use the391``r.text`` method, not the ``r.content`` method. ``r.content`` returns a392bytestring, while ``r.text`` returns a Unicode-encoded string. I have no plans393to perform byte-manipulation on this response, so I want any Unicode code

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

line 394why, one step back
394points encoded.

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

line 395why, one step back
395

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

lines 396–397why, one step back
396::
397

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 398–409why, one step back
398 >>> import json
399 >>> commit_data = json.loads(r.text)400 >>> print commit_data.keys()401 [u'committer', u'author', u'url', u'tree', u'sha', u'parents', u'message']402 >>> print commit_data[u'committer']403 {u'date': u'2012-05-10T11:10:50-07:00', u'email': u'me@kennethreitz.com', u'name': u'Kenneth Reitz'}404 >>> print commit_data[u'message']405 makin' history406407So far, so simple. Well, let's investigate the GitHub API a little bit. Now,408we could look at the documentation, but we might have a little more fun if we409use Requests instead. We can take advantage of the Requests OPTIONS verb to

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

line 410why, one step back
410see what kinds of HTTP methods are supported on the url we just used.

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

line 411why, one step back
411

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

lines 412–413why, one step back
412::
413

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 414–421why, one step back
414 >>> verbs = requests.options(r.url)
415 >>> verbs.status_code416 500417418Uh, what? That's unhelpful! Turns out GitHub, like many API providers, don't419actually implement the OPTIONS method. This is an annoying oversight, but it's420OK, we can just use the boring documentation. If GitHub had correctly421implemented OPTIONS, however, they should return the allowed methods in the

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

line 422why, one step back
422headers, e.g.

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

line 423why, one step back
423

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

lines 424–425why, one step back
424::
425

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 426–435why, one step back
426 >>> verbs = requests.options('http://a-good-website.com/api/cats')
427 >>> print verbs.headers['allow']428 GET,HEAD,POST,OPTIONS429430Turning to the documentation, we see that the only other method allowed for431commits is POST, which creates a new commit. As we're using the Requests repo,432we should probably avoid making ham-handed POSTS to it. Instead, let's play433with the Issues feature of GitHub.434435This documentation was added in response to Issue #482. Given that this issue

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

line 436why, one step back
436already exists, we will use it as an example. Let's start by getting it.

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

line 437why, one step back
437

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

lines 438–439why, one step back
438::
439

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 440–448why, one step back
440 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/issues/482')
441 >>> r.status_code442 200443 >>> issue = json.loads(r.text)444 >>> print issue[u'title']445 Feature any http verb in docs446 >>> print issue[u'comments']447 3448

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

line 449why, one step back
449Cool, we have three comments. Let's take a look at the last of them.

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

line 450why, one step back
450

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

lines 451–452why, one step back
451::
452

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 453–462why, one step back
453 >>> r = requests.get(r.url + u'/comments')
454 >>> r.status_code455 200456 >>> comments = json.loads(r.text)457 >>> print comments[0].keys()458 [u'body', u'url', u'created_at', u'updated_at', u'user', u'id']459 >>> print comments[2][u'body']460 Probably in the "advanced" section461462Well, that seems like a silly place. Let's post a comment telling the poster

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

line 463why, one step back
463that he's silly. Who is the poster, anyway?

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

line 464why, one step back
464

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

lines 465–466why, one step back
465::
466

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 467–471why, one step back
467 >>> print comments[2][u'user'][u'login']
468 kennethreitz469470OK, so let's tell this Kenneth guy that we think this example should go in the471quickstart guide instead. According to the GitHub API doc, the way to do this

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

line 472why, one step back
472is to POST to the thread. Let's do it.

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

line 473why, one step back
473

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

lines 474–475why, one step back
474::
475

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 476–483why, one step back
476 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it!"})
477 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/482/comments"478 >>> r = requests.post(url=url, data=body)479 >>> r.status_code480 404481482Huh, that's weird. We probably need to authenticate. That'll be a pain, right?483Wrong. Requests makes it easy to use many forms of authentication, including

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

line 484why, one step back
484the very common Basic Auth.

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

line 485why, one step back
485

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

lines 486–487why, one step back
486::
487

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 488–499why, one step back
488 >>> from requests.auth import HTTPBasicAuth
489 >>> auth = HTTPBasicAuth('fake@example.com', 'not_a_real_password')490 >>> r = requests.post(url=url, data=body, auth=auth)491 >>> r.status_code492 201493 >>> content = json.loads(r.text)494 >>> print content[u'body']495 Sounds great! I'll get right on it.496497Brilliant. Oh, wait, no! I meant to add that it would take me a while, because498I had to go feed my cat. If only I could edit this comment! Happily, GitHub499allows us to use another HTTP verb, PATCH, to edit this comment. Let's do

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

line 500why, one step back
500that.

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

line 501why, one step back
501

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

lines 502–503why, one step back
502::
503

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 504–514why, one step back
504 >>> print content[u"id"]
505 5804413506 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it once I feed my cat."})507 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/comments/5804413"508 >>> r = requests.patch(url=url, data=body, auth=auth)509 >>> r.status_code510 200511512Excellent. Now, just to torture this Kenneth guy, I've decided to let him513sweat and not tell him that I'm working on this. That means I want to delete514this comment. GitHub lets us delete comments using the incredibly aptly named

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

line 515why, one step back
515DELETE method. Let's get rid of it.

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

line 516why, one step back
516

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

lines 517–518why, one step back
517::
518

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 519–527why, one step back
519 >>> r = requests.delete(url=url, auth=auth)
520 >>> r.status_code521 204522 >>> r.headers['status']523 '204 No Content'524525Excellent. All gone. The last thing I want to know is how much of my ratelimit526I've used. Let's find out. GitHub sends that information in the headers, so527rather than download the whole page I'll send a HEAD request to get the

Merge branch 'develop' of git://github.com/weak/requests into developKenneth Reitzbefore adoption95c82c7

lines 528–530why, one step back
528headers.
529530::

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 531–533why, one step back
531
532 >>> r = requests.head(url=url, auth=auth)533 >>> print r.headers

link headersKenneth Reitzbefore adoptiona032e7c

line 534why, one step back
534 ...

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 535–536why, one step back
535 'x-ratelimit-remaining': '4995'
536 'x-ratelimit-limit': '5000'

link headersKenneth Reitzbefore adoptiona032e7c

line 537why, one step back
537 ...

Merge pull request #676 from apotheos/developKenneth Reitzbefore adoption511b139

lines 538–540why, one step back
538
539Excellent. Time to write a Python program that abuses the GitHub API in all540kinds of exciting ways, 4995 more times.

link headersKenneth Reitzbefore adoptiona032e7c

lines 541–550why, one step back
541
542Link Headers543------------544545Many HTTP APIs feature Link headers. They make APIs more self describing and discoverable.546547GitHub uses these for `pagination <http://developer.github.com/v3/#pagination>`_ in their API, for example::548549 >>> url = 'https://api.github.com/users/kennethreitz/repos?page=1&per_page=10'550 >>> r = requests.head(url=url)

link docs!Kenneth Reitzbefore adoption49a7947

lines 551–552why, one step back
551 >>> r.headers['link']
552 '<https://api.github.com/users/kennethreitz/repos?page=2&per_page=10>; rel="next", <https://api.github.com/users/kennethreitz/repos?page=6&per_page=10>; rel="last"'

link headersKenneth Reitzbefore adoptiona032e7c

line 553why, one step back
553

link docs!Kenneth Reitzbefore adoption49a7947

line 554why, one step back
554Requests will automatically parse these link headers and make them easily consumable::

link headersKenneth Reitzbefore adoptiona032e7c

line 555why, one step back
555

link docs!Kenneth Reitzbefore adoption49a7947

lines 556–557why, one step back
556 >>> r.links['next']
557 'https://api.github.com/users/kennethreitz/repos?page=2&per_page=10'

link headersKenneth Reitzbefore adoptiona032e7c

line 558why, one step back
558

link docs!Kenneth Reitzbefore adoption49a7947

lines 559–560why, one step back
559 >>> r.links['last']
560 'https://api.github.com/users/kennethreitz/repos?page=6&per_page=10'

link headersKenneth Reitzbefore adoptiona032e7c

line 561why, one step back
561