Skip to content

Instantly share code, notes, and snippets.

@tzengerink
Last active August 29, 2015 14:01
Show Gist options
  • Save tzengerink/0d46543b169cc393588a to your computer and use it in GitHub Desktop.
Save tzengerink/0d46543b169cc393588a to your computer and use it in GitHub Desktop.
Consume an API that uses OAuth

OAuth Consumer

Consumes an API that uses OAuth.

Copy the file example.service.cnf to service.cnf and change the configuration variables to your liking, then:

$> python2 oauth-consumer.py [http method] [uri] [data]

For example:

$> python2 oauth-consumer.py put user/profile '{"fname":"Luke", "lname":"Skywalker"}'
service.cnf
keys.cnf
[service]
name = API Service
consumer_key = MyConsumerKey
consumer_secret = MyConsumerSecret
request_token_url = http://api.domain.tld/oauth/requesttoken
access_token_url = http://api.domain.tld/oauth/accesstoken
authorize_url = http://api.domain.tld/oauth/authorize
base_url = http://api.domain.tld/
#!/bin/env python
# -*- coding: utf-8 -*-
"""
OAUTH CONSUMER
--------------
Consume an API that uses OAuth.
Copyright (c) 2014 T. Zengerink
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import ConfigParser, json, sys
from rauth import OAuth1Service, OAuth1Session
class Api(object):
def __init__(self, service, session, key_manager):
self.service = service
self.key_manager = key_manager
self.session = session
self.request_token, self.request_secret = self.get_request_tokens()
self.access_token, self.access_secret = self.get_access_tokens()
def execute(self, *args, **kwargs):
method = getattr(self.session, args[0])
data = json.loads(args[2]) if len(args) is 3 else {}
return method('%s%s' % (self.service.base_url, args[1]),
headers={'Content-Type': 'application/json'},
data=data)
def get_access_tokens(self):
access_token, access_secret = self.key_manager.get()
if not access_token or not access_secret:
access_token, access_secret = self.service.get_access_token(
self.request_token,
self.request_secret,
method='POST',
header_auth=True,
data={'oauth_verifier':self.get_verifier()})
self.key_manager.set(access_token, access_secret)
self.session.access_token=access_token
self.session.access_token_secret=access_secret
return access_token, access_secret
def get_verifier(self):
print(self.service.get_authorize_url(self.request_token))
return raw_input('Enter authorization code: ')
def get_request_tokens(self):
return self.service.get_request_token(method='POST', header_auth=True)
class Config(dict):
def __init__(self):
filename = 'service.cnf'
config = ConfigParser.ConfigParser()
config.read(filename)
try:
self.update(dict(config.items('service')))
except ConfigParser.NoSectionError:
raise Exception('Could not read configuration \'%s\'' % filename)
class KeyManager(object):
def __init__(self):
self.filename = 'keys.cnf'
def get(self):
str = self.read_file()
if str:
return str.split(':')
return None, None
def read_file(self):
try:
f = open(self.filename, 'r')
str = f.read()
f.close()
except IOError:
str = ''
return str
def set(self, token, secret):
self.write_file('%s:%s' % (token, secret))
def write_file(self, str):
f = open(self.filename, 'w')
f.write(str)
f.close()
return str
def main(args):
config = Config()
session = OAuth1Session(consumer_key=config.get('consumer_key'),
consumer_secret=config.get('consumer_secret'))
api = Api(OAuth1Service(**config), session, KeyManager())
print(json.dumps(api.execute(*args).json()))
if __name__ == '__main__':
if len(sys.argv) > 1:
main(sys.argv[1:])
else:
print('Usage: %s %s %s %s' % (sys.argv[0], '[http method]', '[uri]',
'[data]'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment