Skip to content

Instantly share code, notes, and snippets.

@manojkarthick
Last active May 13, 2017 17:49
Show Gist options
  • Select an option

  • Save manojkarthick/c819795440d866e874d6c8f27ba10472 to your computer and use it in GitHub Desktop.

Select an option

Save manojkarthick/c819795440d866e874d6c8f27ba10472 to your computer and use it in GitHub Desktop.
Get Story/Post information from the Hacker News API
import requests
def get_response(story_type):
url = 'https://hacker-news.firebaseio.com/v0/' + story_type + 'stories.json'
response = requests.get(url)
story_id_data = response.json()
return story_id_data
def get_story_ids(stories, size):
story_ids_reqd = list()
for i in range(0, size):
story_ids_reqd.append(stories[i])
return story_ids_reqd
def get_story_data(story_ids):
stories = dict()
for story_id in story_ids:
url = 'https://hacker-news.firebaseio.com/v0/item/' + str(story_id) + '.json'
story_response = requests.get(url)
story_data = story_response.json()
story_by = get_field_data(story_data,'by')
story_title = get_field_data(story_data,'title')
story_url = get_field_data(story_data,'url')
story_score = get_field_data(story_data,'score')
story_data_values = '{};{};{};{}'.format(story_by,story_title,story_url,story_score)
stories[story_id] = story_data_values
return stories
def get_field_data(story_data, field):
if field not in story_data:
response = ''
else:
response = story_data[field]
return response
stories_all = get_response(type)
stories_reqd = get_story_ids(stories_all,size=5)
stories_data = get_story_data(stories_reqd)
print(stories_data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment