Skip to content

Instantly share code, notes, and snippets.

@joestump
Created September 3, 2012 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joestump/3613823 to your computer and use it in GitHub Desktop.
Save joestump/3613823 to your computer and use it in GitHub Desktop.
A simple JSON only Alchemy API client for Python using the requests library.
import requests
import urllib
class AlchemyAPI(object):
BASE_URL = 'https://access.alchemyapi.com'
def __init__(self, api_key):
self.api_key = api_key
def keywords(self, text):
results = self._call_endpoint('TextGetRankedKeywords', text)
return [{'relevance': float(k['relevance']), 'text': k['text']} for k in
results['keywords']]
def sentiment(self, text):
results = self._call_endpoint('TextGetTextSentiment', text)
return (float(results['docSentiment']['score']),
results['docSentiment']['type'])
def _call_endpoint(self, name, text):
endpoint = self._endpoint(name, text=text)
resp = requests.get(endpoint)
if resp.status_code != 200:
raise Exception('API returned %s' % resp.status_code)
if resp.json['status'] != 'OK':
raise Exception('API status was not OK (%s)' % resp.json['status'])
return resp.json
def _endpoint(self, name, **kwargs):
kwargs.update({
'apikey': self.api_key,
'outputMode': 'json',
})
return '%s/calls/text/%s?%s' % (self.BASE_URL, name, urllib.urlencode(kwargs))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment