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.
Why Use a News API?
Section titled “Why Use a News API?”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 sportslanguage– e.g. English, Spanish, Arabiccountry– target regional coveragesource_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.
Use Cases
Section titled “Use Cases”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
/relatedendpoint can help surface contextually similar news
Prerequisites
Section titled “Prerequisites”Before we dive in, make sure you have:
- Python 3.8 or newer
- An active NewsDataHub API key
- The following packages installed:
pip install requests rich emojiThe Python Script
Section titled “The Python Script”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.

Full source code: https://github.com/newsdatahub/newsdatahub-news-cli-app
#!/usr/bin/env python3import requestsimport datetimeimport randomimport timefrom rich.console import Consolefrom rich.progress import Progress, SpinnerColumn, TextColumnfrom emoji import emojize
# ====== CONFIGURATION ======PER_PAGE = 100 # change this once — used everywhereAPI_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()How It Works
Section titled “How It Works”-
Fetches up to
PER_PAGEU.S. technology headlines -
Displays each with:
- Color-coded source, date, and clickable link (if your terminal supports it)
- Contextual emoji chosen by keywords
- Graceful pacing between articles
-
Handles common API errors (rate limit, invalid request, server issues)
-
Colors are chosen for a clean, readable terminal output:
- NewsDataHub branding → dark blue + orange
- Sources → red
- Dates → black
- Links → blue (clickable where supported)
Optional: Automate It with a Cron Task
Section titled “Optional: Automate It with a Cron Task”You can make your script run automatically once or twice a day.
Find your script’s full path
Section titled “Find your script’s full path”Open your terminal and run:
pwd # prints current directoryls # list filesExample output:
/Users/user/projects/news_cli.pyEdit your cron schedule
Section titled “Edit your cron schedule”crontab -eThen add:
0 10 * * * /usr/bin/python3 /Users/user/projects/news_cli.py >> /Users/user/news_cli.log 2>&10 16 * * * /usr/bin/python3 /Users/user/projects/news_cli.py >> /Users/user/news_cli.log 2>&1This runs the script at 10 AM and 4 PM daily, logging output to news_cli.log.
You can check active cron jobs anytime:
crontab -lWhat You’ve Built
Section titled “What You’ve Built”- A clean, colorful terminal app
- Fetches structured, reliable news data
- Simple setup with only
requests,rich, andemoji - 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.
More Use Cases
Section titled “More Use Cases”Adapt this script for different monitoring scenarios using production-tested queries from our Live News Feeds Repository:
Supply Chain Disruption Monitoring
Section titled “Supply Chain Disruption Monitoring”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
Cybersecurity Threat Alerts
Section titled “Cybersecurity Threat Alerts”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
Corporate Layoffs Tracking
Section titled “Corporate Layoffs Tracking”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
Financial Fraud Detection
Section titled “Financial Fraud Detection”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
Geopolitical Risk Monitoring
Section titled “Geopolitical Risk Monitoring”Track international conflicts and tensions:
# Ukraine War CoveragePARAMS = { "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,aiohttpfor async, or the built-inurllib. The examples userequestsfor 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,businessorcountry=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.