How Do I Get Breaking News and Top Headlines with NewsDataHub API?
Discover how to integrate NewsDataHub’s breaking news API via GET /v1/top-news to fetch curated news by topic, country, language, and source. This comprehensive guide covers news API filters, pagination techniques, and powerful query operators with practical code examples.
As developers, we often need to provide our users with the most relevant and timely news updates. Whether it’s for a news aggregator app, a finance platform tracking economic news, or a political blog analyzing recent events, the NewsDataHub API is a powerful tool that enables us to retrieve curated top stories within a specified timeframe. This news API allows us to filter breaking news by topics such as politics, technology, business, finance, and more. This article will guide you through the process of integrating and effectively using the NewsDataHub breaking news API, specifically the GET /v1/top-news endpoint.
Understanding the GET /v1/top-news Endpoint
Section titled “Understanding the GET /v1/top-news Endpoint”The GET /v1/top-news endpoint of the NewsDataHub breaking news API retrieves top articles published within the last 24-72 hours from the top-news source profile (digital_native, mainstream_news, newspaper, news_agency). It provides numerous news API filters including topics, ISO-3166-1 alpha-2 country codes, sources, and even political leaning filters.
Here’s a quick overview of some key parameters you can use:
hours:- Type: Integer (query parameter)
- Purpose: Filters articles published within the last 24, 48, or 72 hours.
- Accepted values:
24,48,72 - Default:
48 - Example:
?hours=24
require_media:- Type: Boolean (query parameter)
- Purpose: If
true, only returns articles that include media (images or videos). - Accepted values:
true,false - Default:
false - Example:
?require_media=true
q:- Type: String (query parameter)
- Purpose: Search query that supports logical operators:
AND,OR,NOT. - Notes: Useful for keyword filtering across article content.
- Example:
?q=election AND economy NOT sports
country:- Type: String (query parameter)
- Purpose: Filter by one or more ISO-3166-1 alpha-2 country codes.
- Accepted format: Single code (
US) or comma-separated (US,CA,GB). - Regex validation:
^[A-Z]{2}(,[A-Z]{2})*$ - Example:
?country=US,CA
topic:- Type: Array of strings (query parameter, supports multiple values or comma-separated)
- Purpose: Filter by news topics/categories.
- Default topics:
politics,technology,business,finance,government,crime,health,sports,economy,international,law,science - Clarification: Filtering by non-default topics may return fewer or no results.
- Example:
?topic=politics,technology
language:- Type: String (query parameter)
- Purpose: Filter by article language using ISO‑639‑1 codes.
- Regex validation:
^[a-z]{2}$ - Examples:
en,fr,es - Example:
?language=en
source:- Type: Array of strings (query parameter, supports multiple values or comma-separated)
- Purpose: Filter by one or more news source names.
- Example:
?source=Boston.com,BBC News
political_leaning:- Type: Array of strings (query parameter, supports multiple values or comma-separated)
- Purpose: Filter by source political alignment.
- Accepted values:
left,center_left,center,center_right,right,far_left,far_right
- Example:
?political_leaning=center_left,center_right
per_page:- Type: Integer (query parameter)
- Purpose: Defines number of results returned per page.
- Accepted values: 1-100
- Default: free
10, starter30, paid tiers50 - Example:
?per_page=20
cursor:- Type: String (query parameter)
- Purpose: Provides a pagination cursor to continue fetching results from a previous response.
- Clarification: Useful for large datasets where offset-based pagination is inefficient.
- Example:
?cursor=eyJvZmZzZXQiOjIwLCJ0aW1lc3RhbXAiOiIyMDI1LTAxLTE1VDEwOjMwOjAwWiJ9
fields:- Type: String (query parameter)
- Purpose: Comma-separated list of specific fields to include in the response.
- Default: Returns all fields if not specified.
- Special rule:
idis always included. - Example:
?fields=title,pub_date,source_title
Retrieving Top News Articles
Section titled “Retrieving Top News Articles”Below is an example of how to retrieve top news articles using a GET request. For this example, we’re using Python and the requests library.
import requests
API_KEY = "your-api-key"URL = "https://api.newsdatahub.com/v1/top-news"headers = { "x-api-key": API_KEY, "accept": "application/json", "User-Agent": "newsdatahub-top-news-endpoint/1.0-py"}params = { 'hours': 24, 'topic': 'technology', 'per_page': 10, 'country': 'US'}
try: response = requests.get(URL, params=params, headers=headers, timeout=30) response.raise_for_status() # Raise exception for 4XX/5XX status codes
data = response.json()['data'] for article in data: print(article['title']) print(f"By {article['source_title']}, published: {article['pub_date']}") print('----------------------------')
except requests.exceptions.HTTPError as err: status_code = err.response.status_code if status_code == 400: print("Error 400: Bad Request - Check your parameters") elif status_code == 401: print("Error 401: Unauthorized - Invalid API key") elif status_code == 429: print("Error 429: Too Many Requests - Rate limit exceeded") elif status_code == 500: print("Error 500: Internal Server Error - Try again later") else: print(f"HTTP Error: {err}")except requests.exceptions.RequestException as err: print(f"Request Error: {err}")except (KeyError, ValueError) as err: print(f"Response parsing error: {err}")Example output:
EV buyers lose $7,500 tax break; automakers offer workaroundsBy WPTV NewsChannel 5, published: 2025-10-02T15:04:24----------------------------US stocks drift near their records as tech keeps rising and Wall Street keeps ignoring DC's shutdownBy WSVN 7News, published: 2025-10-02T14:45:24----------------------------Waymo's self-driving car tested after traffic violation near San FranciscoBy CBS News, published: 2025-10-02T14:43:00----------------------------Tesla deliveries rise 7% before EV tax credits expireBy CNBC, published: 2025-10-02T14:08:41----------------------------OpenAI hits $500 billion valuation after share sale to SoftBank, others, source saysBy One America News Network, published: 2025-10-02T13:36:52----------------------------New exoskeleton built to boost endurance and cut fatigueBy Fox News, published: 2025-10-02T12:52:56----------------------------Rivian Narrows Outlook for Full-Year Electric Vehicle DeliveriesBy Bloomberg, published: 2025-10-02T12:47:13----------------------------Trump to Talk Federal Job Cuts, OpenAI's Milestone, MoreBy Bloomberg, published: 2025-10-02T12:44:15----------------------------OpenAI Becomes Most Valuable Startup, US Shutdown Enters 2nd Day | The Opening Trade 10/2By Bloomberg, published: 2025-10-02T12:18:19----------------------------CNBC's Inside India newsletter: India's gigawatt gold rushBy CNBC, published: 2025-10-02T12:03:58----------------------------In the above example, we’re retrieving the top technology news articles from the last 24 hours for the US using ISO-3166-1 alpha-2 country codes.
Truncated example of the response:
Section titled “Truncated example of the response:”{ "next_cursor": "MC4wLDE3NTk0MTAxMDQwMDAsMjAxOTA5ODEx", "total_results": 1021, "per_page": 50, "data": [ { "id": "5a650f3a-d792-48ba-a36a-59b6493b7b71", "title": "Calm down — AI’s not killing jobs as fast as you think", "source_title": "WPTV NewsChannel 5", "source_link": "https://www.wptv.com", "article_link": "https://www.wptv.com/science-and-tech/artificial-intelligence/calm-down-ais-not-killing-jobs-as-fast-as-you-think", "keywords": [ "yale", "budget lab", "technological", "organizations", "institutional", "vulnerable because organizations", "worried artificial intelligence", "organizations are accelerating" ], "topics": [ "economy", "technology", "job market", "business", "anxiety" ], "description": "A Yale report says AI hasnt caused major job losses 33 months after ChatGPTs debut, despite polls showing widespread worker anxiety.", "pub_date": "2025-10-02T17:43:18", "creator": "Justin Boggs", "content": "As many workers say they are worried artificial intelligence might replace them, so far AI has failed to cause any substantive changes to the workforce, according to a new report from Yales Budget Lab. The report notes changes in the types of jobs people hold, but says some of these shifts can be explained by workers changing positions or reentering the workforce from unemployment. \"Our metrics indicate that the broader labor market has not experienced a discernible disruption since ChatGPTs release 33 months ago, undercutting fears that AI automation is currently eroding the demand for cognitive labor across the economy,\" the report says. The disruption AI has caused to the workforce is similar to other technological shifts, such as the advent of the Internet in the 1990s or the rise of personal computing in the 1980s, the report adds. RELATED STORY | ChatGPT launches parental control features for teen users The findings come as polls show workers expressing concern that their jobs could be replaced by AI. Separate surveys also show some employers plan to use AI to replace certain roles. A recent survey by Resume. org found that four in 10 employers plan to replace part of their workforce with AI by 2026. Such impacts could be felt across industries. High-salary roles are often targeted first because companies see immediate savings in payroll, and employees lacking AI-related skills are vulnerable because organizations are accelerating automation, said Kara Dennison, head of career advising at Resume. org. Recent hires and entry-level employees are also at risk because they havent built deep institutional knowledge or proven long-term value.\" An August Reuters poll found that 71% of Americans fear permanent job loss due to AI. RELATED STORY | Children are asking AI for advice on sex and mental health, new report finds But the Yale Budget Lab says these polls may not reflect reality.", "media_url": "https://ewscripps.brightspotcdn.com/dims4/default/0d53fbf/2147483647/strip/true/crop/1000x525+0+19/resize/1200x630!/quality/90/?url=https%3A%2F%2Fewscripps.brightspotcdn.com%2Ffd%2Fa9%2Fd9f8ba034c8b866aeee71632df40%2Fshutterstock-2245793859.jpg", "media_type": "image/jpeg", "media_description": null, "media_credit": null, "media_thumbnail": null, "language": "en", "sentiment": { "pos": 0.031, "neg": 0.078, "neu": 0.892 }, "source": { "id": "wptv-west-palm-beach", "country": "US", "political_leaning": "nonpartisan", "reliability_score": 8.0, "type": "mainstream_news" } }, ]}Some fields are provided both as convenience top‑level properties (e.g., source_title) and within nested objects (e.g., source).
Here is another example using curl where we also utilize the fields parameter.
curl -G 'https://api.newsdatahub.com/v1/top-news' \ -H 'x-api-key: YOUR_API_KEY' \ -H 'User-Agent: newsdatahub-top-news-endpoint/1.0-curl' \ --data-urlencode 'hours=48' \ --data-urlencode 'topic=technology' \ --data-urlencode 'country=US' \ --data-urlencode 'per_page=5' \ --data-urlencode 'fields=title,article_link,source,pub_date'The response will only return fields specified in fields parameter. Note that id is always included.
{ "next_cursor": "MC4wLDE3NTk0MjQ4NjYwMDAsMjAxOTU0Nzky", "total_results": 522, "per_page": 5, "data": [ { "id": "6e80358f-78fd-407b-91d6-bd4c8129753e", "title": "The B-Team shares their AOL screen names", "article_link": "https://wgntv.com/morning-news/the-b-team-shares-their-aol-screen-names/", "source": { "id": "wgn-tv", "country": "US", "political_leaning": "center", "reliability_score": 8.0, "type": "mainstream_news" }, "pub_date": "2025-10-02T18:24:22.284193" }, { "id": "fff9f06b-d751-4247-9963-28db57fa7581", "title": "Stablecoins Make Banking Narrower", "article_link": "https://www.bloomberg.com/opinion/newsletters/2025-10-02/stablecoins-make-banking-narrower", "source": { "id": "bloomberg", "country": "US", "political_leaning": "nonpartisan", "reliability_score": 9.0, "type": "mainstream_news" }, "pub_date": "2025-10-02T17:55:40" }, { "id": "5a650f3a-d792-48ba-a36a-59b6493b7b71", "title": "Calm down — AI’s not killing jobs as fast as you think", "article_link": "https://www.wptv.com/science-and-tech/artificial-intelligence/calm-down-ais-not-killing-jobs-as-fast-as-you-think", "source": { "id": "wptv-west-palm-beach", "country": "US", "political_leaning": "nonpartisan", "reliability_score": 8.0, "type": "mainstream_news" }, "pub_date": "2025-10-02T17:43:18" }, { "id": "e67e7a63-0b01-4d61-9c49-44faa60db48e", "title": "Intel stock is up 50% over the last month, putting U.S. stake at $16 billion", "article_link": "https://www.cnbc.com/2025/10/02/intel-stock-us-trump-stake.html", "source": { "id": "cnbc", "country": "US", "political_leaning": "center", "reliability_score": 8.0, "type": "mainstream_news" }, "pub_date": "2025-10-02T17:37:40" }, { "id": "331c40b5-f0b8-4492-811a-6b91fc498388", "title": "Perplexity AI rolls out Comet browser for free worldwide", "article_link": "https://www.cnbc.com/2025/10/02/perplexity-ai-comet-browser-free-.html", "source": { "id": "cnbc", "country": "US", "political_leaning": "center", "reliability_score": 8.0, "type": "mainstream_news" }, "pub_date": "2025-10-02T17:07:46" } ]}Error Handling and Rate Limits
Section titled “Error Handling and Rate Limits”The NewsDataHub API returns standard HTTP status codes. It’s important to handle these error responses appropriately in your code and respect the rate limits. Below are a few common error responses and what they mean:
- 400 Bad Request: The request was unacceptable, often due to missing a required parameter.
- 401 Unauthorized: No valid API key provided.
- 429 Too Many Requests: You’ve exceeded the rate limits. Check the official documentation for current limits.
- 500 Internal Server Error: Something went wrong on NewsDataHub’s end. Try again later. If error persists, contact our support team.
Frequently Asked Questions (FAQ)
Section titled “Frequently Asked Questions (FAQ)”-
What is the NewsDataHub API?
The NewsDataHub API is a comprehensive news data service that provides access to breaking news articles from major publications worldwide. It offers powerful filtering capabilities by topic, country, language, source and more. Check out our official documentation here.
-
Can I try the NewsDataHub API without writing code?
Yes, we have an interactive API Testing Tool in our documentation that lets you make API requests directly from the browser. Just sign up for an account to get your API key (no credit card required) and start testing various endpoints and parameters right away in our docs.
-
How fresh is the news data provided by the API?
The NewsDataHub API offers two main endpoints. The
GET /v1/top-newsendpoint returns curated articles from the top-news source profile (digital_native,mainstream_news,newspaper,news_agency) published within the last 24-72 hours (default 48 hours). TheGET /v1/newsendpoint provides the complete stream of articles ingested in near real-time, along with access to historical articles in our database, ensuring you can query both the latest updates and past coverage. -
Can I filter news by multiple criteria simultaneously?
Yes, the API supports multiple filter parameters in a single request. You can combine filters for topic, country, language, source, and even political leaning to retrieve highly targeted news content.
-
What programming languages can I use with the NewsDataHub API?
The NewsDataHub API is RESTful and can be integrated with any programming language that supports HTTP requests, including Python, JavaScript, Ruby, PHP, Java, and more.
-
Is there a limit to the number of API requests I can make?
Yes, the API has rate limits that vary by subscription plan. You should implement proper error handling for 429 responses (Too Many Requests) and refer to the official documentation for specific limits.
Wrapping Up
Section titled “Wrapping Up”The NewsDataHub news API is a versatile tool that can provide your applications with real-time, curated breaking news data. Its extensive news API filters allow for streamlined news personalization based on your users’ preferences, whether they want news by topic, news by country, or filtered by political leaning. Remember to handle responses and errors correctly, respect rate limits, and always refer to the official API documentation for updated information on pricing and more. Happy coding!
-
How often does the /top endpoint update?
Top news updates continuously as articles are published and engagement changes. Poll every 5-15 minutes for near-real-time trending stories.
-
What determines if an article is ‘top’ or ‘trending’?
A combination of recency, publisher authority, social engagement, and topic momentum. The algorithm adapts to breaking news and trending topics.
-
Can I get top news for specific topics only?
Yes. Use the
topicparameter to filter top news by category:topic=technologyreturns only trending tech stories. -
Is there a limit to how many top articles I can fetch?
Use the
page_sizeparameter (max 100 per request). Pagination lets you fetch more if needed, though top news is typically most relevant in the first page. -
How is /top different from /search with recent date filter?
/topranks by trending momentum and breaking news signals./searchwith date filters ranks by relevance to your keyword query.