You want to build a small news dashboard. Maybe for a portfolio, a side project, or a Slack bot that pings your team with the day's top stories. So you start searching — and every guide points you at a paid service that wants a credit card before you write a single line of code. That's frustrating.
This free news api tutorial fixes that. We'll use the Hacker News Algolia Search API — it's free, requires no API key, and returns clean JSON. By the end, you'll have a working script in both Python and JavaScript that pulls live headlines, handles errors, and prints them in a readable format.
I'll show you the basic version first, then the practical version with proper error handling. Both work the moment you paste them in. Let's get to it.
What Is the Hacker News API?
The Hacker News API (powered by Algolia) is a public search endpoint that returns articles, comments, and user data from Hacker News. It's run by Algolia and YC, and it's been stable for years.
Why use it? Because it's one of the few news headlines api example endpoints that needs zero authentication. No signup, no key, no rate limit forms to fill out. You hit the URL, you get JSON back. The response window covers the full Hacker News archive going back to 2006, so you can pull recent stories or older ones without restriction.
Why This API Is Great for a Free News API Tutorial
- No API key required — paste the URL, run the script, get data.
- Free with no usage limits published — there's no official rate limit, but space your requests with a small delay if you're looping.
- Clean JSON structure — predictable fields, easy to parse.
- Real, current data — headlines update in real time as new stories hit the front page.
- Beginner-friendly — one endpoint covers most use cases.
One honest caveat: results cap at 1000 hits per query (Algolia's hard limit), and per-page caps at 1000 with the hitsPerPage parameter. For a dashboard, you'll never hit that.
Step-by-Step Setup
You'll need:
- Python 3.8 or newer (for the Python examples)
- Node.js 18 or newer (for the JavaScript example)
- The
requestslibrary for Python
Install requests with pip:
pip install requests
That's it. No virtual env required for a quick test, but use one if you're building this into a bigger project.
Code Examples
Python Example: Basic Fetch
Here's the smallest possible script that pulls the latest front-page stories. Copy, paste, run.
import requests
# Algolia HN endpoint — no API key needed
url = "https://hn.algolia.com/api/v1/search?tags=front_page"
response = requests.get(url)
data = response.json()
# 'hits' is the array of stories
for story in data["hits"][:5]:
print(story["title"])
print(story["url"])
print("---")
Run it and you'll see five front-page Hacker News stories printed with their links. That's a working top headlines api free call in 10 lines.
Python Example: Dashboard Script with Error Handling
The basic version works, but it'll crash the moment the network hiccups or the API returns something unexpected. Here's the version you'd actually use in production.
import requests
from datetime import datetime
BASE_URL = "https://hn.algolia.com/api/v1/search"
def fetch_headlines(tag="front_page", limit=10):
"""Fetch top headlines from Hacker News.
Note: Algolia caps hitsPerPage at 1000.
There's no published rate limit, but be polite.
"""
params = {
"tags": tag,
"hitsPerPage": limit
}
try:
response = requests.get(BASE_URL, params=params, timeout=10)
response.raise_for_status() # raises on 4xx/5xx
data = response.json()
except requests.exceptions.Timeout:
print("Request timed out. Try again in a moment.")
return []
except requests.exceptions.HTTPError as err:
print(f"HTTP error: {err}")
return []
except requests.exceptions.RequestException as err:
print(f"Network error: {err}")
return []
hits = data.get("hits", [])
if not hits:
print("No stories found. Check the tag value.")
return []
return hits
def print_dashboard(stories):
print(f"\n=== Top Headlines — {datetime.now().strftime('%Y-%m-%d %H:%M')} ===\n")
for i, story in enumerate(stories, start=1):
title = story.get("title") or story.get("story_title") or "(no title)"
url = story.get("url") or "(no link)"
points = story.get("points", 0)
author = story.get("author", "unknown")
print(f"{i}. {title}")
print(f" by {author} | {points} points")
print(f" {url}\n")
if __name__ == "__main__":
stories = fetch_headlines(limit=5)
print_dashboard(stories)
This version checks for timeouts, HTTP errors, and missing fields. The story.get("title") or story.get("story_title") bit handles a quirk — some HN entries are comments and use story_title instead of title. The docs don't make this obvious, but skipping that check causes empty rows in your dashboard.
Sample Python Output
=== Top Headlines — 2026-05-10 11:30 ===
1. Show HN: I built a tiny static site generator in 200 lines of Go
by gopher_dev | 412 points
https://github.com/example/tinygen
2. The hidden cost of microservices nobody talks about
by sre_2025 | 287 points
https://blog.example.com/microservices-cost
3. Postgres 17 is faster than you think
by db_nerd | 245 points
https://www.postgresql.org/about/news/
4. Why we moved off Kubernetes after 3 years
by infra_lead | 198 points
https://engineering.example.io/post-k8s
5. A practical guide to writing better commit messages
by git_guru | 156 points
https://example.dev/commits
JavaScript Example: Fetch Headlines with Error Handling
Same idea, in JavaScript. Use this if you want to build news dashboard javascript style — say, a Node script feeding a frontend, or a serverless function on Vercel.
// Node.js 18+ or any modern browser
const BASE_URL = "https://hn.algolia.com/api/v1/search";
async function fetchHeadlines(tag = "front_page", limit = 10) {
// hitsPerPage caps at 1000 on Algolia's side
const url = `${BASE_URL}?tags=${encodeURIComponent(tag)}&hitsPerPage=${limit}`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Request failed — HTTP ${response.status}`);
}
const data = await response.json();
const hits = data.hits ?? [];
if (hits.length === 0) {
console.log("No stories returned. Check the tag value.");
return;
}
console.log(`\n=== Top Headlines — ${new Date().toISOString().slice(0, 16)} ===\n`);
hits.forEach((story, i) => {
// Some entries are comments and use story_title
const title = story.title ?? story.story_title ?? "(no title)";
const link = story.url ?? "(no link)";
const points = story.points ?? 0;
const author = story.author ?? "unknown";
console.log(`${i + 1}. ${title}`);
console.log(` by ${author} | ${points} points`);
console.log(` ${link}\n`);
});
} catch (error) {
console.error("Fetch failed:", error.message);
}
}
fetchHeadlines("front_page", 5);
Sample JavaScript Console Output
=== Top Headlines — 2026-05-10T11:30 ===
1. Show HN: I built a tiny static site generator in 200 lines of Go
by gopher_dev | 412 points
https://github.com/example/tinygen
2. The hidden cost of microservices nobody talks about
by sre_2025 | 287 points
https://blog.example.com/microservices-cost
3. Postgres 17 is faster than you think
by db_nerd | 245 points
https://www.postgresql.org/about/news/
4. Why we moved off Kubernetes after 3 years
by infra_lead | 198 points
https://engineering.example.io/post-k8s
5. A practical guide to writing better commit messages
by git_guru | 156 points
https://example.dev/commits
Understanding the Output
The API returns a JSON object with a hits array. Each hit is a story. Here's what the fields mean:
title— the headline. Sometimes null if the entry is a comment, in which case usestory_title.url— the external link. Null for self-posts (Show HN, Ask HN).author— the username who submitted the story.points— upvote count at the time of the API call.num_comments— comment count.created_at— ISO 8601 timestamp like2026-05-10T09:15:00.000Z.objectID— the unique HN story ID. You can build a link to the comments page withhttps://news.ycombinator.com/item?id={objectID}.
The top-level nbHits tells you how many results matched your query, and nbPages tells you how many pages you can paginate through.
Error Handling
Three errors trip beginners up most often. Here's what they mean and how to handle them.
1. Timeouts. The API is fast, but networks get flaky. Always pass timeout=10 to requests.get(). Without it, your script can hang forever.
2. Empty hits array. If you query a tag that doesn't exist (like tag="top_news" instead of front_page), the API returns 200 OK with an empty hits list. No error. Most confusing failure mode for beginners. Always check if not hits before iterating.
3. Missing title field. When you query for comments or replies, the title field is null. Use .get() with a fallback in Python, or the ?? operator in JS. The pattern in the dashboard script handles this.
About rate limits: there's no published limit for the HN Algolia API. If you're hammering it in a loop, add time.sleep(1) between calls to avoid temporary blocks. Be a good API citizen.
Real-World Use Cases
Personal news aggregator tutorial project. Build a CLI that prints the top 10 HN stories every morning. Pipe it through cron and email yourself the digest. Took me an afternoon the first time.
Slack or Discord bot. Post the top three stories to a #tech-news channel every hour. Useful for engineering teams who want signal without doomscrolling.
Portfolio dashboard. Pair the JavaScript fetch code with a simple React or Svelte frontend. You get a clean grid of cards, live data, and something real to show on GitHub.
Content site sidebar. Pull trending tech headlines into your blog's sidebar. Fresh content, zero maintenance.
Comparison with Other Free News APIs
| API | Auth Required | Free Tier Limit | Coverage |
|---|---|---|---|
| Hacker News (Algolia) | None | No published limit, 1000 hits per query max | Tech news, since 2006 |
| NewsAPI.org | API key | 100 requests/day on free tier | General news, last 30 days on free |
| GNews | API key | 100 requests/day on free tier | General news, multi-language |
| Reddit JSON | None for read | 60 requests/minute | Subreddit posts, all topics |
FAQ
Do I need an API key for the Hacker News API?
No. The Algolia HN endpoint is fully open. You can hit it from a browser, curl, or any HTTP client without a token. That's why it's the best starter for a free news api tutorial.
Can I filter headlines by topic or category?
Yes, with the tags parameter. Use values like story, front_page, show_hn, or ask_hn. You can also combine tags with the query parameter to search by keyword — for example ?query=python&tags=story.
What's the difference between this and NewsAPI.org?
NewsAPI.org covers mainstream outlets like BBC and Reuters but requires a key and limits free usage to 100 requests per day. The HN API is tech-focused and has no key requirement. Different jobs, different tools.
How do I sort headlines by date instead of relevance?
Use the /search_by_date endpoint instead of /search. Same parameters, but results come back sorted newest-first. Good for a live ticker.
How can I build a news dashboard in JavaScript with this API?
Use the JavaScript example above as your data layer, then wire the returned array into your frontend framework of choice. React, Vue, Svelte — they all consume JSON the same way. Render each story as a card and you've got a working dashboard.
Is this API reliable enough for production?
For low-volume, non-critical use — yes. It's been stable for years. For mission-critical apps, cache the responses and have a fallback. Don't depend on any free service for revenue-generating uptime.
Conclusion
You now have a working headlines dashboard in two languages. The Python script is great for cron jobs and CLI tools. The JavaScript version drops straight into a Node backend or a frontend project.
The next step is to extend it. Add filtering by keyword, paginate through more results with the page parameter, or wire the output into a frontend grid. Once you've got the data flowing, the rest is just UI.
Looking for more free APIs to play with? Browse the Free API Hub directory and find your next project.










