How Do I Filter News by Country? Geographic News Filtering with NewsDataHub API
Filtering news by country allows you to deliver location-specific content to your users, whether you’re building a regional news app, tracking international events, or providing localized news feeds. NewsDataHub API makes country-based filtering simple using ISO 2-letter country codes like ‘US’ for United States or ‘GB’ for Great Britain. In this guide, you’ll learn how to use the country parameter to filter news articles by geographic region, combine multiple countries in a single query, and implement location-based news delivery in your applications. These techniques are essential for developers building news aggregators, regional dashboards, or any application that needs to display country-specific headlines.
Understanding the NewsDataHub API
Section titled “Understanding the NewsDataHub API”The NewsDataHub API is a robust news data service that provides access to a wide range of news articles from global sources. One of the API’s key features is geographic filtering. This feature allows us to filter news articles based on the country of origin using ISO 2-letter country codes.
Filtering by Country
Section titled “Filtering by Country”To filter news by country, we use the country parameter in our API request. This parameter accepts ISO 2-letter country codes. For instance, if we want to fetch news from the United States, we would use the code ‘US’:
fetch('https://api.newsdatahub.com/v1/news?country=US', { headers: { 'X-API-Key': 'your_api_key_here', 'User-Agent': 'newsdatahub-country-filtering/1.0-js' }}) .then(response => response.json()) .then(data => { console.log(`Found ${data.total_results} articles`); console.log(data.data); // Array of articles });In the above example, the ‘fetch’ function sends a GET request to the NewsDataHub API with the country parameter set to ‘US’. The API then returns a list of news articles from the United States.
Filtering by Multiple Countries
Section titled “Filtering by Multiple Countries”The NewsDataHub API also supports filtering by multiple countries at once. This is useful when we want to display news from several related countries. We can accomplish this by using comma-separated country codes:
fetch('https://api.newsdatahub.com/v1/news?country=US,CA,GB', { headers: { 'X-API-Key': 'your_api_key_here', 'User-Agent': 'newsdatahub-country-filtering/1.0-js' }}) .then(response => response.json()) .then(data => { console.log(`Found ${data.total_results} articles from US, Canada, and UK`); console.log(data.data); // Array of articles });In this example, we’re fetching news from the United States (US), Canada (CA), and Great Britain (GB) in a single request.
Combining Country Filtering with Other Parameters
Section titled “Combining Country Filtering with Other Parameters”You can combine country filtering with other available parameters for more precise news selection. Here are some useful combinations:
// Get technology news from Germany in German languagefetch('https://api.newsdatahub.com/v1/news?country=DE&topic=technology&language=de', { headers: { 'X-API-Key': 'your_api_key_here', 'User-Agent': 'newsdatahub-country-filtering/1.0-js' }}) .then(response => response.json()) .then(data => console.log(data.data));
// Get news from France in the last 7 daysconst oneWeekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];const today = new Date().toISOString().split('T')[0];
fetch(`https://api.newsdatahub.com/v1/news?country=FR&start_date=${oneWeekAgo}&end_date=${today}`, { headers: { 'X-API-Key': 'your_api_key_here', 'User-Agent': 'newsdatahub-country-filtering/1.0-js' }}) .then(response => response.json()) .then(data => console.log(data.data));Regional Monitoring: Real-World Examples
Section titled “Regional Monitoring: Real-World Examples”These production feeds demonstrate country-specific news filtering for different use cases:
Canadian News (English)
Section titled “Canadian News (English)”Monitor Canadian political and business news in English:
fetch('https://api.newsdatahub.com/v1/news?country=CA&language=en&topic=politics,business', { headers: { 'X-API-Key': 'your_api_key_here', 'User-Agent': 'newsdatahub-country-filtering/1.0-js' }}) .then(response => response.json()) .then(data => console.log(data.data));Use case: Policy teams tracking Canadian government actions and corporate news Live feed: Canadian News (English)
China Economy News
Section titled “China Economy News”Track Chinese economic developments reported in English-language sources:
fetch('https://api.newsdatahub.com/v1/news?country=CN&topic=economy,business&language=en', { headers: { 'X-API-Key': 'your_api_key_here', 'User-Agent': 'newsdatahub-country-filtering/1.0-js' }}) .then(response => response.json()) .then(data => console.log(data.data));Use case: Financial analysts monitoring Chinese market trends Live feed: China Economy News
United States Political Coverage
Section titled “United States Political Coverage”Monitor US political news with comprehensive coverage:
fetch('https://api.newsdatahub.com/v1/news?country=US&topic=politics&language=en', { headers: { 'X-API-Key': 'your_api_key_here', 'User-Agent': 'newsdatahub-country-filtering/1.0-js' }}) .then(response => response.json()) .then(data => console.log(data.data));Use case: Political analysts tracking US government and elections Live feed: US Political News
Multi-Country European Coverage
Section titled “Multi-Country European Coverage”Track news across multiple European countries simultaneously:
fetch('https://api.newsdatahub.com/v1/news?country=DE,FR,GB,IT,ES&language=en&topic=economy', { headers: { 'X-API-Key': 'your_api_key_here', 'User-Agent': 'newsdatahub-country-filtering/1.0-js' }}) .then(response => response.json()) .then(data => console.log(data.data));Use case: European market intelligence and cross-border business monitoring
Getting Source Geolocation Data
Section titled “Getting Source Geolocation Data”While the NewsDataHub /v1/news endpoint provides basic source information, detailed geolocation data (latitude, longitude, city, timezone) is only available through the /v1/sources endpoint. To get geolocation data for news articles, you need to make a two-step process:
- First, fetch news articles to get source IDs
- Then, fetch detailed source information using those IDs
Here’s how to access geolocation data properly:
async function getNewsWithGeolocation(countryCode) { try { // Step 1: Get news articles const newsResponse = await fetch(`https://api.newsdatahub.com/v1/news?country=${countryCode}`, { headers: { 'X-API-Key': 'your_api_key_here', 'User-Agent': 'newsdatahub-country-filtering/1.0-js' } }); const newsData = await newsResponse.json();
// Step 2: Get geolocation for each unique source const sourceIds = [...new Set(newsData.data.map(article => article.source?.id).filter(Boolean))];
for (const sourceId of sourceIds) { const sourceResponse = await fetch(`https://api.newsdatahub.com/v1/sources/${sourceId}`, { headers: { 'X-API-Key': 'your_api_key_here', 'User-Agent': 'newsdatahub-country-filtering/1.0-js' } }); const sourceData = await sourceResponse.json();
if (sourceData.geolocation) { const { latitude, longitude, city, timezone } = sourceData.geolocation; console.log(`Source: ${sourceData.title}`);
// Handle potential null coordinates if (latitude !== null && longitude !== null) { console.log(`Location: ${city} (${latitude}, ${longitude})`); console.log(`Timezone: ${timezone}`); // Use coordinates for mapping features } else { console.log(`Location: ${city} (coordinates not available)`); }
// Find articles from this source const articlesFromSource = newsData.data.filter(article => article.source?.id === sourceId); console.log(`Articles from this location: ${articlesFromSource.length}`); } } } catch (error) { console.error('Error fetching data:', error); }}
// UsagegetNewsWithGeolocation('US');Conclusion
Section titled “Conclusion”Country news filtering is an essential feature for any news aggregator or application that deals with global news. The NewsDataHub API makes it easy to implement this feature with its country parameter, supporting both single and multiple country filtering. By combining country filtering with other parameters like topic, language, and date ranges, along with the geolocation data available in the source metadata, we can create engaging, location-based news experiences for our users.
As your next step, explore the NewsDataHub API documentation to learn more about its features and capabilities. Try combining country filtering with topic or language parameters, or experiment with displaying news articles on a map using the geolocation data. Happy coding!
-
Can I filter by multiple countries at once?
Yes. Use comma-separated ISO codes:
country=us,gb,ca. This returns articles from any of the specified countries. -
What if I want global news excluding specific countries?
Currently, the API supports inclusion filtering only. To exclude countries, fetch all results and filter client-side, or make separate requests per desired country.
-
Do country filters work with the /top endpoint?
Yes. Both
/searchand/topendpoints support thecountryparameter for geographic filtering. -
How accurate is country detection?
Country is determined by publisher location and article origin, not content topic. An article about France from a US publisher returns
country=us. -
Can I get city-level or region-level filtering?
No. Country is the finest geographic granularity available. Use keyword search or topic filters for city-specific news (e.g.,
q="New York").