Created
January 3, 2014 04:26
-
-
Save sampsyo/8232717 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import requests | |
import json | |
BASE_URL = 'http://www.comicvine.com/api' | |
API_KEY = 'c7f4481e0a6154b8ac39580747ca8c91c3d4a321' | |
def dump(jo): | |
print(json.dumps(jo, indent=2, sort_keys=True)) | |
class ComicVine(object): | |
def __init__(self, api_key=API_KEY, base_url=BASE_URL): | |
"""Initialize the API access. Optionally supply an API key and a | |
URL for the endpoints. | |
""" | |
self.api_key = api_key | |
self.base_url = base_url | |
# Load the type IDs. These are necessary for lookups by ID, | |
# frustratingly. We could consider hard-coding these if we're | |
# confident they'll never change. | |
self.type_ids = {} | |
self.type_plurals = {} | |
for typ in self.get('types'): | |
name = typ['detail_resource_name'] | |
self.type_ids[name] = typ['id'] | |
self.type_plurals[name] = typ['list_resource_name'] | |
def get(self, path): | |
"""Perform a web service request for the given path and return | |
the results from the JSON response. | |
""" | |
if path.startswith('/'): | |
path = path[1:] | |
if path.endswith('/'): | |
path = path[:-1] | |
url = '{}/{}/'.format(self.base_url, path) | |
req = requests.get(url, params={ | |
'api_key': self.api_key, | |
'format': 'json', | |
}) | |
res = req.json() | |
# TODO check for errors, etc. | |
return res['results'] | |
def by_id(self, entity, id): | |
"""Get a single entity by its id. | |
""" | |
if entity not in self.type_ids: | |
raise ValueError('unknown entity type: {}'.format(entity)) | |
return self.get('{}/{}-{}'.format( | |
entity, | |
self.type_ids[entity], | |
id, | |
)) | |
def main(): | |
api = ComicVine() | |
vol = api.by_id('volume', 46568) | |
print(vol['name']) | |
print(vol['publisher']['name']) | |
print(vol['image']['medium_url']) | |
for issue in vol['issues']: | |
num = int(issue['issue_number']) | |
name = issue['name'] | |
print('{}: {}'.format(num, name)) | |
detail = api.by_id('issue', issue['id']) | |
print(detail['image']['medium_url']) | |
print('released: {}'.format(detail['store_date'])) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment