FreeAPIHub
HomeAPIsAI ModelsAI ToolsBlog
Favorites
FreeAPIHub

The central hub for discovering, testing, and integrating the world's best AI models and APIs.

Platform

  • Categories
  • AI Models
  • APIs

Company

  • About Us
  • Contact
  • FAQ

Help

  • Terms of Service
  • Privacy Policy
  • Cookies

© 2026 FreeAPIHub. All rights reserved.

GitHubTwitterLinkedIn

Table of Contents

  1. 1What Is the Hacker News API?
  2. 2Why This API Is Great for a Free News API Tutorial
  3. 3Step-by-Step Setup
  4. 4Code Examples
  5. 5Python Example: Basic Fetch
  6. 6Python Example: Dashboard Script with Error Handling
  7. 7Sample Python Output
  8. 8JavaScript Example: Fetch Headlines with Error Handling
  9. 9Sample JavaScript Console Output
  10. 10Understanding the Output
  11. 11Error Handling
  12. 12Real-World Use Cases
  13. 13Comparison with Other Free News APIs
  14. 14FAQ
  15. 15Do I need an API key for the Hacker News API?
  16. 16Can I filter headlines by topic or category?
  17. 17What's the difference between this and NewsAPI.org?
  18. 18How do I sort headlines by date instead of relevance?
  19. 19How can I build a news dashboard in JavaScript with this API?
  20. 20Is this API reliable enough for production?
  21. 21Conclusion

Table of Contents

21 sections

  1. 1What Is the Hacker News API?
  2. 2Why This API Is Great for a Free News API Tutorial
  3. 3Step-by-Step Setup
  4. 4Code Examples
  5. 5Python Example: Basic Fetch
  6. 6Python Example: Dashboard Script with Error Handling
  7. 7Sample Python Output
  8. 8JavaScript Example: Fetch Headlines with Error Handling
  9. 9Sample JavaScript Console Output
  10. 10Understanding the Output
  11. 11Error Handling
  12. 12Real-World Use Cases
  13. 13Comparison with Other Free News APIs
  14. 14FAQ
  15. 15Do I need an API key for the Hacker News API?
  16. 16Can I filter headlines by topic or category?
  17. 17What's the difference between this and NewsAPI.org?
  18. 18How do I sort headlines by date instead of relevance?
  19. 19How can I build a news dashboard in JavaScript with this API?
  20. 20Is this API reliable enough for production?
  21. 21Conclusion

Trending

1

Flask vs Django vs FastAPI: Choosing the Best Python Web Framework

7 min705
2

Top 7 Free AI Tools for Academic Research and Paper Discovery

7 min529
3

Master API Testing with Postman: A Complete Beginner’s Guide

12 min509
4

Top AI Video Editing Tools Compared for Faster Content Creation

8 min480
5

Top AI Coding Tools to Revolutionize Development in 2026

9 min459

More in API Development

Build a Country Info Explorer Using the Countries Now API

11 min read

How to Fetch Currency Exchange Rates with a Free API (Python Tutorial)

11 min read

Build a Random Quotes Generator App Using a Free Quotes API

11 min read

How to Use a Free Weather API in Python for Beginners

10 min read

Understanding APIs: A Beginner's Guide to Testing APIs 2026

12 min read
All API Development posts
API Development
May 10, 20261 views

Free News API Tutorial: Build a Live Headlines Dashboard

A practical free news api tutorial showing how to fetch live headlines using the Hacker News Algolia API in Python and JavaScript. No API key needed. Includes error handling, sample output, and a working dashboard script.

Developer dashboard showing a list of news headlines fetched from a free news API in a terminal next to a code editor

Developer dashboard showing a list of news headlines fetched from a free news API in a terminal next to a code editor

FreeAPIHub

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 requests library 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 use story_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 like 2026-05-10T09:15:00.000Z.
  • objectID — the unique HN story ID. You can build a link to the comments page with https://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.

Tags

#free news api tutorial#build news dashboard javascript#news headlines api example#top headlines api free#news aggregator tutorial

Found this helpful?

Share this article with fellow developers or save it for later reference. Your support helps us create more quality content.

Suggested for You

All posts
Comparison of Flask, Django, and FastAPI Python web frameworks
705
7 minProgramming

Flask vs Django vs FastAPI: Choosing the Best Python Web Framework

Read
Illustration of AI tools aiding academic research and paper discovery with digital interface of scientific papers
529
7 minAcademic Research

Top 7 Free AI Tools for Academic Research and Paper Discovery

Read
API testing using Postman interface with sample API requests and responses
509
12 minAPI Development

Master API Testing with Postman: A Complete Beginner’s Guide

Read
Comparison of AI video editing tools showing interface features and video clips
480
8 minVideo Editing

Top AI Video Editing Tools Compared for Faster Content Creation

Read
AI coding tools enhancing software development workflow in 2026
459
9 minSoftware Development

Top AI Coding Tools to Revolutionize Development in 2026

Read

Continue Learning

More from API Development

Python country info explorer using the Countries Now API showing capital city and population data
API Development
May 10, 202611 min read

Build a Country Info Explorer Using the Countries Now API

Learn how to build a country info explorer in Python using the Countries Now API. This beginner-friendly tutorial covers fetching capitals, population data, and currency info — no API key required.

Read
Python code fetching live currency exchange rates using a free API
API Development
May 9, 202611 min read

How to Fetch Currency Exchange Rates with a Free API (Python Tutorial)

Learn how to fetch live currency exchange rates in Python using the free Frankfurter API. No API key required. Includes working code examples, error handling, real-world use cases, and a full FAQ.

Read
Random quotes generator app built with a free quotes API in Python and JavaScript
API Development
May 8, 202611 min read

Build a Random Quotes Generator App Using a Free Quotes API

Learn how to build a random quotes generator app in Python and JavaScript using a free quotes API. This beginner-friendly tutorial covers API calls, JSON parsing, error handling, and real-world use cases — no API key required.

Read
Python code on a screen fetching live weather data from a free API with no API key
API Development
May 8, 202610 min read

How to Use a Free Weather API in Python for Beginners

Learn how to fetch live weather data in Python using the Open-Meteo API — no API key, no signup, just clean working code. A practical beginner guide with real examples and error handling.

Read
Illustration of API communication between applications with code and data exchange
API Development
February 24, 202612 min read

Understanding APIs: A Beginner's Guide to Testing APIs 2026

New to APIs? This beginner-friendly 2026 guide explains what APIs are, how they work, and how to test them with real examples using Postman, Bruno, and curl. Covers HTTP methods, authentication, pagination, rate limits, and common status codes.

Read