NAV
javascript python csharp php shell

Introduction

Data returned by the API in JSON:

{
  "totalArticles": 54904,
  "articles": [
    {
      "title": "Google's Pixel 7 and 7 Pro’s design gets revealed even more with fresh crisp renders",
      "description": "Now we have a complete image of what the next Google flagship phones will look like. All that's left now is to welcome them during their October announcement!",
      "content": "Google’s highly anticipated upcoming Pixel 7 series is just around the corner, scheduled to be announced on October 6, 2022, at 10 am EDT during the Made by Google event. Well, not that there is any lack of images showing the two new Google phones, b... [1419 chars]",
      "url": "https://www.phonearena.com/news/google-pixel-7-and-pro-design-revealed-even-more-fresh-renders_id142800",
      "image": "https://m-cdn.phonearena.com/images/article/142800-wide-two_1200/Googles-Pixel-7-and-7-Pros-design-gets-revealed-even-more-with-fresh-crisp-renders.jpg",
      "publishedAt": "2022-09-28T08:14:24Z",
      "source": {
        "name": "PhoneArena",
        "url": "https://www.phonearena.com"
      }
    }
  ]
}

GNews API is a simple REST API with which you can search for current and historic news articles published by over 60,000 sources. With this news API, you can also collect the current top headlines articles based on the Google News ranking.

This documentation specifies how to use the API and is provided with various examples in the following programming languages: JavaScript, Python, C#, PHP and Bash. The API is separated into two endpoints, the first is the search endpoint which allows you to search for articles based on a combination of keywords, the second is the top-headlines endpoint which allows you to retrieve trending articles in multiple categories.

On the right side, you can see an example of data returned by the API. The data are always returned in JSON format. Each article contains the following properties:

Property Description
title The main title of the article.
description The small paragraph under the title.
content All the content of the article. The content is truncated if the expand parameter is not set to content. Full content is only available if you have a paid subscription activated on your account.
url The URL of the article.
image The main image of the article.
publishedAt The date of publication of the article. The date is always in the UTC time zone.
source.name The name of the source.
source.url The homepage of the source.

Authentication

GNews API uses a system of API keys to authenticate you. If you don't have an API key yet, you have to sign up first. Once you have created an account you will find your API key in the dashboard.

Your API key must be passed in the query string of your HTTP request like this:

https://gnews.io/api/v4/{endpoint}?apikey=API_KEY

Search Endpoint

To use the search endpoint, use this code:

apikey = 'API_KEY';
url = 'https://gnews.io/api/v4/search?q=example&lang=en&country=us&max=10&apikey=' + apikey;

fetch(url)
  .then(function (response) {
    return response.json();
  })
  .then(function (data) {
    articles = data.articles;

    for (i = 0; i < articles.length; i++) {
      // articles[i].title
      console.log("Title: " + articles[i]['title']);
      // articles[i].description
      console.log("Description: " + articles[i]['description']);
      // You can replace {property} below with any of the article properties returned by the API.
      // articles[i].{property}
      // console.log(articles[i]['{property}']);

      // Delete this line to display all the articles returned by the request. Currently only the first article is displayed.
      break;
    }
  });
# https://docs.python.org/3/library/json.html
# This library will be used to parse the JSON data returned by the API.
import json
# https://docs.python.org/3/library/urllib.request.html#module-urllib.request
# This library will be used to fetch the API.
import urllib.request

apikey = "API_KEY"
url = f"https://gnews.io/api/v4/search?q=example&lang=en&country=us&max=10&apikey={apikey}"

with urllib.request.urlopen(url) as response:
    data = json.loads(response.read().decode("utf-8"))
    articles = data["articles"]

    for i in range(len(articles)):
        # articles[i].title
        print(f"Title: {articles[i]['title']}")
        # articles[i].description
        print(f"Description: {articles[i]['description']}")
        # You can replace {property} below with any of the article properties returned by the API.
        # articles[i].{property}
        # print(f"{articles[i]['{property}']}")

        # Delete this line to display all the articles returned by the request. Currently only the first article is displayed.
        break
// https://www.newtonsoft.com/json
// dotnet add package Newtonsoft.Json
// This library will be used to parse the JSON data returned by the API.
using Newtonsoft.Json;

