Skip to content
NewsDataHub NewsDataHub Learning Center

What Is a News API and How Do You Use It with Python? Complete Beginner's Guide

We live in a time when information comes from every direction — headlines, newsletters, podcasts, social feeds, notifications. Most of us are drowning in content, but still struggling to find just the news we actually care about.

That’s where a News API comes in. With a News API, you can focus only on the sources, topics, and keywords that matter — filtering the noise and surfacing meaningful stories for you or your users.

In this guide, we’ll build a simple but delightful Python terminal app that fetches fresh tech headlines from the United States using the NewsDataHub API — complete with colors, emojis, and optional cron automation.


A News API gives you structured, programmatic access to real-world journalism. Instead of manually scraping RSS feeds or crawling websites, you can instantly query thousands of verified outlets with parameters like:

  • topic – filter by themes like technology, politics, economy, or sports
  • language – e.g. English, Spanish, Arabic
  • country – target regional coverage
  • source_type – choose mainstream media, blogs, or niche outlets

Modern APIs such as NewsDataHub index hundreds of thousands of articles daily — providing developers a reliable, structured, and filterable news pipeline for dashboards, research, and AI work.


Here are some ways you can use this API:

  • Train AI models or datasets — collect labeled data for summarization, classification, or sentiment tasks
  • Monitor company or sector news — track Tesla, SpaceX, Google, or Blue Origin in real time
  • Follow trends — observe how often certain topics (like “quantum computing”) appear over time
  • Track economy and crypto — gather stories from financial and economic sources
  • Discover related content — the /related endpoint can help surface contextually similar news

Before we dive in, make sure you have:

  • Python 3.8 or newer
  • An active NewsDataHub API key
  • The following packages installed:
Terminal window
pip install requests rich emoji

Below is the complete working example. It fetches the latest U.S. technology headlines, displays them beautifully in your terminal, and handles rate limits and API errors gracefully.

NewsDataHub News CLI App Demo

Full source code: https://github.com/newsdatahub/newsdatahub-news-cli-app

#!/usr/bin/env python3
import requests
import datetime
import random
import time
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn
from emoji import emojize
# ====== CONFIGURATION ======
PER_PAGE = 100 # change this once — used everywhere
API_KEY = "YOUR_API_KEY"
URL = "https://api.newsdatahub.com/v1/news"
PARAMS = {
"per_page": PER_PAGE,
"topic": "technology",
"language": "en",
"country": "US",
"source_type": "mainstream_news"
}
# ============================
console = Console()
FUN_EMOJIS = [
"🚀", "🤖", "📰", "", "🧠", "💡", "🔋", "🪄", "🌎", "📈",
"🎯", "📱", "🛰️", "🎉", "🦾", "💬", "💻", "🔧", "🔮", "🪙",
"🧪", "🏙️", "🎥", "🧭", "🧩", "🌠", "🏎️", "🌍", "🔥", "📊"
]
KEYWORD_EMOJIS = {
"tesla": "🚘",
"spacex": "🚀",
"ai": "🤖",
"robot": "🦾",
"technology": "💻",
"innovation": "💡",
"finance": "💰",
"stock": "📈",
"crypto": "🪙",
"climate": "🌍",
"energy": "",
"launch": "🛫",
"startup": "🚀",
"science": "🔬",
"research": "🧠",
"market": "📊",
"policy": "🏛️",
"security": "🔒",
"china": "🐉",
"usa": "🦅",
}
def emoji_for_headline(title: str) -> str:
title_lower = title.lower()
for word, icon in KEYWORD_EMOJIS.items():
if word in title_lower:
return icon
return random.choice(FUN_EMOJIS)
def fetch_news():
headers = {
"X-API-Key": API_KEY,
"User-Agent": "news-api-python-tutorial/1.0-py"
}
console.print(
"\n[bold #003366]📰 Presented by [bold orange3]NewsDataHub[/bold orange3] — "
"Your Gateway to Global News Intelligence[/bold #003366]\n"
)
with Progress(SpinnerColumn(), TextColumn("[green]Connecting to NewsDataHub API...")) as progress:
task = progress.add_task("", total=None)
try:
response = requests.get(URL, headers=headers, params=PARAMS, timeout=10)
except Exception as e:
progress.remove_task(task)
console.print(f"[bold red]❌ Connection failed:[/bold red] {e}")
return
progress.remove_task(task)
# Handle HTTP errors gracefully
if response.status_code == 429:
console.print("[bold red]⚠️ Rate limit reached (HTTP 429)[/bold red]. Try again later.")
return
elif 500 <= response.status_code < 600:
console.print(f"[bold red]⚠️ Server error (HTTP {response.status_code}).[/bold red] Please try again later.")
return
elif 400 <= response.status_code < 500:
console.print(f"[bold red]⚠️ Request error (HTTP {response.status_code}).[/bold red] Check your parameters or API key.")
return
data = response.json()
articles = data.get("data", [])
if not articles:
console.print("[yellow]No articles found. Try adjusting your filters.[/yellow]")
return
console.print(
f"\n[bold magenta]🚀 Latest US Tech Headlines ({PER_PAGE} results)[/bold magenta]\n"
)
for i, a in enumerate(articles[:PER_PAGE], start=1):
icon = emoji_for_headline(a["title"])
link = f"[link={a['article_link']}][blue underline]{a['article_link']}[/blue underline][/link]"
console.print(f"[cyan]{i}.[/cyan] {icon} [bold]{a['title']}[/bold]")
console.print(f"[red]{a['source_title']}[/red] • [black]{a['pub_date']}[/black]")
console.print(f"{link}\n")
time.sleep(0.35) # pacing between headlines
console.print("[dim]------------------------------------------------------------[/dim]")
console.print(f"[black]Last updated: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}[/black]")
console.print("\n[bold #003366]✨ Delivered by [bold orange3]NewsDataHub[/bold orange3] ✨[/bold #003366]\n")
if __name__ == "__main__":
fetch_news()

  1. Fetches up to PER_PAGE U.S. technology headlines

  2. Displays each with:

    • Color-coded source, date, and clickable link (if your terminal supports it)
    • Contextual emoji chosen by keywords
    • Graceful pacing between articles
  3. Handles common API errors (rate limit, invalid request, server issues)

  4. Colors are chosen for a clean, readable terminal output:

    • NewsDataHub branding → dark blue + orange
    • Sources → red
    • Dates → black
    • Links → blue (clickable where supported)

You can make your script run automatically once or twice a day.

Open your terminal and run:

Terminal window
pwd # prints current directory
ls # list files

Example output:

/Users/user/projects/news_cli.py
Terminal window
crontab -e

Then add:

0 10 * * * /usr/bin/python3 /Users/user/projects/news_cli.py >> /Users/user/news_cli.log 2>&1
0 16 * * * /usr/bin/python3 /Users/user/projects/news_cli.py >> /Users/user/news_cli.log 2>&1

This runs the script at 10 AM and 4 PM daily, logging output to news_cli.log.

You can check active cron jobs anytime:

Terminal window
crontab -l

  • A clean, colorful terminal app
  • Fetches structured, reliable news data
  • Simple setup with only requests, rich, and emoji
  • Easy automation with cron
  • Fully powered by NewsDataHub

This little tool is a great starting point for:

  • Research dashboards
  • Daily AI training data collection
  • Market or company monitoring bots
  • Or just a fun way to start your morning with the latest tech news.

Adapt this script for different monitoring scenarios using production-tested queries from our Live News Feeds Repository:

Track logistics issues, shortages, and supply chain bottlenecks:

PARAMS = {
"per_page": 100,
"q": '("supply chain" OR logistics OR shipping OR freight) AND (shortage OR delay OR disruption OR bottleneck OR crisis)',
"search_in": "title",
"language": "en"
}

Live feed: https://newsdatahub.com/live/supply-chain

Monitor data breaches, ransomware, and cyber attacks:

PARAMS = {
"per_page": 100,
"q": '(cybersecurity OR "cyber attack" OR "data breach" OR ransomware) AND (threat OR attack OR breach OR hack)',
"search_in": "title",
"language": "en"
}

Live feed: https://newsdatahub.com/live/cybersecurity

Track workforce reductions and hiring freezes:

PARAMS = {
"per_page": 100,
"q": '(layoffs OR "job cuts" OR "hiring freeze" OR "workforce reduction")',
"search_in": "title",
"language": "en"
}

Live feed: https://newsdatahub.com/live/layoffs

Track fraud cases, scams, and financial crime:

PARAMS = {
"per_page": 100,
"q": '(fraud OR scam OR "financial crime" OR "money laundering" OR embezzlement)',
"search_in": "title",
"language": "en"
}

Live feed: https://newsdatahub.com/live/fraud

Track international conflicts and tensions:

# Ukraine War Coverage
PARAMS = {
"per_page": 100,
"q": '(Ukraine OR Russia) AND (war OR conflict OR military OR invasion)',
"language": "en"
}

Live feed: https://newsdatahub.com/live/ukraine-war

Browse 31+ more production-ready queries: Live Feeds Repository — including technology outages, corporate legal news, healthcare costs, climate change, cryptocurrency, and more.


Try it yourself today: https://newsdatahub.com

  • Do I need an API key to use NewsDataHub?

    Yes. Sign up for a free account at newsdatahub.com to get your API key. The free tier includes 100 requests per day to get started.

  • Can I use NewsDataHub API with other Python libraries besides requests?

    Yes. Use any HTTP library like httpx, aiohttp for async, or the built-in urllib. The examples use requests for simplicity.

  • How do I handle API errors in production?

    Implement try-except blocks, check response status codes, use exponential backoff for rate limits (429), and log errors for debugging. See the error handling section above.

  • Can I filter news by multiple topics or countries?

    Yes. Use comma-separated values: topic=technology,business or country=us,gb,ca. Combine filters for precise queries.

  • How often can I make API requests?

    Free tier: 100 requests/day. Paid tiers offer higher limits. Check your plan in the dashboard and implement caching to reduce redundant requests.

  • Can I deploy this CLI tool as a cron job?

    Yes. Schedule it with cron to run hourly or daily: 0 9 * * * python news.py >> news.log 2>&1. Great for daily email digests or Slack notifications.

Olga S.

Founder of NewsDataHub — Distributed Systems & Data Engineering

Connect on LinkedIn