hn-api is a simple, ad-hoc Python API for Hacker News. I say "ad-hoc" because it is unofficial, unauthorised and works by screen-scraping and slicing-and-dicing HTML. I say "simple" because it's in its infancy.
The guts of hn-api were part of my hnsh project, but I decided to pull the API stuff out and make it its own project so that other people could use the pseudo-API I'd created.
If you get stories from HN too often, HN will ban your IP address. So be gentle -- remember, hn-api is an unofficial API.
There are four classes in hn-api:
HackerNewsAPI-- The main class for turning the source code from HN into Python objects.
HackerNewsStory-- The class representing a story on HN.
HackerNewsUser-- The class representing an HN user.
HNException-- An exception raised when things go wrong while trying to get info from HN.
getTopStories()-- Returns the 30 stories on the front page of HN as a list of
getNewestStories()-- Returns 30 stories most recently submitted to HN as a list of
getBestStories()-- Returns the 30 stories on the "best" page of HN as a list of
HackerNewsAPI objects have other methods, but they're internal and you don't need to deal with them to get stories from HN.
id-- The Hacker News ID of a story.
number-- What rank the story is on HN.
title-- The title of the story.
domain-- The website the story is from.
URL-- The full URL of the story.
score-- Current score of the story.
submitter-- The HN username of the person that submitted the story.
commentCount-- How many comments the story has.
commentsURL-- The HN link for discussing the story.
printDetails()-- Prints the attributes of the story.
karma-- The user's score on HN.
name-- The user's username.
userPageURL-- The URL of the user's 'user' page.
threadsPageURL-- The URL of the user's 'threads' page.
__init__(username)-- Constructs a user with a username.
refreshKarma()-- Updates the user's karma.
HNException is exactly the same as a plain Python Exception. The HNException class exists soley for identifying errors that come from trying to get data from HN.
Here's a really simple example of how to use hn-api:
from hnapi import hnapi hn = hnapi.HackerNewsAPI() stories = hn.getTopStories() for s in stories: s.printDetails()
To break this down:
from hnapi import hnapiimports the code you need from hnapi.py.
hn = hnapi.HackerNewsAPI()instantiates the API.
stories = hn.getTopStories()gets the 30 stories on the front page of HN and stores them in a list of HackerNewsStory objects.
for s in stories: s.printDetails()prints the details of every story on the front page of HN.
hn-api is released under the Simplified BSD License.
Copyright (c) 2010 Scott Jackson. All rights reserved.
I'd love to flesh hn-api out a little more. If you'd like to contribute to the project, feel free to do so!
###I hope that hn-api is of use to someone writing a Hacker News-related application. If you use hn-api in something you write, drop me a line -- I'd love to hear about it!