const string API_KEY = "API_KEY";
const string URL = $"https://gnews.io/api/v4/search?q=example&lang=en&country=us&max=10&apikey={API_KEY}";

HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(URL);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<ApiResponse>(responseBody);
List<Article> articles = data.Articles;

for (int i = 0; i < articles.Count; i++)
{
  // articles[i].title
  Console.WriteLine($"Title: {articles[i].Title}");
  // articles[i].description
  Console.WriteLine($"Description: {articles[i].Description}");
  // You can replace {property} below with any of the article properties returned by the API.
  // articles[i].{property}
  // Console.WriteLine($"{articles[i].{property}}");
  // Note that {property} must be compliant with the definition of class Article.

  // Delete this line to display all the articles returned by the request. Currently only the first article is displayed.
  break;
}

class ApiResponse
{
  public int TotalArticles { get; set; }
  public List<Article> Articles { get; set; } = new List<Article>();
}

class Article
{
  public string Title { get; set; } = "";
  public string Description { get; set; } = "";
  public string Content { get; set; } = "";
  public string Url { get; set; } = "";
  public string Image { get; set; } = "";
  public Source Source { get; set; } = new Source();
}

class Source
{
  public string Name { get; set; } = "";
  public string Url { get; set; } = "";
}
<?php
$apikey = 'API_KEY';
$url = "https://gnews.io/api/v4/search?q=example&lang=en&country=us&max=10&apikey=$apikey";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = json_decode(curl_exec($ch), true);
curl_close($ch);
$articles = $data['articles'];

for ($i = 0; $i < count($articles); $i++) {
    // articles[i].title
    echo "Title: " . $articles[$i]['title'] . "\n";
    // articles[i].description
    echo "Description: " . $articles[$i]['description'] . "\n";
    // You can replace {property} below with any of the article properties returned by the API.
    // articles[i].{property}
    // echo $articles[$i]['{property}'] . "\n";

    // Delete this line to display all the articles returned by the request. Currently only the first article is displayed.
    break;
}
# Please note that you must have the package jq: https://stedolan.github.io/jq/
#!/bin/bash
apikey='API_KEY'
url="https://gnews.io/api/v4/search?q=example&lang=en&country=us&max=10&apikey=$apikey"

data=$(curl -s $url)
articles=$(echo $data | jq '.articles')
articles_length=$(echo $articles | jq length)
echo $articles_length

for ((i = 0; i < $articles_length; i++)); do
  echo $i
  # articles[i].title
  title=$(echo $articles | jq ".[$i].title")
  echo "Title: $title"
  # articles[i].description
  description=$(echo $articles | jq ".[$i].description")
  echo "Description: $description"
  # You can replace {property} below with any of the article properties returned by the API.
  # articles[i].{property}
  # {property}=$(echo $articles | jq ".[$i].{property}")
  # echo "${property}"

  # Delete this line to display all the articles returned by the request. Currently only the first article is displayed.
  break
done

Make sure to replace API_KEY with your API key that you can find in your dashboard.

This endpoint allows you to search for news articles through a combination of keywords.

HTTP Request

GET https://gnews.io/api/v4/search?q=example&apikey=API_KEY

Query Parameters

