Skip to content
Myr

First draft of full verbs.

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

authored by Cory Benfield · committed by Cory Benfield · parent 36fd8da · Browse files · 1 file+156 added−0 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+156 added−0 removed

  • other:+156 added−0 removed

1 file+156 added−0 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.