Table of Contents
- Choosing The Right Hacker News API For Your Project
- Hacker News API Versions Compared
- Accessing Real-Time Data with Firebase API Endpoints
- Fetching Story IDs
- Retrieving Item Details
- Mastering Search and Filter Parameters
- Advanced Query Examples in Python
- Practical Code for Common Use Cases
- Fetching and Displaying the Top 10 Stories
- Creating a Keyword-Based Daily Digest
- Managing Rate Limits and Pagination
- Navigating Firebase API Limitations
- Paginating Results with Algolia
- Optimizing Performance with Caching and Error Handling
- Implementing Caching Strategies
- Graceful Error Handling
- A Few Common Questions (The Hacker News API FAQ)
- Are There Any Rate Limits?
- Can I Post Stories or Comments with the API?
- Which API Should I Use? Real-Time vs. Historical

Do not index
Do not index
To pull data from Hacker News, you have a critical decision. There isn't just one Hacker News API; there are two primary options, and they serve completely different purposes.
Picking the wrong one is a common mistake that can derail a project. One API provides a live, real-time firehose of data, while the other is designed for searching through historical archives. Your choice depends entirely on what you intend to build.
Choosing The Right Hacker News API For Your Project
Your first step is to determine if your project requires live data or historical search capabilities. There is no single "best" API—it’s about matching the right tool to the job.
The official Hacker News API, built on Firebase, is focused on what's happening right now. It gives you a direct, up-to-the-second view of top stories, new posts, and user activity as it appears on the site. If you're building a real-time dashboard or a "newest comments" feed, this is the correct choice. Its major limitation is the complete lack of a built-in search function.
The alternative is the community-maintained Algolia HN Search API. This is your time machine. It’s built for exploring the entire history of Hacker News. You can execute complex queries, filter by date ranges, sort by popularity, and find nearly anything ever posted. It is ideal for data analysis, trend identification, or building a search feature for past content.
Hacker News API Versions Compared
To simplify the decision, focus on your primary goal: are you building a live news ticker or a research tool?

The decision tree above clarifies the choice: for live updates, use the official Firebase API. For searching, filtering, or analyzing historical data, Algolia is the correct tool.
This table provides a head-to-head comparison of their core features to help you choose the right one for your specific needs.
Feature | Official (Firebase) API | Algolia Search API |
Primary Use Case | Real-time data access | Historical search & filtering |
Data Scope | Live data, latest items | Full history of HN content |
Search Capability | None | Full-text search, complex filters |
Real-Time Updates | Yes, via web sockets | No, indexed periodically |
Data Structure | Item IDs, user profiles | Searchable JSON objects |
Common Projects | Live news feeds, comment trackers | Data analysis, trend research |
This distinction is fundamental. Attempting to build a historical search application with the Firebase API will lead to failure, just as you cannot obtain real-time comment streams from Algolia. Choose correctly at the project's outset.
Once you start pulling this data, you might want to analyze it with a Large Language Model. For cost estimations, refer to our comparison of LLM pricing.
Accessing Real-Time Data with Firebase API Endpoints
The official Hacker News API on Firebase is the standard for obtaining a live feed of site activity. It is the correct API for accessing stories, comments, and user activity as it happens. The API is open, free, and does not require authentication keys, simplifying initial setup.
All requests start from the base URL:
https://hacker-news.firebaseio.com. You append specific endpoint paths to retrieve the desired data. To streamline your setup, a Firebase Mcp tool can simplify the management of these endpoints.
This structure enables the development of applications that mirror the live state of Hacker News with minimal overhead.
Fetching Story IDs
Most applications begin by fetching a list of story IDs. The Firebase API offers several endpoints for this, each returning a JSON array of up to 500 unique item IDs.
- /v0/topstories.json: The current top stories on the front page.
- /v0/newstories.json: The firehose of the most recently submitted stories.
- /v0/beststories.json: A curated list of stories algorithmically deemed "best."
Retrieving these IDs is straightforward using
curl or JavaScript's fetch API.Curl Example
curl 'https://hacker-news.firebaseio.com/v0/topstories.json'JavaScript Example
fetch('https://hacker-news.firebaseio.com/v0/topstories.json')
.then(response => response.json())
.then(data => console.log(data.slice(0, 10))); // Logs the first 10 top story IDsOnce you have an array of IDs, the next step is to retrieve the details for each item.
Retrieving Item Details
To get the data for a story, comment, or user profile, use the
/v0/item/<id>.json endpoint, substituting <id> with the desired item ID.The
kids array is essential for building threaded comments, requiring recursive calls to the same item endpoint for each comment ID to map out a conversation. This "chaining" of requests is a fundamental pattern for using the Hacker News API effectively.While the Firebase API is excellent for real-time data, its lack of search functionality is a deal-breaker for many projects. This is where the community-maintained Algolia HN Search API provides a critical, alternative method for accessing Hacker News data.
It functions as a searchable archive of nearly every story and comment ever posted. If your project involves historical data analysis, trend tracking, or content discovery features, this is your tool. Instead of only seeing what's popular now, you can query the entire history of Hacker News. Its main endpoint is purpose-built for search and filtering.