Parameter Name Default Value Description
q None This parameter is mandatory.
This parameter allows you to specify your search keywords to find the news articles you are looking for. The keywords will be used to return the most relevant articles. It is possible to use logical operators with keywords, see the section on query syntax.
lang Any This parameter allows you to specify the language of the news articles returned by the API. You have to set as value the 2 letters code of the language you want to filter.
See the list of supported languages
country Any This parameter allows you to specify the country where the news articles returned by the API were published, the contents of the articles are not necessarily related to the specified country. You have to set as value the 2 letters code of the country you want to filter.
See the list of supported countries
max 10 This parameter allows you to specify the number of news articles returned by the API. The minimum value of this parameter is 1 and the maximum value is 100. The value you can set depends on your subscription.
See the pricing for more information
in title,description This parameter allows you to choose in which attributes the keywords are searched. The attributes that can be set are title, description and content. It is possible to combine several attributes by separating them with a comma.
e.g. title,description
nullable None This parameter allows you to specify the attributes that you allow to return null values. The attributes that can be set are title, description and content. It is possible to combine several attributes by separating them with a comma.
e.g. title,description
from None This parameter allows you to filter the articles that have a publication date greater than or equal to the specified value. The date must respect the following format:
YYYY-MM-DDThh:mm:ssTZD
TZD = time zone designator, its value must always be Z (universal time)
e.g. 2024-04-24T11:29:26Z
to None This parameter allows you to filter the articles that have a publication date smaller than or equal to the specified value. The date must respect the following format:
YYYY-MM-DDThh:mm:ssTZD
TZD = time zone designator, its value must always be Z (universal time)
e.g. 2024-04-24T11:29:26Z
sortby publishedAt This parameter allows you to choose with which type of sorting the articles should be returned. Two values are possible:
publishedAt = sort by publication date, the articles with the most recent publication date are returned first
relevance = sort by best match to keywords, the articles with the best match are returned first
page 1 This parameter will only work if you have a paid subscription activated on your account.
This parameter allows you to control the pagination of the results returned by the API. The paging behavior is closely related to the value of the max parameter. The first page is page 1, then you have to increment by 1 to go to the next page. Let's say that the value of the max parameter is 10, then the first page will contain the first 10 articles returned by the API (articles 1 to 10), page 2 will return the next 10 articles (articles 11 to 20), the behavior extends to page 3, 4, ...
expand None This parameter will only work if you have a paid subscription activated on your account.
This parameter allows you to return in addition to other data, the full content of the articles. To get the full content of the articles, the parameter must be set to content

Query Syntax

Things to know before you start :

  1. In this section, the word query refers to the value of the q parameter and not to the HTTP request.
  2. The query must be URL-encoded.
  3. It is not possible to use special characters without putting quotes around them.

e.g.

Non Valid Valid
Hello! "Hello!"
Left - Right "Left - Right"
Question? "Question?"

Phrase Search Operator

This operator allows you to make an exact search. Keywords surrounded by quotation marks are used to search for articles with the exact same keyword sequence. For example the query: "Apple iPhone" will return articles matching at least once this sequence of keywords.

Logical AND Operator

This operator allows you to make sure that several keywords are all used in the article search. By default the space character acts as an AND operator, it is possible to replace the space character by AND to obtain the same result. For example the query: Apple Microsoft is equivalent to Apple AND Microsoft

Logical OR Operator

This operator allows you to retrieve articles matching the keyword a or the keyword b. It is important to note that this operator has a higher precedence than the AND operator. For example the query: Apple OR Microsoft will return all articles matching the keyword Apple as well as all articles matching the keyword Microsoft

Due to the higher precedence of the operator OR the following query will not work as expected: Apple AND iPhone OR Microsoft. Normally, articles matching the keywords Apple and iPhone are returned first and then articles matching the keyword Microsoft are returned. Because of the precedence of the OR operator, in practice the query will return articles matching Apple AND iPhone or Apple AND Microsoft. To have a normal behavior, it is necessary to add brackets. The query Apple AND iPhone OR Microsoft will behave normally when it is in this form: (Apple AND iPhone) OR Microsoft

Logical NOT Operator

This operator allows you to remove from the results the articles corresponding to the specified keywords. To use it, you need to add NOT in front of each word or phrase surrounded by quotes. For example the query: Apple NOT iPhone will return all articles matching the keyword Apple but not the keyword iPhone

Examples of valid queries

Query
Microsoft Windows 10
Apple OR Microsoft
Apple AND NOT iPhone
(Windows 7) AND (Windows 10)
"Apple iPhone 13" AND NOT "Apple iPhone 14"
Intel AND (i7 OR i9)
(Intel AND (i7 OR "i9-13900K")) AND NOT AMD AND NOT "i7-13700K"

Top Headlines Endpoint

To use the top headlines endpoint, use this code:

apikey = 'API_KEY';
category = 'general';
url = 'https://gnews.io/api/v4/top-headlines?category=' + category + '&lang=en&country=us&max=10&apikey=' + apikey;

fetch(url)
  .then(function (response) {
    return response.json();
  })
  .then(function (data) {
    articles = data.articles;

    for (i = 0; i < articles.length; i++) {
      // articles[i].title
      console.log("Title: " + articles[i]['title']);
      // articles[i].description
      console.log("Description: " + articles[i]['description']);
      // You can replace {property} below with any of the article properties returned by the API.
      // articles[i].{property}
      // console.log(articles[i]['{property}']);

      // Delete this line to display all the articles returned by the request. Currently only the first article is displayed.
      break;
    }
  });
# https://docs.python.org/3/library/json.html
# This library will be used to parse the JSON data returned by the API.
import json
# https://docs.python.org/3/library/urllib.request.html#module-urllib.request
# This library will be used to fetch the API.
import urllib.request

apikey = "API_KEY"
category = "general"
url = f"https://gnews.io/api/v4/top-headlines?category={category}&lang=en&country=us&max=10&apikey={apikey}"

with urllib.request.urlopen(url) as response:
    data = json.loads(response.read().decode("utf-8"))
    articles = data["articles"]

    for i in range(len(articles)):
        # articles[i].title
        print(f"Title: {articles[i]['title']}")
        # articles[i].description
        print(f"Description: {articles[i]['description']}")
        # You can replace {property} below with any of the article properties returned by the API.
        # articles[i].{property}
        # print(f"{articles[i]['{property}']}")

        # Delete this line to display all the articles returned by the request. Currently only the first article is displayed.
        break
// https://www.newtonsoft.com/json
// dotnet add package Newtonsoft.Json
// This library will be used to parse the JSON data returned by the API.
using Newtonsoft.Json;

const string API_KEY = "API_KEY";
const string CATEGORY = "general";
const string URL = $"https://gnews.io/api/v4/top-headlines?category={CATEGORY}&lang=en&country=us&max=10&apikey={API_KEY}";

HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(URL);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<ApiResponse>(responseBody);
List<Article> articles = data.Articles;

for (int i = 0; i < articles.Count; i++)
{
  // articles[i].title
  Console.WriteLine($"Title: {articles[i].Title}");
  // articles[i].description
  Console.WriteLine($"Description: {articles[i].Description}");
  // You can replace {property} below with any of the article properties returned by the API.
  // articles[i].{property}
  // Console.WriteLine($"{articles[i].{property}}");
  // Note that {property} must be compliant with the definition of class Article.

  // Delete this line to display all the articles returned by the request. Currently only the first article is displayed.
  break;
}

class ApiResponse
{
  public int TotalArticles { get; set; }
  public List<Article> Articles { get; set; } = new List<Article>();
}

class Article
{
  public string Title { get; set; } = "";
  public string Description { get; set; } = "";
  public string Content { get; set; } = "";
  public string Url { get; set; } = "";
  public string Image { get; set; } = "";
  public Source Source { get; set; } = new Source();
}

class Source
{
  public string Name { get; set; } = "";
  public string Url { get; set; } = "";
}
<?php
$apikey = 'API_KEY';
$category = 'general';
$url = "https://gnews.io/api/v4/top-headlines?category=$category&lang=en&country=us&max=10&apikey=$apikey";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = json_decode(curl_exec($ch), true);
curl_close($ch);
$articles = $data['articles'];

for ($i = 0; $i < count($articles); $i++) {
    // articles[i].title
    echo "Title: " . $articles[$i]['title'] . "\n";
    // articles[i].description
    echo "Description: " . $articles[$i]['description'] . "\n";
    // You can replace {property} below with any of the article properties returned by the API.
    // articles[i].{property}
    // echo $articles[$i]['{property}'] . "\n";

    // Delete this line to display all the articles returned by the request. Currently only the first article is displayed.
    break;
}
# Please note that you must have the package jq: https://stedolan.github.io/jq/
#!/bin/bash
apikey='API_KEY'
category='general'
url="https://gnews.io/api/v4/top-headlines?category=$category&lang=en&country=us&max=10&apikey=$apikey"

data=$(curl -s $url)
articles=$(echo $data | jq '.articles')
articles_length=$(echo $articles | jq length)
echo $articles_length

for ((i = 0; i < $articles_length; i++)); do
  echo $i
  # articles[i].title
  title=$(echo $articles | jq ".[$i].title")
  echo "Title: $title"
  # articles[i].description
  description=$(echo $articles | jq ".[$i].description")
  echo "Description: $description"
  # You can replace {property} below with any of the article properties returned by the API.
  # articles[i].{property}
  # {property}=$(echo $articles | jq ".[$i].{property}")
  # echo "${property}"

  # Delete this line to display all the articles returned by the request. Currently only the first article is displayed.
  break
