Stay Updated with the Real Time Global News API

7 Jun 2025
Stay Updated with the Real Time Global News API

The Real Time Global News API is an invaluable tool for developers looking to integrate real-time news data into their applications. With its cognitive actions, you can easily search for news articles and fetch the latest headlines from various sources around the world. This API provides a streamlined way to access current events, making it perfect for applications that require timely information. The benefits of using this API include faster access to the latest news, customizable search options, and the ability to filter results based on specific criteria such as country, language, and publication date.

Use Cases:

  • News Aggregators: Build applications that compile news from various sources and present it in a user-friendly format.
  • Market Analysis: Use the latest news to analyze trends and sentiments in financial markets or industries.
  • Research Tools: Provide researchers with access to current events and articles relevant to their fields of study.
  • Social Media Applications: Integrate news feeds into social media platforms to keep users informed about the latest happenings.

Prerequisites:

To utilize the Real Time Global News API, you'll need an API key. Familiarity with making API calls and handling JSON data will also be beneficial.

Search News Articles

The Search News Articles action allows you to search for and retrieve news articles using specified queries. You can enhance your search with optional filters for time range, country, language, and data source.

Input Requirements:

  • query (string): The search term to look up. (e.g., "Elon Musk")
  • limit (number): The maximum number of results to return. Default is 10.
  • country (string): The ISO 3166-1 alpha-2 country code to filter results. Default is 'US'.
  • language (string): The language code to filter results. Default is 'en' for English.
  • timePublished (string): Filters results based on the time they were published (options include 'anytime', '1h', '1d', '7d', '1y').

Expected Output: A JSON object containing an array of news articles that match the search criteria, including article title, link, snippet, authors, and publication date.

Use Cases for Search News Articles:

  • Custom News Feeds: Create personalized news feeds based on user interests.
  • Content Curation: Automatically gather articles for newsletters or blog posts.
  • Real-time Monitoring: Set up alerts for specific topics or events as they unfold in the news.

```python
import requests
import json

# Replace with your actual Cognitive Actions API key and endpoint
# Ensure your environment securely handles the API key
COGNITIVE_ACTIONS_API_KEY = "YOUR_COGNITIVE_ACTIONS_API_KEY"
# This endpoint URL is hypothetical and should be documented for users
COGNITIVE_ACTIONS_EXECUTE_URL = "https://api.cognitiveactions.com/actions/execute"

action_id = "5e152b92-76d0-42f0-a7d3-8361dee4603b" # Action ID for: Search News Articles

# Construct the exact input payload based on the action's requirements
# This example uses the predefined example_input for this action:
payload = {
  "limit": 10,
  "query": "Elon Musk",
  "country": "US",
  "language": "en",
  "timePublished": "anytime"
}

headers = {
    "Authorization": f"Bearer {COGNITIVE_ACTIONS_API_KEY}",
    "Content-Type": "application/json",
    # Add any other required headers for the Cognitive Actions API
}

# Prepare the request body for the hypothetical execution endpoint
request_body = {
    "action_id": action_id,
    "inputs": payload
}

print(f"--- Calling Cognitive Action: {action.name or action_id} ---")
print(f"Endpoint: {COGNITIVE_ACTIONS_EXECUTE_URL}")
print(f"Action ID: {action_id}")
print("Payload being sent:")
print(json.dumps(request_body, indent=2))
print("------------------------------------------------")

try:
    response = requests.post(
        COGNITIVE_ACTIONS_EXECUTE_URL,
        headers=headers,
        json=request_body
    )
    response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)

    result = response.json()
    print("Action executed successfully. Result:")
    print(json.dumps(result, indent=2))

except requests.exceptions.RequestException as e:
    print(f"Error executing action {action_id}: {e}")
    if e.response is not None:
        print(f"Response status: {e.response.status_code}")
        try:
            print(f"Response body: {e.response.json()}")
        except json.JSONDecodeError:
            print(f"Response body (non-JSON): {e.response.text}")
    print("------------------------------------------------")


## Fetch Latest News Headlines
The **Fetch Latest News Headlines** action retrieves the latest top stories or headlines for a specified country using real-time news data. This action is designed to keep users up-to-date with the most current news.

**Input Requirements:**
- **limit (number)**: The maximum number of results to return. Default is 500.
- **country (string)**: The two-letter ISO 3166-1 alpha-2 country code. Default is 'US'.
- **language (string)**: The primary language code in ISO 639-1 format. Default is 'en'.

**Expected Output:**
A JSON object containing an array of the latest news headlines, including article title, link, snippet, source name, and publication date.

### Use Cases for Fetch Latest News Headlines:
- **Headline Widgets:** Integrate a real-time news ticker or widget in websites or applications.
- **Event Monitoring:** Monitor breaking news for specific countries or regions for timely updates.
- **User Notifications:** Alert users about significant news events or developments in their areas of interest.

import requests
import json

# Replace with your actual Cognitive Actions API key and endpoint
# Ensure your environment securely handles the API key
COGNITIVE_ACTIONS_API_KEY = "YOUR_COGNITIVE_ACTIONS_API_KEY"
# This endpoint URL is hypothetical and should be documented for users
COGNITIVE_ACTIONS_EXECUTE_URL = "https://api.cognitiveactions.com/actions/execute"

action_id = "f3ed2a1f-9626-4373-a7ad-860959c23cbd" # Action ID for: Fetch Latest News Headlines

# Construct the exact input payload based on the action's requirements
# This example uses the predefined example_input for this action:
payload = {
  "limit": 500,
  "country": "US",
  "language": "en"
}

headers = {
    "Authorization": f"Bearer {COGNITIVE_ACTIONS_API_KEY}",
    "Content-Type": "application/json",
    # Add any other required headers for the Cognitive Actions API
}

# Prepare the request body for the hypothetical execution endpoint
request_body = {
    "action_id": action_id,
    "inputs": payload
}

print(f"--- Calling Cognitive Action: {action.name or action_id} ---")
print(f"Endpoint: {COGNITIVE_ACTIONS_EXECUTE_URL}")
print(f"Action ID: {action_id}")
print("Payload being sent:")
print(json.dumps(request_body, indent=2))
print("------------------------------------------------")

try:
    response = requests.post(
        COGNITIVE_ACTIONS_EXECUTE_URL,
        headers=headers,
        json=request_body
    )
    response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)

    result = response.json()
    print("Action executed successfully. Result:")
    print(json.dumps(result, indent=2))

except requests.exceptions.RequestException as e:
    print(f"Error executing action {action_id}: {e}")
    if e.response is not None:
        print(f"Response status: {e.response.status_code}")
        try:
            print(f"Response body: {e.response.json()}")
        except json.JSONDecodeError:
            print(f"Response body (non-JSON): {e.response.text}")
    print("------------------------------------------------")


### Conclusion
The Real Time Global News API offers powerful capabilities for developers looking to incorporate real-time news into their applications. By utilizing the Search News Articles and Fetch Latest News Headlines actions, you can create engaging and informative experiences for your users. Whether it's for news aggregation, market analysis, or research purposes, this API provides the tools you need to stay ahead in a fast-paced information landscape. Start integrating today and keep your users informed with the latest global events!