Skip to content

Instantly share code, notes, and snippets.

@jcrosen
Last active February 9, 2018 00:31
Show Gist options
  • Save jcrosen/383d77ec16cff8350e1d to your computer and use it in GitHub Desktop.
Save jcrosen/383d77ec16cff8350e1d to your computer and use it in GitHub Desktop.
Example discogs API console with built-in Oauth support
#!/usr/bin/env python
#
# This illustrates the call-flow required to complete an OAuth request
# against the discogs.com API. The script will download and save a single
# image from the discogs.com API as an example.
# See README.md for further documentation.
#
import oauth2 as oauth
import urlparse
import json
import urllib
HOST = 'your_local_hostname'
PORT = '5000'
SERVER = '{}{}'.format(HOST, ':{}'.format(PORT) if PORT else '')
APP_BASE_URL = 'http://{}'.format(SERVER)
API_BASE_URL = 'http://api.{}'.format(SERVER)
CONTENT_TYPE = 'application/json'
def make_app_url(path):
return APP_BASE_URL + (path or '')
def make_api_url(path):
return API_BASE_URL + (path or '')
def make_body(data):
if CONTENT_TYPE == 'application/json':
return json.dumps(data)
else:
return urllib.urlencode(data)
# Your consumer key and consumer secret generated by discogs when an application is created
# and registered . See https://www.discogs.com/settings/developers . These credentials
# are assigned by application and remain static for the lifetime of your discogs application.
# the consumer details below were generated for the 'discogs-oauth-example' application.
consumer_key = 'mIEuHZBqcVDDeLHpfdiY'
consumer_secret = 'UfpUlKyDqlRFNFIwzurIBgqjpcXRijrs'
# The following oauth end-points are defined by discogs.com staff. These static endpoints
# are called at various stages of oauth handshaking.
request_token_url = make_api_url('/oauth/request_token')
authorize_url = make_app_url('/oauth/authorize')
access_token_url = make_api_url('/oauth/access_token')
# A user-agent is required with Discogs API requests. Be sure to make your user-agent
# unique, or you may get a bad response.
user_agent = 'discogs_api_example/1.0'
# create oauth Consumer and Client objects using
consumer = oauth.Consumer(consumer_key, consumer_secret)
client = oauth.Client(consumer)
# pass in your consumer key and secret to the token request URL. Discogs returns
# an ouath_request_token as well as an oauth request_token secret.
resp, content = client.request(request_token_url, 'POST', headers={'User-Agent': user_agent})
# we terminate if the discogs api does not return an HTTP 200 OK. Something is
# wrong.
if resp['status'] != '200':
raise Exception('Invalid response {0}.'.format(resp['status']))
request_token = dict(urlparse.parse_qsl(content))
print ' == Request Token == '
print ' * oauth_token = {0}'.format(request_token['oauth_token'])
print ' * oauth_token_secret = {0}'.format(request_token['oauth_token_secret'])
print
# Authorize our newly received request_token against the discogs oauth endpoint.
# Prompt your user to "accept" the terms of your application. The application
# will act on behalf of their discogs.com account.
# If the user accepts, discogs displays a key to the user that is used for
# verification. The key is required in the 2nd phase of authentication.
print 'Please browse to the following URL {0}?oauth_token={1}'.format(
authorize_url, request_token['oauth_token'])
# Waiting for user input
accepted = 'n'
while accepted.lower() == 'n':
print
accepted = raw_input('Have you authorized me at {0}?oauth_token={1} [y/n] :'.format(
authorize_url, request_token['oauth_token']))
# request the verification token from the user.
oauth_verifier = raw_input('Verification code: ')
# Generate objects that pass the verification key with the oauth token and oauth
# secret to the discogs access_token_url
token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret'])
token.set_verifier(oauth_verifier)
client = oauth.Client(consumer, token)
resp, content = client.request(access_token_url, 'POST', headers={'User-Agent': user_agent})
# if verification is successful, the discogs oauth API will return an access token
# and access token secret. This is the final authentication phase. You should persist
# the oauth_token and the oauth_token_secret to disk, database or some
# other local store. All further requests to the discogs.com API that require authentication
# and must be made with these access_tokens.
access_token = dict(urlparse.parse_qsl(content))
print ' == Access Token =='
print ' * oauth_token = {0}'.format(access_token['oauth_token'])
print ' * oauth_token_secret = {0}'.format(access_token['oauth_token_secret'])
print ' Authentication complete. Future requests must be signed with the above tokens.'
print
# We're now able to fetch an image using the application consumer key and secret,
# along with the verified oauth token and oauth token for this user.
headers = {'User-Agent': user_agent, 'Content-Type': CONTENT_TYPE}
token = oauth.Token(
key=access_token['oauth_token'],
secret=access_token['oauth_token_secret']
)
client = oauth.Client(consumer, token)
resp, content = client.request(make_api_url('/oauth/identity'), headers=headers)
print ' == Authenticated identity request =='
print ' * response status = {0}'.format(resp['status'])
print ' * content:\n\n{}'.format(content)
print ''
print '''
== Console Instructions ==
To make a request you can use the form:
path = '/users/test'
data = {'key': 'value'}
resp, content = client.request(
make_api_url(path), headers=headers, method="POST", body=make_body(data)
)
Have fun!
'''
@jcrosen
Copy link
Author

jcrosen commented Jun 20, 2014

Save the gist locally somewhere and then load it up in an interactive interpreter:

python -i <path_to_file>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment