Getting started overview

Integrating with the GNews API involves a sequence of steps designed to enable quick access to news data. The process begins with account creation and obtaining an API key, which is essential for authenticating requests. Once an API key is secured, developers can proceed to construct and execute their first API calls, typically to endpoints such as the /search or /top-headlines. GNews provides comprehensive documentation with examples in multiple programming languages to facilitate this initial setup.

The GNews API supports two primary functions:

  • News Search: Allows querying for articles based on keywords, topics, language, and other parameters.
  • Top Headlines: Provides access to trending news articles across various categories and countries.

A quick reference table summarizing the initial getting started steps:

Step What to do Where
1. Create Account Register for a GNews account. GNews homepage
2. Obtain API Key Locate your unique API key in the dashboard. GNews dashboard (after registration)
3. Construct Request Format your API call with the endpoint and parameters. GNews API documentation
4. Execute Request Send the HTTP request using your chosen programming language or tool. Development environment (e.g., cURL, Python)
5. Process Response Parse the JSON response to extract news data. Development environment

Create an account and get keys

Before making any requests to the GNews API, an account must be created to obtain an API key. This key is a unique identifier that authenticates your application with the GNews service and tracks your usage against your plan limits, such as the free tier's 100 requests per day.

  1. Visit the GNews website: Navigate to the GNews homepage.
  2. Register for an account: Click on the "Sign Up" or "Get API Key" button. You will typically need to provide an email address and create a password. Account creation is a standard practice for API providers to manage access and analyze usage patterns, as described in common API key best practices.
  3. Access your dashboard: After successful registration and potentially email verification, you will be redirected to your GNews dashboard.
  4. Locate your API key: Your unique API key will be displayed prominently on your dashboard. It is a long alphanumeric string. Copy this key, as it will be required for every API request you make.

Security Note: Your API key should be treated like a password. Do not hardcode it directly into client-side code, commit it to public version control systems, or expose it in publicly accessible files. For server-side applications, it's recommended to store API keys in environment variables or a secure configuration management system. For client-side implementations, consider using a proxy server to keep the key secure.

Your first request

With your API key in hand, you can now make your first request to the GNews API. This example will demonstrate how to fetch top headlines using cURL, a command-line tool for making HTTP requests, and Python, a widely used programming language for API interactions.

The GNews API uses a simple RESTful architecture, where you send HTTP GET requests to specific URLs and receive JSON responses. Authentication is handled by passing your API key as a query parameter named token.

Example: Top headlines with cURL

This cURL command retrieves the top 10 headlines in English about technology. Replace YOUR_API_KEY with the actual key copied from your GNews dashboard.

curl "https://gnews.io/api/v4/top-headlines?category=technology&lang=en&country=us&max=10&token=YOUR_API_KEY"

Explanation:

  • https://gnews.io/api/v4/top-headlines: The base URL for the top headlines endpoint.
  • category=technology: Filters articles by the 'technology' category.
  • lang=en: Specifies the language of the articles as English.
  • country=us: Specifies the country of the articles as United States.
  • max=10: Limits the number of articles returned to 10.
  • token=YOUR_API_KEY: Your unique API key for authentication.

Example: Top headlines with Python

This Python script performs the same request, retrieving 10 technology headlines. Ensure you replace YOUR_API_KEY with your key.

import requests
import json

API_KEY = "YOUR_API_KEY"  # Replace with your actual GNews API key
BASE_URL = "https://gnews.io/api/v4/top-headlines"

params = {
    "category": "technology",
    "lang": "en",
    "country": "us",
    "max": 10,
    "token": API_KEY
}

try:
    response = requests.get(BASE_URL, params=params)
    response.raise_for_status()  # Raise an HTTPError for bad responses (4xx or 5xx)
    data = response.json()

    print("Successfully fetched top headlines:")
    for article in data.get("articles", []):
        print(f"- {article['title']} ({article['source']['name']})")

except requests.exceptions.HTTPError as errh:
    print(f"HTTP Error: {errh}")
except requests.exceptions.ConnectionError as errc:
    print(f"Error Connecting: {errc}")
