You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

39 lines
1005 B
Python

1 year ago
#!/usr/bin/env python3
import requests
from dataclasses import dataclass
@dataclass
class Story:
id: int
title: str
link: str
author: str
votes: int
comments: int
def get_topstories():
# Query Hacker News API for top stories and their titles/links
# returns the top 500 stories, so quite enough.
url = 'https://hacker-news.firebaseio.com/v0/topstories.json'
r = requests.get(url)
if not r.ok:
raise Exception('Error fetching data from Hacker News API')
return r.json()
def get_story(story_id):
story_url = f'https://hacker-news.firebaseio.com/v0/item/{story_id}.json'
s = requests.get(story_url).json()
return Story(s['id'],
s['title'],
s['url'] if 'url' in s else 'No URL',
s['by'],
s['score'],
len(s['kids']) if 'kids' in s else 0)
def main():
ts = get_topstories()
s = get_story(ts[0])
print(s)
if __name__ == '__main__':
main()