Skip to content


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

207 lines (173 sloc) 5.512 kb
The transparencydata module provides API wrappers for the data found on
__author__ = "Jeremy Carbaugh ("
__version__ = "0.1"
__copyright__ = "Copyright (c) 2010 Sunlight Labs"
__license__ = "BSD"
import sys
if sys.version_info[0] == 3:
from urllib.parse import urlencode, urljoin
from urllib.request import urlopen
from urllib.error import HTTPError
from urllib import urlencode
from urlparse import urljoin
from urllib2 import HTTPError, urlopen
import json
except ImportError:
import simplejson as json
DEFAULT_PARAMETERS = ('apikey','page','per_page')
class TransparencyDataError(Exception):
# base client
class Client(object):
def __init__(self, key, base_url=DEFAULT_URL):
self.apikey = key
self.apiurl = base_url
self.debug = False
def __call__(self, **kwargs):
kwargs['apikey'] = self.apikey
params = {}
handlers = {}
if hasattr(self, 'handlers'):
for param, value in kwargs.iteritems():
(name, operator) = param.split('__') if '__' in param else (param, None)
if name not in self.parameters and name not in DEFAULT_PARAMETERS:
raise TransparencyDataError('%s is not a valid parameter' % param)
if operator == 'in':
if isinstance(value, (list, tuple)):
value = "|".join(str(v) for v in value)
operator = None
elif operator == 'gt':
value = ">|%s" % value
elif operator == 'lt':
value = "<|%s" % value
elif operator == 'between':
if not isinstance(value, (list, tuple)):
raise TransparencyDataError('%s__%s must be a tuple or list' % (name, operator))
start = value[0].strftime("%Y-%m-%d")
end = value[1].strftime("%Y-%m-%d")
value = "><|%s|%s" % (start, end)
handler = handlers.get(name, None)
if handler:
value = handler(name, value, operator)
params[name] = value.encode('utf8')
url = "%s?%s" % (urljoin(self.apiurl, self.endpoint), urlencode(params))
if self.debug:
print url
response = urlopen(url).read().decode()
return json.loads(response)
except HTTPError, e:
raise TransparencyDataError(
except (ValueError, KeyError), e:
raise TransparencyDataError('Invalid Response')
# base types
class ContributionsClient(Client):
endpoint = 'contributions.json'
parameters = (
class LobbyingClient(Client):
endpoint = 'lobbying.json'
parameters = (
class EarmarkClient(Client):
endpoint = 'earmarks.json'
parameters = (
class GrantsClient(Client):
endpoint = 'grants.json'
parameters = (
class ContractsClient(Client):
endpoint = 'contracts.json'
parameters = (
# main wrapper
class TransparencyData(object):
def __init__(self, key):
self.contributions = ContributionsClient(key)
self.lobbying = LobbyingClient(key)
self.earmarks = EarmarkClient(key)
self.grants = GrantsClient(key)
self.contracts = ContractsClient(key)
Jump to Line
Something went wrong with that request. Please try again.