The ability to query historical data enables powerful projects. For example, Andrej Karpathy used the Algolia API to pull front-page discussions from a specific month and fed them into an LLM to identify the most prescient comments. This type of retrospective analysis is impossible with the real-time API alone.
Mastering Search and Filter Parameters
The Algolia API's power lies in its query parameters. You can make highly specific requests by appending parameters to the base URL:
http://hn.algolia.com/api/v1/search.These parameters allow for precise slicing of results. The most common are:
- query: The keyword or phrase to search for (e.g.,
query=AI).
- tags: Filter by item type, such as
story,comment, orask_hn.
- numericFilters: Apply filters based on numerical values like score or creation date (e.g.,
points>100orcreated_at_i > [timestamp]).
This granular control distinguishes the Algolia Hacker News API. The original Firebase API, released around 2014, was revolutionary for real-time access but was never designed for this level of data exploration. Its endpoints provide IDs for the top 500 stories and let you monitor comment counts, but they cannot identify trends like the rise of AI agent discussions—a relevant topic for developers using platforms like Agent 37's OpenClaw hosting. For more detail on the official API's design and limitations, see its official documentation on GitHub.
Advanced Query Examples in Python
Here is a Python script demonstrating these parameters. The code uses the
requests library to find popular stories about 'AI' posted in the last month with more than 50 points.import requests
import time
# Calculate the timestamp for 30 days ago
thirty_days_ago = int(time.time()) - (30 * 24 * 60 * 60)
# Define the API endpoint and parameters
url = "http://hn.algolia.com/api/v1/search"
params = {
"query": "AI",
"tags": "story",
"numericFilters": f"created_at_i>{thirty_days_ago},points>50"
}
# Make the request
response = requests.get(url, params=params)
data = response.json()
# Print the titles of the top hits
for hit in data.get("hits", []):
print(f"- {hit.get('title')}")Practical Code for Common Use Cases
Knowing the endpoints is different from implementing them effectively. Here is practical, ready-to-use code for common tasks using the Hacker News API.
These examples are designed to quickly advance you from concept to a working prototype. We will fetch top stories and then build a custom digest based on a keyword, using either the Firebase or Algolia API as appropriate.
Fetching and Displaying the Top 10 Stories
A common requirement is displaying the current top stories. For any HN client, this is a core feature.
Using the official Firebase API, this is a two-step process: first, get the list of top story IDs. Second, iterate through those IDs to fetch the details for each story.
This JavaScript snippet implements this efficiently, fetching only what is necessary.
// Function to fetch details for a single item
async function getItemDetails(id) {
const response = await fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json`);
return response.json();
}
// Main function to get the top 10 stories
async function getTopTenStories() {
try {
// 1. Fetch the list of top story IDs
const response = await fetch('https://hacker-news.firebaseio.com/v0/topstories.json');
const topStoryIds = await response.json();
// 2. Get the first 10 IDs and fetch their details concurrently
const topTenIds = topStoryIds.slice(0, 10);
const storyPromises = topTenIds.map(id => getItemDetails(id));
const stories = await Promise.all(storyPromises);
// 3. Display the titles and scores
console.log("Hacker News Top 10 Stories:");
stories.forEach(story => {
if (story) {
console.log(`- ${story.title} (Score: ${story.score})`);
}
});
} catch (error) {
console.error("Failed to fetch stories:", error);
}
}
getTopTenStories();This approach is suitable for building real-time news readers or website widgets. For similar asynchronous patterns with embedded content, our guide on the YouTube IFrame API may offer useful insights.
Creating a Keyword-Based Daily Digest
Suppose you need a daily summary of new stories that mention "Python." The Firebase API is unsuitable for this task due to its lack of a search function.
This requires the Algolia Hacker News API. It is designed for powerful filtering by keyword, date, and other criteria.
import requests
import time
# Calculate the timestamp for 24 hours ago
one_day_ago = int(time.time()) - (24 * 60 * 60)
# Define Algolia API endpoint and parameters
URL = "http://hn.algolia.com/api/v1/search"
PARAMS = {
"query": "Python",
"tags": "story",
"numericFilters": f"created_at_i>{one_day_ago},points>5"
}
# Make the API request
try:
response = requests.get(URL, params=PARAMS)
response.raise_for_status() # Raise an exception for bad status codes
data = response.json()
print("New stories about 'Python' in the last 24 hours:")
for hit in data.get("hits", []):
print(f"- {hit.get('title')} (URL: {hit.get('url')})")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")By combining
query and numericFilters, you can create highly specific feeds for any topic, author, or popularity threshold, demonstrating the power of a dedicated search API.Managing Rate Limits and Pagination
When using an API at scale, you will encounter its limits. The Firebase and Algolia versions of the Hacker News API handle large data volumes and frequent requests differently. Understanding both is necessary to build a robust application.
Both APIs are generous and do not have strict, documented rate limits for read-only access. However, this is not an invitation for unthrottled requests. Hammering the servers can result in a temporary block. Implementing sensible client-side behavior is good practice. It's also wise to review API authentication best practices for general security, even when a key is not required.

Navigating Firebase API Limitations
The official Firebase API lacks traditional pagination. A request for the top 500 story IDs returns all 500 at once; you cannot request "page 2."
This design necessitates a specific strategy for handling large lists. Requesting details for all 500 items simultaneously can overwhelm both the API and your client. The correct approach is to process the list of IDs in small, manageable batches.
- Batch Your Requests: Fetch the full list of IDs, then loop through it, fetching details for 10-20 items at a time.
- Introduce Delays: Implement a small delay between batches to avoid overwhelming the server.
- Prioritize Necessary Data: For features like an infinite scroll feed, fetch the next batch only when the user approaches the end of the current content.
Paginating Results with Algolia
The Algolia Hacker News API is more direct. As it was designed for search, it includes proper pagination managed by standard parameters.
To navigate results, use two primary parameters:
page: Specifies the desired page of results (e.g.,page=0for the first page).
hitsPerPage: Defines the number of results per page, up to a maximum of 1,000.
This simplifies working with thousands of search results. Simply increment the
page parameter in a loop until all necessary data is retrieved or the API returns an empty hits array.Optimizing Performance with Caching and Error Handling
An application that makes unplanned API calls will be slow and unreliable. To build a professional-grade application using the Hacker News API, you must implement caching and robust error handling.
Caching is the most effective tool for improving application speed. Story details and user profiles do not change every second; fetching the same data repeatedly is wasteful. A well-implemented caching layer significantly improves performance.
Implementing Caching Strategies
The simplest method is a server-side cache. An in-memory store like Redis is effective for this. The logic is: upon receiving a request, first check Redis. If the data exists, serve it instantly. If not, call the API, store the response in the cache with an expiration time (TTL), and then return it to the user.
Graceful Error Handling
API calls will fail due to network issues, invalid item IDs, or transient API problems. Your application must anticipate and handle these issues gracefully instead of crashing.
A common issue with the Firebase API is its return of
null for deleted or non-existent items. Your code must explicitly check for this.# Python example for handling null responses
import requests
def get_item(item_id):
url = f"https://hacker-news.firebaseio.com/v0/item/{item_id}.json"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
if data is None:
print(f"Warning: Item {item_id} not found or has been deleted.")
return None
return data
else:
print(f"Error: API returned status {response.status_code}")
return None
# Test with a potentially invalid ID
item = get_item(999999999)
if item:
print(item['title'])For temporary network failures, implement a retry strategy with exponential backoff. If a request fails, wait one second before retrying. If it fails again, wait two seconds, then four, and so on. This prevents overwhelming the API during a brief outage. This robust logic is a fundamental skill, applicable whether you are using the HN API or maintaining a custom Slack chat bot.
A Few Common Questions (The Hacker News API FAQ)
Here are answers to some of the most frequently asked questions.
Are There Any Rate Limits?
Officially, no. Neither the Firebase nor the Algolia API specifies a hard rate limit for read-only access.
However, excessive requests will result in a temporary block. The best practice is to cache responses aggressively and implement backoff logic in your client code from the start.
Can I Post Stories or Comments with the API?
No. The Hacker News API is strictly read-only. Programmatic posting of stories, comments, or upvotes is not supported. All write actions must be performed manually through the official Hacker News website.
Which API Should I Use? Real-Time vs. Historical
The choice depends entirely on your use case.
- For real-time data, such as current top stories or new comments, use the official Firebase API. It is designed for live updates.
- For historical data, use the Algolia API. It is built for searching, filtering by date, and analyzing trends over time.
Ready to turn all this Hacker News data into your own AI agent or Claude skill? Agent 37 gives you managed OpenClaw hosting that gets you up and running in 30 seconds. Stop messing with servers and start building. Check out our one-click solution at https://www.agent37.com/.