Learning Python Network Programming

(Sean Pound) #1

APIs in Action


Authenticating requests


We now have enough information for authenticating requests. Twitter uses an
authentication standard called oAuth, version 1.0a. It's described in detail at
http://oauth.net/core/1.0a/.


The oAuth authentication standard is a little tricky, but fortunately the Requests
module has a companion library called requests-oauthlib, which can handle most
of the complexity for us. This is available on PyPi, so we can download and install it
with pip.


$ pip install requests-oauthlib
Downloading/unpacking requests-oauthlib


Now, we can add authentication to our requests, and then write our application.


A Twitter client


Save the code mentioned here to a file, and save it as twitter_worldclock.py.
You'll need to replace , , ,
and with the values that you have taken down from the
aforementioned Twitter app configuration:


import requests, requests_oauthlib, sys

consumer_key = '<CONSUMER_KEY>'
consumer_secret = '<CONSUMER_SECRET>'
access_token = '<ACCESS_TOKEN>'
access_secret = '<ACCESS_KEY>'

def init_auth():
auth_obj = requests_oauthlib.OAuth1(
consumer_key, consumer_secret,
access_token, access_secret)

if verify_credentials(auth_obj):
print('Validated credentials OK')
return auth_obj
else:
print('Credentials validation failed')
sys.exit(1)

def verify_credentials(auth_obj):
url = 'https://api.twitter.com/1.1/' \
'account/verify_credentials.json'
response = requests.get(url, auth=auth_obj)
return response.status_code == 200
Free download pdf