except requests.exceptions.Timeout as errt:
    print(f"Timeout Error: {errt}")
except requests.exceptions.RequestException as err:
    print(f"Something went wrong: {err}")
except json.JSONDecodeError:
    print("Failed to decode JSON response.")

Expected JSON Response (partial):

{
  "totalArticles": 15234,
  "articles": [
    {
      "title": "Example Article Title 1",
      "description": "Brief description of the article 1.",
      "content": "Full content of the article 1...",
      "url": "https://example.com/article1",
      "image": "https://example.com/image1.jpg",
      "publishedAt": "2026-05-29T10:00:00Z",
      "source": {
        "name": "Example Source",
        ""url": "https://example.com/source"
      }
    },
    // ... more articles
  ]
}

Common next steps

After successfully making your first API call, consider these next steps to further integrate GNews into your application:

  • Explore other endpoints: Beyond /top-headlines, investigate the /search endpoint to query specific keywords, phrases, and apply advanced filters such as date ranges, language, and countries for more targeted news retrieval.
  • Error handling: Implement robust error handling in your application. The GNews API returns standard HTTP status codes (e.g., 400 Bad Request, 401 Unauthorized, 403 Forbidden, 429 Too Many Requests, 500 Internal Server Error). Your code should gracefully manage these responses to provide a stable user experience. Understanding HTTP status codes is fundamental for API development.
  • Parameterization and dynamic queries: Instead of hardcoding parameters, allow users to input search terms or select categories. This makes your application more dynamic and useful.
  • Pagination: If you expect a large number of results, implement pagination using the page parameter to fetch articles in batches, optimizing load times and resource usage.
  • Rate Limit Management: Keep track of your API usage to stay within your plan's rate limits. For the free tier, this is 100 requests per day. Implement mechanisms like exponential backoff for retries to handle 429 Too Many Requests errors.
  • Data Storage and Caching: For frequently accessed news, consider caching responses to reduce API calls and improve performance. Ensure compliance with GNews's terms of service regarding data retention.
  • Explore SDKs/Libraries: While GNews doesn't provide official SDKs, community-contributed libraries in your preferred language might simplify integration. Search GitHub or package managers for "GNews API client library".

Troubleshooting the first call

Encountering issues during your first API call is common. Here are some typical problems and their solutions:

  • 401 Unauthorized or API Key invalid:
    • Issue: Your API key is incorrect, missing, or expired.
    • Solution: Double-check that you have copied the correct API key from your GNews dashboard. Ensure it's included as the token parameter in your request URL. API keys are case-sensitive.
  • 400 Bad Request:
    • Issue: The request URL or parameters are malformed or contain invalid values.
    • Solution: Review the GNews API documentation for the specific endpoint you are calling. Verify parameter names, expected values, and required parameters. For example, ensuring category or lang are valid options.
  • 429 Too Many Requests:
    • Issue: You have exceeded your plan's rate limit (e.g., 100 requests/day for the free tier).
    • Solution: Wait for the rate limit to reset (usually daily). Implement logic to track your requests and avoid hitting the limit. Consider upgrading your GNews subscription plan if you require higher volumes.
  • Network Issues (e.g., connection timeout):
    • Issue: Your application cannot establish a connection to the GNews API server.
    • Solution: Check your internet connection. Verify that there are no firewalls or network configurations blocking outbound HTTP requests to gnews.io.
  • Empty Response or Unexpected Data Structure:
    • Issue: The API call succeeded, but the articles array is empty, or the JSON structure differs from expectations.
    • Solution: This might indicate no articles matching your specific query parameters. Try broadening your search (e.g., remove specific keywords, categories, or countries). Consult the GNews API reference for the exact JSON response structure.
  • CORS Policy Error (for client-side JavaScript):
    • Issue: If you are making requests directly from a web browser (e.g., with JavaScript), you might encounter Cross-Origin Resource Sharing (CORS) errors.
    • Solution: The GNews API likely does not support direct client-side requests due to CORS restrictions for security. You will need to route API calls through a backend server (proxy) that then communicates with the GNews API. This is a common pattern for handling CORS restrictions when consuming APIs from browsers.