I'll help you create a script to fetch top posts from HackerNews using their API. Here's a Python solution that gets the top posts sorted by votes:
import requests
from concurrent.futures import ThreadPoolExecutor
from typing import List, Dict
import time
def get_top_stories() -> List[int]:
"""Fetch IDs of top stories from HackerNews"""
url = "https://hacker-news.firebaseio.com/v0/topstories.json"
response = requests.get(url)
return response.json()
def get_story_details(story_id: int) -> Dict:
"""Fetch details of a specific story"""
url = f"https://hacker-news.firebaseio.com/v0/item/{story_id}.json"
response = requests.get(url)
return response.json()
def get_top_posts(limit: int = 20) -> List[Dict]:
# Get list of top story IDs
story_ids = get_top_stories()
# Fetch details for each story in parallel
with ThreadPoolExecutor(max_workers=10) as executor:
stories = list(executor.map(get_story_details, story_ids))
# Filter out None values and sort by score
valid_stories = [s for s in stories if s and 'score' in s]
sorted_stories = sorted(valid_stories, key=lambda x: x['score'], reverse=True)
# Return the top N stories
return sorted_stories[:limit]
def format_story(story: Dict) -> str:
"""Format story details for display"""
return (f"Title: {story.get('title')}\n"
f"Score: {story.get('score')}\n"
f"URL: {story.get('url', 'N/A')}\n"
f"Comments: https://news.ycombinator.com/item?id={story.get('id')}\n")
def main():
limit = 20 # Configurable number of posts
top_posts = get_top_posts(limit)
print(f"\nTop {limit} HackerNews posts by votes:\n")
for i, story in enumerate(top_posts, 1):
print(f"\n#{i}")
print(format_story(story))
if __name__ == "__main__":
main()
This script:
- Uses the official HackerNews API
- Gets the top stories IDs
- Fetches details for each story in parallel using ThreadPoolExecutor
- Sorts them by score (votes)
- Returns the top N posts (configurable via the
limit parameter)
To use this script, you'll need to install the requests library:
pip install requests
The output will show:
- Title of the post
- Score (number of votes)
- URL to the original content
- Link to the HackerNews comments
You can modify the limit variable in the main() function to get a different number of posts.
If you want to use this as part of a larger application, you can import and use the get_top_posts() function directly, which returns a list of dictionaries containing all story details.
Would you like me to explain any part of the code in more detail or help you modify it for specific needs?