done

Make sure to replace API_KEY with your API key that you can find in your dashboard.

This endpoint allows you to search for current trending articles, the articles that are selected to be returned by this endpoint are based on the Google News ranking. There are 9 categories available, the default category is "general".

HTTP Request

GET https://gnews.io/api/v4/top-headlines?category=general&apikey=API_KEY

Query Parameters

Parameter Name Default Value Description
category general This parameter allows you to change the category for the request. The available categories are : general, world, nation, business, technology, entertainment, sports, science and health.
lang Any This parameter allows you to specify the language of the news articles returned by the API. You have to set as value the 2 letters code of the language you want to filter.
See the list of supported languages
country Any This parameter allows you to specify the country where the news articles returned by the API were published, the contents of the articles are not necessarily related to the specified country. You have to set as value the 2 letters code of the country you want to filter.
See the list of supported countries
max 10 This parameter allows you to specify the number of news articles returned by the API. The minimum value of this parameter is 1 and the maximum value is 100. The value you can set depends on your subscription.
See the pricing for more information
nullable None This parameter allows you to specify the attributes that you allow to return null values. The attributes that can be set are title, description and content. It is possible to combine several attributes by separating them with a comma.
e.g. title,description
from None This parameter allows you to filter the articles that have a publication date greater than or equal to the specified value. The date must respect the following format:
YYYY-MM-DDThh:mm:ssTZD
TZD = time zone designator, its value must always be Z (universal time)
e.g. 2022-08-21T16:27:09Z
to None This parameter allows you to filter the articles that have a publication date smaller than or equal to the specified value. The date must respect the following format:
YYYY-MM-DDThh:mm:ssTZD
TZD = time zone designator, its value must always be Z (universal time)
e.g. 2022-08-21T16:27:09Z
q None This parameter allows you to specify your search keywords which allows you to narrow down the results. The keywords will be used to return the most relevant articles. It is possible to use logical operators with keywords, see the section on query syntax.
page 1 This parameter will only work if you have a paid subscription activated on your account.
This parameter allows you to control the pagination of the results returned by the API. The paging behavior is closely related to the value of the max parameter. The first page is page 1, then you have to increment by 1 to go to the next page. Let's say that the value of the max parameter is 10, then the first page will contain the first 10 articles returned by the API (articles 1 to 10), page 2 will return the next 10 articles (articles 11 to 20), the behavior extends to page 3, 4, ...
expand None This parameter will only work if you have a paid subscription activated on your account.
This parameter allows you to return in addition to other data, the full content of the articles. To get the full content of the articles, the parameter must be set to content

Languages

The following languages are supported by the API (to used with the lang parameter):

Name Value
Arabic ar
Chinese zh
Dutch nl
English en
French fr
German de
Greek el
Hebrew he
Hindi hi
Italian it
Japanese ja
Malayalam ml
Marathi mr
Norwegian no
Portuguese pt
Romanian ro
Russian ru
Spanish es
Swedish sv
Tamil ta
Telugu te
Ukrainian uk

Countries

The following countries are supported by the API (to used with the country parameter):

Name Value
Australia au
Brazil br
Canada ca
China cn
Egypt eg
France fr
Germany de
Greece gr
Hong Kong hk
India in
Ireland ie
Israel il
Italy it
Japan jp
Netherlands nl
Norway no
Pakistan pk
Peru pe
Philippines ph
Portugal pt
Romania ro
Russian Federation ru
Singapore sg
Spain es
Sweden se
Switzerland ch
Taiwan tw
Ukraine ua
United Kingdom gb
United States us

Errors

The API uses the following error codes:

Error Code Meaning
400 Bad Request -- Your request is invalid.
401 Unauthorized -- Your API key is wrong.
403 Forbidden -- You have reached your daily quota, the next reset is at 00:00 UTC.
429 Too Many Requests -- You have made more requests per second than you are allowed.
500 Internal Server Error -- We had a problem with our server. Try again later.
503 Service Unavailable -- We're temporarily offline for maintenance. Please try again later.