The News API can be used in a variety of ways. We’ve put together some sample workflows and handy code snippets to help you get the most out of the solution:

Real-time monitoring

Real-time monitoring enables you to pull stories in real-time, as they are published, based on your specific search query. This may be of particular interest to users who rely on having the latest stories as soon as they are published, such as news tickers for example.

Newly published stories will be pulled every minute, and duplicates in subsequent searches will be ignored, to ensure you are only getting the most recent publications, rather than a repeat of what has come before.

For more information on using this feature, take a look at our blog post introducing the feature.

Examples

The following example shows how to pull stories that contain any of the following terms in the title: Apple OR Amazon OR Facebook OR PayPal OR Microsoft OR Ebay OR Cisco OR Netflix OR IBM.

var AylienNewsApi = require('aylien-news-api');
var Promise = require('bluebird');

// Async Promise "while loop"
function promiseWhile(condition, action) {
  var resolver = Promise.defer();

  var loop = function() {
    if (!condition()) return resolver.resolve();
    return Promise.cast(action())
      .then(loop)
      .catch(resolver.reject);
  };

  process.nextTick(loop);

  return resolver.promise;
}

// Async Promise "sleep"
function sleep(time){
  return new Promise((resolve) => setTimeout(resolve, time));
}

function fetchNewStories(opts){
  console.log('-------------');

  return new Promise(function (resolve, reject){
    var fetchedStories = [];
    var stories = null;
    var whileCondition = function(){
      return (stories == null || stories.length > 0);
    };

    promiseWhile(whileCondition, function(){
      return new Promise(function (resolve, reject){
        apiInstance.listStories(opts, function(error, data, response){
          if (error){
            if (response.status == 429) {
              console.log('Usage limit are exceeded. Wating for 60 seconds...');
              sleep(60 * 1000).then(function(){
                resolve();
              });
            } else {
              reject(error);
            }
          } else {
            opts.cursor = data.nextPageCursor;
            stories = data.stories;

            fetchedStories = fetchedStories.concat(stories);

            console.log("Fetched " + stories.length +
              " stories. Total story count so far: " + fetchedStories.length);

            resolve();
          }
        });
      });
    }).then(function(){
      resolve(fetchedStories);
    });
  });
}


var apiInstance = new AylienNewsApi.DefaultApi();

// Configure API key authorization: app_id
var app_id = apiInstance.apiClient.authentications['app_id'];
app_id.apiKey = "YOUR_APP_ID";

// Configure API key authorization: app_key
var app_key = apiInstance.apiClient.authentications['app_key'];
app_key.apiKey = "YOUR_APP_KEY";

var opts = {
  'title': 'Apple OR Amazon OR Facebook OR PayPal OR Microsoft OR Ebay OR Cisco OR Netflix OR IBM',
  'language': ['en'],
  'publishedAtStart': 'NOW-1HOUR',
  'publishedAtEnd': 'NOW',
  'cursor': '*',
  'perPage': 5,
  'sortBy': 'published_at',
  'sortDirection': 'desc'
};

var whileCondition = function(){ return true; };

promiseWhile(whileCondition, function(){
  return new Promise(function (resolve, reject){
    fetchNewStories(opts).then(function(stories){
      console.log('**************');
      console.log('Fetched ' + stories.length +
        ' stories which were published between ' + opts['publishedAtStart'] +
        ' and ' + opts['publishedAtEnd']);

      if (stories.length > 0) {
        var newFetchAt = stories[0].publishedAt.getTime() + 1000;
        opts['publishedAtStart'] = new Date(newFetchAt);
        opts['cursor'] = '*';
      }

      console.log("Sleep for 60 seconds until next poll...");
      console.log('-------------n');
      sleep(60 * 1000).then(function(){
        resolve();
      });
    });
  });
});
import time
import datetime
import aylien_news_api
from aylien_news_api.rest import ApiException

def fetch_new_stories(params={}):
  print('------------')

  fetched_stories = []
  stories = None

  while stories is None or len(stories) > 0:
    try:
      response = api_instance.list_stories(**params)
    except ApiException as e:
      if ( e.status == 429 ):
        print('Usage limit are exceeded. Wating for 60 seconds...')
        time.sleep(60)
        continue

    stories = response.stories
    params['cursor'] = response.next_page_cursor

    fetched_stories += stories
    print("Fetched %d stories. Total story count so far: %d" %
      (len(stories), len(fetched_stories)))

  return fetched_stories


# Configure API key authorization: app_id
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'
# Configure API key authorization: app_key
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'

# create an instance of the API class
api_instance = aylien_news_api.DefaultApi()

params = {
  'title': 'Apple OR Amazon OR Facebook OR PayPal OR Microsoft OR Ebay OR Cisco OR Netflix OR IBM',
  'language': ['en'],
  'published_at_start': 'NOW-1HOUR',
  'published_at_end': 'NOW',
  'cursor': '*',
  'per_page': 5,
  'sort_by': 'published_at',
  'sort_direction': 'desc'
}

while True:
  stories = fetch_new_stories(params)

  print('************')
  print("Fetched %d stories which were published between %s and %s" %
    (len(stories), params['published_at_start'], params['published_at_end']))

  if len(stories) > 0:
    last_fetched_at = stories[0].published_at + datetime.timedelta(seconds=1)
    params['published_at_start'] = last_fetched_at.isoformat()[:-6] + 'Z'
    params['cursor'] = '*'

  print('Sleep for 60 seconds until next poll...')
  print('------------')
  time.sleep(60)
<?php
require_once(__DIR__ . '/vendor/autoload.php');

function fetch_new_stories($opts){
  print_r("-----------\n");

  global $api_instance;

  $fetched_stories = [];
  $stories = NULL;

  while (is_null($stories) || count($stories) > 0) {
    try {
      $result = $api_instance->listStories($opts);
    } catch (Exception $e) {
      $code = $e->getResponseObject()->getErrors()[0]->getStatus();

      if ($code == '429'){
        print_r("Usage limit are exceeded. Wating for 60 seconds...\n");
        sleep(60);
        continue;
      }
    }

    $stories = $result->getStories();
    $fetched_stories = array_merge($fetched_stories, $stories);
    $opts['cursor'] = $result->getNextPageCursor();

    print_r(sprintf("Fetched %d stories. Total story count so far: %d\n",
      count($stories), count($fetched_stories)));
  }

  return $fetched_stories;
}


// Configure API key authorization: app_id
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-ID', 'YOUR_APP_ID');

// Configure API key authorization: app_key
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-Key', 'YOUR_APP_KEY');

$api_instance = new Aylien\NewsApi\Api\DefaultApi();

$params = array(
  'title' => 'Apple OR Amazon OR Facebook OR PayPal OR Microsoft OR Ebay OR Cisco OR Netflix OR IBM',
  'published_at_start' => 'NOW-1HOUR',
  'published_at_end' => 'NOW',
  'language' => ['en'],
  'per_page' => 5,
  'sort_by' => 'published_at',
  'sort_direction' => 'desc'
);

while(true){
  $stories = fetch_new_stories($params);

  print_r("************\n");
  print_r(sprintf("Fetched %d stories which were published between %s and %s\n",
    count($stories), $params['published_at_start'], $params['published_at_end']));

  if (count($stories) > 0){
    $lastFetchedAt = $stories[0]->getPublishedAt()->add(new DateInterval('PT10S'));

    $params['cursor'] = '*';
    $params['published_at_start'] = $lastFetchedAt->format('Y-m-d\TH:i:s\Z');
  }

  print_r("Sleep for 60 seconds until next poll...\n");
  print_r("-----------\n\n");

  sleep(60);
}
?>
import com.aylien.newsapi.ApiClient;
import com.aylien.newsapi.ApiException;
import com.aylien.newsapi.Configuration;
import com.aylien.newsapi.api.DefaultApi;
import com.aylien.newsapi.auth.ApiKeyAuth;
import com.aylien.newsapi.models.Stories;
import com.aylien.newsapi.models.Story;
import com.aylien.newsapi.parameters.StoriesParams;
import org.joda.time.DateTime;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ApiClient defaultClient = Configuration.getDefaultApiClient();

        // Configure API key authorization: app_id
        ApiKeyAuth app_id = (ApiKeyAuth) defaultClient.getAuthentication("app_id");
        app_id.setApiKey("YOUR_APP_ID");

        // Configure API key authorization: app_key
        ApiKeyAuth app_key = (ApiKeyAuth) defaultClient.getAuthentication("app_key");
        app_key.setApiKey("YOUR_APP_KEY");

        DefaultApi apiInstance = new DefaultApi();

        StoriesParams.Builder storiesBuilder = StoriesParams.newBuilder();

        storiesBuilder.setTitle("Apple OR Amazon OR Facebook OR PayPal OR Microsoft OR Ebay OR Cisco OR Netflix OR IBM");
        storiesBuilder.setLanguage(Arrays.asList("en"));
        storiesBuilder.setPublishedAtStart("NOW-1HOUR");
        storiesBuilder.setPublishedAtEnd("NOW");
        storiesBuilder.setCursor("*");
        storiesBuilder.setPerPage(5);
        storiesBuilder.setSortBy("published_at");
        storiesBuilder.setSortDirection("desc");

        while (true) {
            StoriesParams storiesParams = storiesBuilder.build();

            List stories = fetchNewStories(apiInstance, storiesBuilder);

            System.out.println("*****************");
            System.out.format("Fetched %d stories which were published between %s and %sn",
                    stories.size(), storiesParams.getPublishedAtStart(), storiesParams.getPublishedAtEnd());

            if (stories.size() > 0) {
                DateTime lastFetchedAt = stories.get(0).getPublishedAt().plusSeconds(1);
                storiesBuilder.setPublishedAtStart(lastFetchedAt.toDateTimeISO().toString());
                storiesBuilder.setCursor("*");
            }

            System.out.println("Sleep for 60 seconds until next poll...");
            System.out.println("--------------");
            try {
                Thread.sleep(1000 * 60);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static List fetchNewStories(DefaultApi apiInstance, StoriesParams.Builder storiesParams) {
        System.out.println("--------------");

        List fetchedStories = new ArrayList();
        List stories = null;

        while (stories == null || stories.size() > 0) {
            try {
                Stories storiesResponse = apiInstance.listStories(storiesParams.build());
                stories = storiesResponse.getStories();
                storiesParams.setCursor(storiesResponse.getNextPageCursor());

                fetchedStories.addAll(stories);

                System.out.format("Fetched %d stories. Total story count so far: %dn",
                        stories.size(), fetchedStories.size());
            } catch (ApiException e) {
                if (e.getCode() == 429) {
                    System.out.println("Usage limit are exceeded. Wating for 60 seconds...");
                    try {
                        Thread.sleep(1000 * 60);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                    continue;
                }
            }
        }

        return fetchedStories;
    }
}
# Load the gem
require 'aylien_news_api'
require 'time'

def fetch_new_stories(params={})
  puts "------------"

  fetched_stories = []
  stories = nil

  while stories.nil? || stories.size > 0
    begin
      result = $api_instance.list_stories(params)
    rescue AylienNewsApi::ApiError => e
      if e.code == 429
        puts 'Usage limit are exceeded. Wating for 60 seconds...'
        sleep(60)
        retry
      end
    end

    stories = result.stories
    params[:cursor] = result.next_page_cursor

    fetched_stories += stories
    puts "Fetched #{stories.size} stories. Total story count so far: #{fetched_stories.size}"
  end

  fetched_stories
end

# Setup authorization
AylienNewsApi.configure do |config|
  # Configure API key authorization: app_id
  config.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'

  # Configure API key authorization: app_key
  config.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'
end

# create an instance of the API class
$api_instance = AylienNewsApi::DefaultApi.new

opts = {
  :title => "Apple OR Amazon OR Facebook OR PayPal OR Microsoft OR Ebay OR Cisco OR Netflix OR IBM",
  :language => ['en'],
  :published_at_start => 'NOW-1HOUR',
  :published_at_end => 'NOW',
  :cursor => '*',
  :per_page => 5,
  :sort_by => "published_at",
  :sort_direction => "desc"
}

while true do
  stories = fetch_new_stories(opts)

  puts "*"*80
  puts "Fetched #{stories.size} stories which "
    "were published between #{opts[:published_at_start]} and #{opts[:published_at_end]}"

  if stories.size > 0
    last_fetched_at = stories[0].published_at + Rational(1, 86400)
    opts[:published_at_start] = last_fetched_at.to_time.utc.iso8601
    opts[:cursor] = "*"
  end

  puts "Sleep for 60 seconds until next poll..."
  puts "------------nn"

  sleep(60)
end
package main

// Import the library
import (
  "fmt"
  newsapi "github.com/AYLIEN/aylien_newsapi_go"
  "time"
)

func main() {
  api := newsapi.NewDefaultApi()

  // Configure API key authorization: app_id
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-ID"] = "YOUR_APP_ID"

  // Configure API key authorization: app_key
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-Key"] = "YOUR_APP_KEY"

  storiesParams := &newsapi.StoriesParams{
    Title:            "Apple OR Amazon OR Facebook OR PayPal OR Microsoft OR Ebay OR Cisco OR Netflix OR IBM",
    Language:         []string{"en"},
    PublishedAtStart: "NOW-1HOUR",
    PublishedAtEnd:   "NOW",
    Cursor:           "*",
    PerPage:          5,
    SortBy:           "published_at",
    SortDirection:    "desc"}

  for {
    stories := fetchNewStories(api, storiesParams)

    fmt.Println("***************")
    fmt.Printf("Fetched %d stories which were published between %s and %sn",
      len(stories), storiesParams.PublishedAtStart, storiesParams.PublishedAtEnd)

    if len(stories) > 0 {
      lastFetchedAt := stories[0].PublishedAt.Add(time.Duration(1) * time.Second)
      storiesParams.PublishedAtStart = lastFetchedAt.Format("2006-01-02T15:04:05Z")
      storiesParams.Cursor = "*"
    }

    fmt.Println("Sleep for 60 seconds until next poll...")
    fmt.Println("------------")
    time.Sleep(time.Duration(60) * time.Second)
  }
}

func fetchNewStories(apiInstance *newsapi.DefaultApi, params *newsapi.StoriesParams) []newsapi.Story {
  fmt.Println("---------------")

  var fetchedStories []newsapi.Story
  var stories []newsapi.Story
  isFirstCall := true

  for isFirstCall || len(stories) > 0 {
    storiesResponse, res, err := apiInstance.ListStories(params)
    if err != nil {
      panic(err)
    }

    if res.Response.StatusCode == 429 {
      fmt.Println("Usage limit are exceeded. Wating for 60 seconds...")
      time.Sleep(time.Duration(60) * time.Second)
      continue
    }

    isFirstCall = false
    stories = storiesResponse.Stories
    params.Cursor = storiesResponse.NextPageCursor

    fetchedStories = append(fetchedStories, stories...)

    fmt.Printf("Fetched %d stories. Total story count so far: %dn", len(stories), len(fetchedStories))
  }

  return fetchedStories
}
using System;
using Aylien.NewsApi.Api;
using Aylien.NewsApi.Client;
using Aylien.NewsApi.Model;
using System.Collections.Generic;

namespace RealTimeMonitoring
{
    class Program
    {
        static DefaultApi apiInstance;

        static void Main(string[] args)
        {
            // Configure API key authorization: app_id
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-ID", "YOUR_APP_ID");

            // Configure API key authorization: app_key
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-Key", "YOUR_APP_KEY");

            apiInstance = new DefaultApi();
            var publishedAtStart = "NOW-1HOUR";
            var publishedAtEnd = "NOW";

            while (true)
            {
                var stories = FetchNewStories(publishedAtStart, publishedAtEnd);

                Console.WriteLine("*****************");
                Console.WriteLine(string.Format("Fetched {0} stories which were published between {1} and {2}",
                    stories.Count, publishedAtStart, publishedAtEnd));

                if (stories.Count > 0)
                {
                    var lastFetchedAt = stories[0].PublishedAt.Value.AddSeconds(1);
                    publishedAtStart = lastFetchedAt.ToString("yyyy-MM-ddTHH:mm:ssZ");
                }

                Console.WriteLine("Sleep for 60 seconds until next poll...");
                Console.WriteLine("------------");
                System.Threading.Thread.Sleep(1000 * 60);
            }
        }

        static List FetchNewStories(String publishedAtStart, String publishedAtEnd)
        {
            Console.WriteLine("--------------------");

            var cursor = "*";
            var fetchedStories = new List();
            List stories = null;

            while (stories == null || stories.Count > 0)
            {
                try
                {
                    var storiesResponse = apiInstance.ListStoriesWithHttpInfo(
                        title: "Apple OR Amazon OR Facebook OR PayPal OR Microsoft OR Ebay OR Cisco OR Netflix OR IBM",
                        language: new List { "en" },
                        publishedAtStart: publishedAtStart,
                        publishedAtEnd: publishedAtEnd,
                        cursor: cursor,
                        perPage: 5,
                        sortBy: "published_at",
                        sortDirection: "desc"
                    );


                    stories = storiesResponse.Data._Stories;
                    cursor = storiesResponse.Data.NextPageCursor;
                    fetchedStories.AddRange(stories);

                    Console.WriteLine(string.Format("Fetched {0} stories. Total story count so far: {1}",
                        stories.Count, fetchedStories.Count));
                }
                catch (ApiException e)
                {
                    if (e.ErrorCode == 429)
                    {
                        Console.WriteLine("Usage limit are exceeded. Wating for 60 seconds...");
                        System.Threading.Thread.Sleep(1000 * 60);
                    }
                    else
                    {
                        Console.WriteLine("Exception when calling DefaultApi.ListStories: " + e.Message);
                    }

                }
            }
            return fetchedStories;
        }
    }
}

Pagination of Results

This workflow allows you to decide how the results of a search are split into multiple pages on your UI. This is important because most end-users of any application won't scroll through many pages of results.

Fetching a Large Number of Sorted Results: Cursor

The API supports using a cursor to scan through results. In the API, a cursor is a logical concept that doesn't cache any state information on the server. Instead, the sort values of the last story returned to the client are used to compute a next_page_cursor, representing a logical point in the ordered space of sort values. That next_page_cursor can be specified in the parameters of subsequent requests to tell the API where to continue.

Using a Cursor

To use a cursor with the API, specify a cursor parameter with the value of *. This is the same as declaring page=1 to tell the API "start at the beginning of my sorted results," except it also informs the API that you want to use a cursor. The default value of cursor is * unless you specify otherwise. In addition to returning the top N sorted results (where you can control N using the per_page parameter) the API response will also include an encoded String named next_page_cursor.

You then take the next_page_cursor String value from the response, and pass it back to the API as the cursor parameter for your next request. You can repeat this process until you've fetched as many stories as you want, or until the next_page_cursor returns matches the cursor you've already specified — indicating that there are no more results.

Using the Per Page Attribute

The API supports using a per_page to specify the maximum number of stories per page. This parameter is used to paginate results from a query. The possible value for this parameter is between 1 to 100.

Examples

The following example shows how to retrieve all stories in English, that are about Sports and were published between 1 hour ago and now.

var AylienNewsApi = require('aylien-news-api');
var Promise = require('bluebird');

// Async Promise "while loop"
function promiseWhile(condition, action) {
  var resolver = Promise.defer();

  var loop = function() {
    if (!condition()) return resolver.resolve();
    return Promise.cast(action())
      .then(loop)
      .catch(resolver.reject);
  };

  process.nextTick(loop);

  return resolver.promise;
}

// Async Promise "sleep"
function sleep(time){
  return new Promise((resolve) => setTimeout(resolve, time));
}

function fetchNewStories(opts){
  return new Promise(function (resolve, reject){
    var fetchedStories = [];
    var stories = null;
    var whileCondition = function(){
      return (stories == null || stories.length > 0);
    };

    promiseWhile(whileCondition, function(){
      return new Promise(function (resolve, reject){
        apiInstance.listStories(opts, function(error, data, response){
          if (error){
            if (response.status == 429) {
              console.log('Usage limit are exceeded. Wating for 30 seconds...');
              sleep(30 * 1000).then(function(){
                resolve();
              });
            } else {
              reject(error);
            }
          } else {
            opts.cursor = data.nextPageCursor;
            stories = data.stories;

            fetchedStories = fetchedStories.concat(stories);

            console.log("Fetched " + stories.length +
              " stories. Total story count so far: " + fetchedStories.length);

            resolve();
          }
        });
      });
    }).then(function(){
      resolve(fetchedStories);
    });
  });
}


var apiInstance = new AylienNewsApi.DefaultApi();

// Configure API key authorization: app_id
var app_id = apiInstance.apiClient.authentications['app_id'];
app_id.apiKey = "YOUR_APP_ID";

// Configure API key authorization: app_key
var app_key = apiInstance.apiClient.authentications['app_key'];
app_key.apiKey = "YOUR_APP_KEY";

var opts = {
  'language': ['en'],
  'publishedAtStart': 'NOW-1HOUR',
  'publishedAtEnd': 'NOW', 
  'categoriesTaxonomy': 'iab-qag',
  'categoriesId': ['IAB17'],
  'cursor': '*',
  'perPage': 16
};

fetchNewStories(opts).then(function(stories){
  console.log('**************');
  console.log('Fetched ' + stories.length +
    ' stories which are in English, are about Sports and were' +
    ' published between 1 hour ago and now');
});
import time
import aylien_news_api
from aylien_news_api.rest import ApiException

def fetch_new_stories(params={}):
  fetched_stories = []
  stories = None

  while stories is None or len(stories) > 0:
    try:
      response = api_instance.list_stories(**params)
    except ApiException as e:
      if ( e.status == 429 ):
        print('Usage limit are exceeded. Wating for 60 seconds...')
        time.sleep(60)
        continue

    stories = response.stories
    params['cursor'] = response.next_page_cursor

    fetched_stories += stories
    print("Fetched %d stories. Total story count so far: %d" %
      (len(stories), len(fetched_stories)))

  return fetched_stories

# Configure API key authorization: app_id
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'
# Configure API key authorization: app_key
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'

# create an instance of the API class
api_instance = aylien_news_api.DefaultApi()

params = {
  'language': ['en'],
  'published_at_start': 'NOW-1HOUR',
  'published_at_end': 'NOW',
  'categories_taxonomy': 'iab-qag',
  'categories_id': ['IAB17'],
  'cursor': '*',
  'per_page': 16
}

stories = fetch_new_stories(params)

print('************')
print("Fetched %d stories which are in English, are 
about Sports and were published between %s and %s" %
(len(stories), params['published_at_start'], params['published_at_end']))
<?php
require_once(__DIR__ . '/vendor/autoload.php');

function fetch_new_stories($opts){
  global $api_instance;

  $fetched_stories = [];
  $stories = NULL;

  while (is_null($stories) || count($stories) > 0) {
    try {
      $result = $api_instance->listStories($opts);
    } catch (Exception $e) {
      $code = $e->getResponseObject()->getErrors()[0]->getStatus();

      if ($code == '429'){
        print_r("Usage limit are exceeded. Wating for 30 seconds...\n");
        sleep(30);
        continue;
      }
    }

    $stories = $result->getStories();
    $fetched_stories = array_merge($fetched_stories, $stories);
    $opts['cursor'] = $result->getNextPageCursor();

    print_r("Fetched " . count($stories) . 
      " stories. Total story count so far: " . count($fetched_stories) . "\n");
  }

  return $fetched_stories;
}


// Configure API key authorization: app_id
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-ID', 'YOUR_APP_ID');

// Configure API key authorization: app_key
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-Key', 'YOUR_APP_KEY');

$api_instance = new Aylien\NewsApi\Api\DefaultApi();

$params = array(
  'published_at_start' => 'NOW-1HOUR',
  'published_at_end' => 'NOW',
  'language' => ['en'],
  'categories_taxonomy' => 'iab-qag',
  'categories_id' => ['IAB17'],
  'per_page' => 16
);

$stories = fetch_new_stories($params);

print_r("************\n");
print('Fetched ' . count($stories) . 
  " stories which are in English, are about Sports and were published between 1 hour ago and now\n");
?>
import com.aylien.newsapi.ApiClient;
import com.aylien.newsapi.ApiException;
import com.aylien.newsapi.Configuration;
import com.aylien.newsapi.api.DefaultApi;
import com.aylien.newsapi.auth.ApiKeyAuth;
import com.aylien.newsapi.models.Stories;
import com.aylien.newsapi.models.Story;
import com.aylien.newsapi.parameters.StoriesParams;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ApiClient defaultClient = Configuration.getDefaultApiClient();

        // Configure API key authorization: app_id
        ApiKeyAuth app_id = (ApiKeyAuth) defaultClient.getAuthentication("app_id");
        app_id.setApiKey("YOUR_APP_ID");

        // Configure API key authorization: app_key
        ApiKeyAuth app_key = (ApiKeyAuth) defaultClient.getAuthentication("app_key");
        app_key.setApiKey("YOUR_APP_KEY");

        DefaultApi apiInstance = new DefaultApi();

        StoriesParams.Builder storiesBuilder = StoriesParams.newBuilder();

        storiesBuilder.setLanguage(Arrays.asList("en"));
        storiesBuilder.setPublishedAtStart("NOW-1HOUR");
        storiesBuilder.setPublishedAtEnd("NOW");
        storiesBuilder.setCategoriesTaxonomy("iab-qag");
        storiesBuilder.setCategoriesId(Arrays.asList("IAB17"));
        storiesBuilder.setCursor("*");
        storiesBuilder.setPerPage(16);

        List stories = fetchNewStories(apiInstance, storiesBuilder);

        StoriesParams storiesParams = storiesBuilder.build();
        System.out.println("*****************");
        System.out.format("Fetched %d stories which are in English, are about Sports and were published between %s and %sn",
                stories.size(), storiesParams.getPublishedAtStart(), storiesParams.getPublishedAtEnd());
    }

    public static List fetchNewStories(DefaultApi apiInstance, StoriesParams.Builder storiesParams) {
        List fetchedStories = new ArrayList();
        List stories = null;

        while (stories == null || stories.size() > 0) {
            try {
                Stories storiesResponse = apiInstance.listStories(storiesParams.build());
                stories = storiesResponse.getStories();
                storiesParams.setCursor(storiesResponse.getNextPageCursor());

                fetchedStories.addAll(stories);

                System.out.format("Fetched %d stories. Total story count so far: %dn",
                        stories.size(), fetchedStories.size());
            } catch (ApiException e) {
                if (e.getCode() == 429) {
                    System.out.println("Usage limit are exceeded. Wating for 60 seconds...");
                    try {
                        Thread.sleep(1000 * 60);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                    continue;
                }
            }
        }

        return fetchedStories;
    }
}
# Load the gem
require 'aylien_news_api'

def fetch_new_stories(params={})
  fetched_stories = []
  stories = nil

  while stories.nil? || stories.size > 0
    begin
      result = $api_instance.list_stories(params)
    rescue AylienNewsApi::ApiError => e
      if e.code == 429
        puts 'Usage limit are exceeded. Wating for 30 seconds...'
        sleep(30)
        retry
      end
    end

    stories = result.stories
    params[:cursor] = result.next_page_cursor

    fetched_stories += stories
    puts "Fetched #{stories.size} stories. Total story count so far: #{fetched_stories.size}"
  end

  fetched_stories
end

# Setup authorization
AylienNewsApi.configure do |config|
  # Configure API key authorization: app_id
  config.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'

  # Configure API key authorization: app_key
  config.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'
end

# create an instance of the API class
$api_instance = AylienNewsApi::DefaultApi.new

opts = {
  :language => ['en'],
  :published_at_start => 'NOW-1HOUR',
  :published_at_end => 'NOW',
  :categories_taxonomy => 'iab-qag',
  :categories_id => ['IAB17'],
  :cursor => '*',
  :per_page => 16
}

stories = fetch_new_stories(opts)

puts "*"*80
puts "Fetched #{stories.size} stories which are "
  "in English, are about Sports and were published between 1 hour ago and now"
package main

// Import the library
import (
  "fmt"
  newsapi "github.com/AYLIEN/aylien_newsapi_go"
  "time"
)

func main() {
  api := newsapi.NewDefaultApi()

  // Configure API key authorization: app_id
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-ID"] = "YOUR_APP_ID"

  // Configure API key authorization: app_key
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-Key"] = "YOUR_APP_KEY"

  storiesParams := &newsapi.StoriesParams{
    Language:           []string{"en"},
    PublishedAtStart:   "NOW-1HOUR",
    PublishedAtEnd:     "NOW",
    CategoriesTaxonomy: "iab-qag",
    CategoriesId:       []string{"IAB17"},
    Cursor:             "*",
    PerPage:            16}

  stories := fetchNewStories(api, storiesParams)

  fmt.Println("***************")
  fmt.Printf("Fetched %d stories which are in English, are about Sports and were published between %s and %sn",
    len(stories), storiesParams.PublishedAtStart, storiesParams.PublishedAtEnd)
}

func fetchNewStories(apiInstance *newsapi.DefaultApi, params *newsapi.StoriesParams) []newsapi.Story {
  var fetchedStories []newsapi.Story
  var stories []newsapi.Story
  isFirstCall := true

  for isFirstCall || len(stories) > 0 {
    storiesResponse, res, err := apiInstance.ListStories(params)
    if err != nil {
      panic(err)
    }

    if res.Response.StatusCode == 429 {
      fmt.Println("Usage limit are exceeded. Wating for 60 seconds...")
      time.Sleep(time.Duration(60) * time.Second)
      continue
    }

    isFirstCall = false
    stories = storiesResponse.Stories
    params.Cursor = storiesResponse.NextPageCursor

    fetchedStories = append(fetchedStories, stories...)

    fmt.Printf("Fetched %d stories. Total story count so far: %dn",
      len(stories), len(fetchedStories))
  }

  return fetchedStories
}
using System;
using Aylien.NewsApi.Api;
using Aylien.NewsApi.Client;
using Aylien.NewsApi.Model;
using System.Collections.Generic;

namespace ResultsPagination
{
    class Program
    {
        static DefaultApi apiInstance;

        static void Main(string[] args)
        {
            // Configure API key authorization: app_id
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-ID", "YOUR_APP_ID");

            // Configure API key authorization: app_key
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-Key", "YOUR_APP_KEY");

            apiInstance = new DefaultApi();
            var publishedAtStart = "NOW-1HOUR";
            var publishedAtEnd = "NOW";

            var stories = FetchNewStories(publishedAtStart, publishedAtEnd);
            Console.WriteLine("*****************");
            Console.WriteLine(string.Format("Fetched {0} stories which are in English, are about Sports and were published between {1} and {2}",
                    stories.Count, publishedAtStart, publishedAtEnd));
        }

        static List FetchNewStories(String publishedAtStart, String publishedAtEnd)
        {
            var cursor = "*";
            var fetchedStories = new List();
            List stories = null;

            while (stories == null || stories.Count > 0)
            {
                try
                {
                    var storiesResponse = apiInstance.ListStories(
                        language: new List { "en" },
                        publishedAtStart: publishedAtStart,
                        publishedAtEnd: publishedAtEnd,
                        categoriesTaxonomy: "iab-qag",
                        categoriesId: new List { "IAB17" },
                        cursor: cursor,
                        perPage: 16
                    );

                    stories = storiesResponse._Stories;
                    cursor = storiesResponse.NextPageCursor;
                    fetchedStories.AddRange(stories);

                    Console.WriteLine(string.Format("Fetched {0} stories. Total story count so far: {1}",
                        stories.Count, fetchedStories.Count));
                }
                catch (ApiException e)
                {
                    if (e.ErrorCode == 429)
                    {
                        Console.WriteLine("Usage limit are exceeded. Wating for 60 seconds...");
                        System.Threading.Thread.Sleep(1000 * 60);
                    }
                    else
                    {
                        Console.WriteLine("Exception when calling DefaultApi.ListStories: " + e.Message);
                    }

                }
            }
            return fetchedStories;
        }
    }
}

Sorting Results

You can choose how you want your results to be sorted by using the sort_by parameter. This allows you to receive the most relevant results of your query first, with relevance based on a value you choose as a parameter.

The sort_by parameter can take one of the following values:

Relevance

Using the relevance value returns the stories that most closely matches your search input. The parameter value is relevance.

Recency

There are two ways of sorting your results by recency:

  • Using the recency value gives a higher rank to stories that were published more recently but also gives weight to your query too.
  • Using published_at as the value here will rank your results based only on how recently your returned stores were published.

Hotness

Using the hotness value gives a higher rank to stories that were published more recently but also gives weight to social media sharing, inbound links, and Alexa ranking.

Social Media shares

It is possible to sort your results by the following Social Media-based metrics:

  • Shares on Facebook (social_shares_count.facebook)
  • Shares on LinkedIn (social_shares_count.linkedin)
  • Upvotes on Reddit (social_shares_count.reddit)
  • Shares on Google Plus (social_shares_count.google_plus)
  • Total number of shares on all the above networks (social_shares_count)

Number of photos

This value allows users to rank results based on the number of photos on the page. The parameter value is media.images.count.

Number of videos

This value allows users to rank results based on the number of videos on the page. The parameter value is media.videos.count.

Alexa ranking

Alexa is a ranking system that ranks websites based on the volume of traffic they have generated over the previous 3 months. The more traffic a website receives, the higher its ranking. For example, Google.com has a ranking of 1, BBC.co.uk has a ranking of around 100, and so on. Alexa gives two options to users when seeking the ranking of sites:

  • Global ranking, based on how popular a website is globally
  • National ranking, based on how popular a site is in a given country. This is available for every country in the world, and is accessed by adding the ISO 3166-1 alpha-2 country code to your parameter. For more information, take a look at our page on working with Alexa rankings.

Each of the parameters above can sort results by ascending or descending value. This is achieved by entering either asc or desc as a value of the sort_direction parameter. If this parameter is not declared, results will be returned in descending order.

Examples

The code below gathers stories that mention baseball from the last month and sorts them according to their Alexa ranking in the US from high to low.

var AylienNewsApi = require('aylien-news-api');

var apiInstance = new AylienNewsApi.DefaultApi();

// Configure API key authorization: app_id
var app_id = apiInstance.apiClient.authentications['app_id'];
app_id.apiKey = "YOUR_APP_ID";

// Configure API key authorization: app_key
var app_key = apiInstance.apiClient.authentications['app_key'];
app_key.apiKey = "YOUR_APP_KEY";

var opts = {
  'language': ['en'],
  'entitiesBodyLinksDbpedia': [
    'http://dbpedia.org/resource/Baseball'
  ],
  'categoriesTaxonomy': 'iab-qag',
  'categoriesId': ['IAB17'],
  'publishedAtStart': 'NOW-1MONTH',
  'publishedAtEnd': 'NOW',
  'sortBy': 'source.rankings.alexa.rank.US'
};

var callback = function(error, data, response) {
  if (error) {
    console.error(error);
  } else {
    console.log('The API has been called successfully.');
    console.log('=====================================');
    for (var i = 0; i < data.stories.length; i++){
      console.log(data.stories[i].title + " / " + data.stories[i].source.name);
    }
  }
};
apiInstance.listStories(opts, callback);
import aylien_news_api
from aylien_news_api.rest import ApiException

# Configure API key authorization: app_id
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'
# Configure API key authorization: app_key
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'

# create an instance of the API class
api_instance = aylien_news_api.DefaultApi()

opts = {
  'sort_by': 'source.rankings.alexa.rank.US',
  'language': ['en'],
  'published_at_start': 'NOW-1MONTH',
  'published_at_end': 'NOW',
  'entities_body_links_dbpedia': [
    'http://dbpedia.org/resource/Baseball'
  ],
  'categories_taxonomy': 'iab-qag',
  'categories_id': ['IAB17']
}

try:
    # List stories
    api_response = api_instance.list_stories(**opts)
    print('The API has been called successfully.')
    print('=====================================')
    for story in api_response.stories:
      print(story.title + " / " + story.source.name)
except ApiException as e:
    print("Exception when calling DefaultApi->list_stories: %sn" % e)
<?php
require_once(__DIR__ . '/vendor/autoload.php');

// Configure API key authorization: app_id
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-ID', 'YOUR_APP_ID');

// Configure API key authorization: app_key
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-Key', 'YOUR_APP_KEY');

$api_instance = new Aylien\NewsApi\Api\DefaultApi();

$opts = array(
  'published_at_start' => 'NOW-1MONTH',
  'published_at_end' => 'NOW',
  'entities_body_links_dbpedia' => [
    'http://dbpedia.org/resource/Baseball'
  ],
  'categories_taxonomy' => 'iab-qag',
  'categories_id' => ['IAB17'],
  'language' => ['en'],
  'sort_by' => 'source.rankings.alexa.rank.US'
);

try {
    $result = $api_instance->listStories($opts);
    print_r("The API has been called successfully.\n");
    print_r("=====================================\n");
    for($i = 0; $i < sizeof($result->getStories()); $i++){
      print_r($result->getStories()[$i]->getTitle() . " / " .
        $result->getStories()[$i]->getSource()->getName() . "\n");
    }
} catch (Exception $e) {
    print_r($e->getResponseObject()->getErrors());
    echo 'Exception when calling DefaultApi->listStories: ', $e->getMessage(), "\n";
}
?>
import com.aylien.newsapi.*;
import com.aylien.newsapi.auth.*;
import com.aylien.newsapi.models.*;
import com.aylien.newsapi.parameters.*;
import com.aylien.newsapi.api.DefaultApi;

import java.util.*;

public class Main {

    public static void main(String[] args) {
        ApiClient defaultClient = Configuration.getDefaultApiClient();

        // Configure API key authorization: app_id
        ApiKeyAuth app_id = (ApiKeyAuth) defaultClient.getAuthentication("app_id");
        app_id.setApiKey("YOUR_APP_ID");

        // Configure API key authorization: app_key
        ApiKeyAuth app_key = (ApiKeyAuth) defaultClient.getAuthentication("app_key");
        app_key.setApiKey("YOUR_APP_KEY");

        DefaultApi apiInstance = new DefaultApi();

        StoriesParams.Builder storiesBuilder = StoriesParams.newBuilder();

        storiesBuilder.setSortBy("source.rankings.alexa.rank.US");
        storiesBuilder.setLanguage(Arrays.asList("en"));
        storiesBuilder.setPublishedAtStart("NOW-1MONTH");
        storiesBuilder.setPublishedAtEnd("NOW");
        storiesBuilder.setEntitiesBodyLinksDbpedia(Arrays.asList(
                "http://dbpedia.org/resource/Baseball"
        ));
        storiesBuilder.setCategoriesTaxonomy("iab-qag");
        storiesBuilder.setCategoriesId(Arrays.asList("IAB17"));

        try {
            Stories result = apiInstance.listStories(storiesBuilder.build());
            for (Iterator i = result.getStories().iterator(); i.hasNext();){
                Story story = i.next();
                System.out.println(story.getTitle() + " / " + story.getSource().getName());
            }
        } catch (ApiException e) {
            System.err.println("Exception when calling DefaultApi#listStories");
            e.printStackTrace();
        }
    }
}
# Load the gem
require 'aylien_news_api'

# Setup authorization
AylienNewsApi.configure do |config|
  # Configure API key authorization: app_id
  config.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'

  # Configure API key authorization: app_key
  config.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'
end

api_instance = AylienNewsApi::DefaultApi.new

opts = {
  :published_at_start => "NOW-1MONTH",
  :published_at_end => "NOW",
  :entities_body_links_dbpedia => [
    'http://dbpedia.org/resource/Baseball'
  ],
  :categories_taxonomy => 'iab-qag',
  :categories_id => ['IAB17'],
  :language => ['en'],
  :sort_by => 'source.rankings.alexa.rank.US'
}


begin
  #List stories
  result = api_instance.list_stories(opts)

  puts 'The API has been called successfully.'
  puts '====================================='
  result.stories.each do |story|
    puts "#{story.title} / #{story.source.name}"
  end
rescue AylienNewsApi::ApiError => e
  puts "Exception when calling DefaultApi->list_stories: #{e}"
  puts e.response_body
end
package main

// Import the library
import (
  "fmt"
  newsapi "github.com/AYLIEN/aylien_newsapi_go"
)

func main() {
  api := newsapi.NewDefaultApi()

  // Configure API key authorization: app_id
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-ID"] = "YOUR_APP_ID"

  // Configure API key authorization: app_key
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-Key"] = "YOUR_APP_KEY"

  storiesParams := &newsapi.StoriesParams{
    Language:                 []string{"en"},
    PublishedAtStart:         "NOW-1MONTH",
    PublishedAtEnd:           "NOW",
    EntitiesBodyLinksDbpedia: []string{"http://dbpedia.org/resource/Baseball"},
    CategoriesTaxonomy:       "iab-qag",
    CategoriesId:             []string{"IAB17"},
    SortBy:                   "source.rankings.alexa.rank.US"}

  storiesResponse, res, err := api.ListStories(storiesParams)
  if err != nil {
    panic(err)
  }
  _ = res

  for _, story := range storiesResponse.Stories {
    fmt.Println(story.Title, " / ", story.Source.Name)
  }
}
using System;
using Aylien.NewsApi.Api;
using Aylien.NewsApi.Client;
using Aylien.NewsApi.Model;
using System.Collections.Generic;

namespace SortingResultsExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Configure API key authorization: app_id
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-ID", "YOUR_APP_ID");

            // Configure API key authorization: app_key
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-Key", "YOUR_APP_KEY");

            var apiInstance = new DefaultApi();

            try
            {
                // List stories
                Stories storiesResponse = apiInstance.ListStories(
                    publishedAtStart: "NOW-1MONTH",
                    publishedAtEnd: "NOW",
                    language: new List { "en" },
                    entitiesBodyLinksDbpedia: new List {
                        "http://dbpedia.org/resource/Baseball"
                    },
                    categoriesTaxonomy: "iab-qag",
                    categoriesId: new List { "IAB17" },
                    sortBy: "source.rankings.alexa.rank.US"
                );

                foreach (var story in storiesResponse._Stories)
                {
                    Console.WriteLine(story.Title + " / " + story.Source.Name);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception when calling DefaultApi.ListStories: " + e.Message);
            }
        }
    }
}

Working with Entities

An "entity" or "named entity" is a thing with a name, a type and (optionally) a uniform resource identifier (URI), which is a url specifically for that entity that allows a computer to refer to it specifically. Any distinct person, organization, place or product could be considered an entity. The list doesn't end here; these are just 4 highly common types of entities.

To make the definition of entities clearer, let's consider the role of the word "apple" in the following sentences:

  • "Apple is a great source of vitamins."
  • "Apple was founded by Steve Jobs and Steve Wozniak."

In the first sentence, "apple" refers to the following entity:

  • Text (also called surface form): "Apple"
  • Name: Apple
  • Type: Fruit, Eukaryote, Plant, etc.
  • Unique identifier: http://dbpedia.org/resource/Apple

Whereas in the second sentence, "apple" represents a different entity:

  • Text: "Apple"
  • Name: Apple Inc.
  • Type: Company, Organization, etc.
  • Unique identifier: http://dbpedia.org/resource/Apple_Inc.

In the News API, we extract entities found in the title and the body of each individual story, and you can filter your search results in most endpoints based on these values.

Searching by Entities

Except for Autocompletes, all of our endpoints support the following attributes for filtering results by entities:

  • entities.title.text[]: List of surface forms for entities found in the story title
  • entities.title.type[]: List of types for entities found in the story title
  • entities.title.links.dbpedia[]: List of identifiers (DBpedia URI) for entities found in the story title
  • entities.body.text[]: List of surface forms for entities found in the story body
  • entities.body.type[]: List of types for entities found in the story body
  • entities.body.links.dbpedia[]: List of identifiers (DBpedia URI) for entities found in the story body

These parameters allow you to first decide where in the article (title or body) the desired entity(ies) should appear. Secondly, you can search based on entity names (e.g. "Apple" or "Kim Kardashian"), entity types (e.g. Person or College) and/or entity links (e.g. http://dbpedia.org/resource/Apple_Inc.).

DBpedia is a semantic web project that extracts structured information created as part of the Wikipedia project. Think of it as the structured counterpart of Wikipedia, where distinct entities are given URIs, and their attributes and relations to other entities are presented in a graph structure.

Using DBpedia links or URIs to refer to entities has several advantages. Most importantly, it enables the party presenting information and the party receiving information to ensure that they are referring to the same exact thing and eliminate ambiguity as they communicate with each other.

For instance if two well-known people share the same name (e.g. Michael Jackson), we could differentiate them by using their DBpedia identifiers: http://dbpedia.org/resource/Michael_Jackson for the entertainer and http://dbpedia.org/resource/Michael_Jackson_(basketball) for the basketball player.

While using the News API, if you wish to focus on a well-known entity, by using its DBpedia link you can clarify your intent unambiguously, to reduce the number of false positives.

Additionally, knowing the DBpedia link of an entity enables us to query DBpedia (or Freebase) to retrieve additional information about that entity. For instance, to retrieve a list of all Apple products, we can run the following query through DBpedia's SPARQL interface:

select ?products where {
  <http://dbpedia.org/resource/Apple_Inc.> <http://dbpedia.org/ontology/product> ?products 
}

(try it here)

Since DBpedia contains URIs for all of Apple's products, we can query the News API to retrieve stories that mention any of Apple's products.

Finding DBpedia URIs for Entities

Using the Autocompletes endpoint, you can retrieve the DBpedia link for an entity by providing its name (or a part of it). All you need to do is to set type=dbpedia_resources and provide all or a part of the entity's name using the term parameter.

Similarly, you can search over all entity types by setting type=entity_types while using the Autocompletes endpoint.

For more information, please refer to the examples provided in the Autocompletes documentation.

Note: Not all entities have a DBpedia identifier. Typically, only well-known entities have one. If your Autocompletes search doesn't yield any results, consider providing the name of the entity as text (entities.title.text[] or entities.body.text[]) instead.

DBpedia Types

The DBpedia project has its own extensive ontology for entity types, which goes beyond the common types such as person, organization or place. For a complete list of these, refer to the Ontology Classes document on the DBpedia project website.

To filter based on DBpedia types, you can simply use the entities.title.type[] and/or entities.body.type[] parameters.

Note: For simplicity, we omit the "http://dbpedia.org/ontology/" prefix from DBpedia type strings. For instance, to retrieve all stories where any Member of Parliament (DBpedia type http://dbpedia.org/ontology/MemberOfParliament) is mentioned in the title, you can set entities.title.type[]=MemberOfParliament.

Examples

The following example shows articles that are in English, mention Harvey Norman or Apple Inc. in the body, and were published between 1 day ago and now:

var AylienNewsApi = require('aylien-news-api');

var apiInstance = new AylienNewsApi.DefaultApi();

// Configure API key authorization: app_id
var app_id = apiInstance.apiClient.authentications['app_id'];
app_id.apiKey = "YOUR_APP_ID";

// Configure API key authorization: app_key
var app_key = apiInstance.apiClient.authentications['app_key'];
app_key.apiKey = "YOUR_APP_KEY";

var opts = {
  'entitiesBodyLinksDbpedia': [
    'http://dbpedia.org/resource/Harvey_Norman',
    'http://dbpedia.org/resource/Apple_Inc.'
  ],
  'language': ['en'],
  'publishedAtStart': 'NOW-1DAY',
  'publishedAtEnd': 'NOW'
};

var callback = function(error, data, response) {
  if (error) {
    console.error(error);
  } else {
    console.log('The API has been called successfully.');
    console.log('=====================================');
    for (var i = 0; i < data.stories.length; i++){
      console.log(data.stories[i].title + " / " + data.stories[i].source.name);
    }
  }
};
apiInstance.listStories(opts, callback);
import aylien_news_api
from aylien_news_api.rest import ApiException

# Configure API key authorization: app_id
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'
# Configure API key authorization: app_key
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'

# create an instance of the API class
api_instance = aylien_news_api.DefaultApi()

opts = {
  'entities_body_links_dbpedia': [
    'http://dbpedia.org/resource/Harvey_Norman',
    'http://dbpedia.org/resource/Apple_Inc.'
  ],
  'language': ['en'],
  'published_at_start': 'NOW-1DAY',
  'published_at_end': 'NOW'
}

try:
    # List stories
    api_response = api_instance.list_stories(**opts)
    print('The API has been called successfully.')
    print('=====================================')
    for story in api_response.stories:
      print(story.title + " / " + story.source.name)
except ApiException as e:
    print("Exception when calling DefaultApi->list_stories: %sn" % e)
<?php
require_once(__DIR__ . '/../vendor/autoload.php');

// Configure API key authorization: app_id
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-ID', 'YOUR_APP_ID');

// Configure API key authorization: app_key
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-Key', 'YOUR_APP_KEY');

$api_instance = new Aylien\NewsApi\Api\DefaultApi();

$opts = array(
  'entities_body_links_dbpedia' => [
    'http://dbpedia.org/resource/Harvey_Norman',
    'http://dbpedia.org/resource/Apple_Inc.'
  ],
  'language' => ['en'],
  'published_at_start' => 'NOW-1DAY',
  'published_at_end' => 'NOW'
);

try {
    $result = $api_instance->listStories($opts);
    print_r("The API has been called successfully.\n");
    print_r("=====================================\n");
    for($i = 0; $i < sizeof($result->getStories()); $i++){
      print_r($result->getStories()[$i]->getTitle() . " / " .
        $result->getStories()[$i]->getSource()->getName() . "\n");
    }
} catch (Exception $e) {
    print_r($e->getResponseObject()->getErrors());
    echo 'Exception when calling DefaultApi->listStories: ', $e->getMessage(), "\n";
}
?>
import com.aylien.newsapi.*;
import com.aylien.newsapi.auth.*;
import com.aylien.newsapi.models.*;
import com.aylien.newsapi.parameters.*;
import com.aylien.newsapi.api.DefaultApi;

import java.util.*;

public class Main {

    public static void main(String[] args) {
        ApiClient defaultClient = Configuration.getDefaultApiClient();

        // Configure API key authorization: app_id
        ApiKeyAuth app_id = (ApiKeyAuth) defaultClient.getAuthentication("app_id");
        app_id.setApiKey("YOUR_APP_ID");

        // Configure API key authorization: app_key
        ApiKeyAuth app_key = (ApiKeyAuth) defaultClient.getAuthentication("app_key");
        app_key.setApiKey("YOUR_APP_KEY");

        DefaultApi apiInstance = new DefaultApi();

        StoriesParams.Builder storiesBuilder = StoriesParams.newBuilder();

        storiesBuilder.setEntitiesBodyLinksDbpedia(Arrays.asList(
            "http://dbpedia.org/resource/Harvey_Norman",
            "http://dbpedia.org/resource/Apple_Inc.")
        );
        storiesBuilder.setLanguage(Arrays.asList("en"));
        storiesBuilder.setPublishedAtStart("NOW-1DAY");
        storiesBuilder.setPublishedAtEnd("NOW");

        try {
            Stories result = apiInstance.listStories(storiesBuilder.build());
            for (Iterator i = result.getStories().iterator(); i.hasNext();){
                Story story = i.next();
                System.out.println(story.getTitle() + " / " + story.getSource().getName());
            }
        } catch (ApiException e) {
            System.err.println("Exception when calling DefaultApi#listStories");
            e.printStackTrace();
        }
    }
}
# Load the gem
require 'aylien_news_api'

# Setup authorization
AylienNewsApi.configure do |config|
  # Configure API key authorization: app_id
  config.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'

  # Configure API key authorization: app_key
  config.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'
end

api_instance = AylienNewsApi::DefaultApi.new

opts = {
  :entities_body_links_dbpedia => [
    'http://dbpedia.org/resource/Harvey_Norman',
    'http://dbpedia.org/resource/Apple_Inc.'
  ],
  :language => ['en'],
  :published_at_start => "NOW-1DAY",
  :published_at_end => "NOW"
}


begin
  #List stories
  result = api_instance.list_stories(opts)

  puts 'The API has been called successfully.'
  puts '====================================='
  result.stories.each do |story|
    puts "#{story.title} / #{story.source.name}"
  end
rescue AylienNewsApi::ApiError => e
  puts "Exception when calling DefaultApi->list_stories: #{e}"
  puts e.response_body
end
package main

// Import the library
import (
    "fmt"
    newsapi "github.com/AYLIEN/aylien_newsapi_go"
)

func main() {
    api := newsapi.NewDefaultApi()

    // Configure API key authorization: app_id
    api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-ID"] = "YOUR_APP_ID"

    // Configure API key authorization: app_key
    api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-Key"] = "YOUR_APP_KEY"

    storiesParams := &newsapi.StoriesParams{
        EntitiesBodyLinksDbpedia: []string{
            "http://dbpedia.org/resource/Harvey_Norman",
            "http://dbpedia.org/resource/Apple_Inc."},
        Language:         []string{"en"},
        PublishedAtStart: "NOW-1DAY",
        PublishedAtEnd:   "NOW"}

    storiesResponse, res, err := api.ListStories(storiesParams)
    if err != nil {
        panic(err)
    }
    _ = res

    fmt.Println("The API has been called successfully.")
    fmt.Println("=====================================")
    for _, story := range storiesResponse.Stories {
        fmt.Println(story.Title, "/", story.Source.Name)
    }
}
using System;
using Aylien.NewsApi.Api;
using Aylien.NewsApi.Client;
using Aylien.NewsApi.Model;
using System.Collections.Generic;

namespace WorkingWithEntitiesExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Configure API key authorization: app_id
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-ID", "YOUR_APP_ID");

            // Configure API key authorization: app_key
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-Key", "YOUR_APP_KEY");

            var apiInstance = new DefaultApi();

            try
            {
                // List stories
                Stories storiesResponse = apiInstance.ListStories(
                    entitiesBodyLinksDbpedia: new List { 
                        "http://dbpedia.org/resource/Harvey_Norman",
                        "http://dbpedia.org/resource/Apple_Inc." },
                    language: new List { "en" },
                    publishedAtStart: "NOW-1DAY",
                    publishedAtEnd: "NOW"
                );

                Console.WriteLine("The API has been called successfully.");
                Console.WriteLine("=====================================");
                foreach (var story in storiesResponse._Stories)
                {
                    Console.WriteLine(story.Title + " / " + story.Source.Name);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception when calling DefaultApi.ListStories: " + e.Message);
            }
        }
    }
}

Boolean Operators

Boolean operators allow you to apply Boolean logic to queries, requiring the presence or absence of specific terms or conditions in fields in order to match documents. The table below summarizes the Boolean operators supported by the standard query parser.

Boolean Operator Alternative Symbol Description
NOT ! Requires that the following term not be present.
AND && Requires both terms on either side of the Boolean operator to be present for a match.
+ Requires that the following term be present.
- Prohibits the following term (that is, matches on fields or documents that do not include that term). The - operator is functionally similar to the Boolean operator !. Because it's used by popular search engines such as Google, it may be more familiar to some user communities.
OR || Requires that either term (or both terms) be present for a match.

The Boolean Operator NOT (!)

The NOT operator excludes documents that contain the term after NOT. This is equivalent to a difference using sets. The symbol ! can be used in place of the word NOT.

The following queries search for documents that contain the phrase "jakarta apache" but do not contain the phrase "Apache Lucene":

"jakarta apache" NOT "Apache Lucene"

"jakarta apache" ! "Apache Lucene"

The Boolean Operator AND (&&)

The AND operator matches documents where both terms exist anywhere in the text of a single document. This is equivalent to an intersection using sets. The symbol && can be used in place of the word AND.

To search for documents that contain "jakarta apache" and "Apache Lucene," use either of the following queries:

"jakarta apache" AND "Apache Lucene"

"jakarta apache" && "Apache Lucene"

The Boolean Operator +

The + symbol (also known as the "required" operator) requires that the term after the + symbol exist somewhere in a field in at least one document in order for the query to return a match.

For example, to search for documents that must contain "jakarta" and that may or may not contain "lucene," use the following query:

+jakarta lucene

The Boolean Operator -

The - symbol or "prohibit" operator excludes documents that contain the term after the - symbol.

For example, to search for documents that contain "jakarta apache" but not "Apache Lucene," use the following query:

"jakarta apache" -"Apache Lucene"

The Boolean Operator OR (||)

The OR operator is the default conjunction operator. This means that if there is no Boolean operator between two terms, the OR operator is used. The OR operator links two terms and finds a matching document if either of the terms exist in a document. This is equivalent to a union using sets. The symbol || can be used in place of the word OR.

For example, to search for documents that contain either "jakarta apache" or just "jakarta," use the query:

"jakarta apache" jakarta

or

"jakarta apache" OR jakarta

Grouping Terms to Form Sub-Queries

The API supports using parentheses to group clauses to form sub-queries. This can be very useful if you want to control the Boolean logic for a query.

The query below searches for either "jakarta" or "apache" and "website":

(jakarta OR apache) AND website

This adds precision to the query, requiring that the term "website" exist, along with either term "jakarta" and "apache."

Working with Dates

Date Formatting

The format used is a restricted form of the canonical representation of dateTime in the XML Schema specification (ISO 8601):

YYYY-MM-DDThh:mm:ssZ

  • YYYY is the year.
  • MM is the month.
  • DD is the day of the month.
  • T is a literal 'T' character that indicates the beginning of the time string.
  • hh is the hour of the day as on a 24-hour clock.
  • mm is minutes.
  • ss is seconds.
  • Z is a literal 'Z' character indicating that this string representation of the date is in UTC

Note that no time zone can be specified; the String representations of dates is always expressed in Coordinated Universal Time (UTC). Here is an example value:

2016-03-27T13:47:26Z

You can optionally include fractional seconds if you wish, although any precision beyond milliseconds will be ignored. Here are examples value with sub-seconds include:

  • 2016-03-27T13:47:26.822Z
  • 2016-03-27T13:47:26.82Z
  • 2016-03-27T13:47:26.8Z

Date Math

The date field types also supports date math expressions, which makes it easy to create times relative to fixed moments in time, include the current time which can be represented using the special value of "NOW".

Date Math Syntax

Date math expressions can do two things: they can specify a time period by adding time units to the current time, and also round the time to a specified unit. Expressions can be chained and are evaluated left to right.

For example: this represents a point in time two months from now, from the millisecond:

NOW+2MONTHS

This is one day ago, to the millisecond:

NOW-1DAY

A slash is used to indicate rounding. Below is a point in time yesterday, rounded to the previous hour, with millisecond precision (For example, if the current time is 15:42:17.2165, the point below is 15:00:00.0000 yesterday):

NOW-1DAY/HOUR

Below is yesterday at 00:00:00.0000AM:

NOW-1DAY/DAY

Here is the supported keywords in Date Math:

Date part keywords Alternative keywords Description Round part?
NOW It represents current date time.
YEAR YEARS It represents the year part of date time.
MONTH MONTHS It represents the month part of date time.
DAY DAYS
DATE
It represents the day part of date time.
HOUR HOURS It represents the hour part of date time.
MINUTE MINUTES It represents the minute part of date time.
SECOND SECONDS It represents the second part of date time.

Working with Locations

There are three ways to work with locations in the News API. Below we outline the three methods.

Based on Source Location

Description

Source location refers to where the source is based, and allows you to filter results to stories published in a specific location.

Examples

The following example shows how to retrieve stories in English, are about Electrical Cars published by Indian sources, were published between 10 days ago and now and sorted by Reddit social shares count.

var AylienNewsApi = require('aylien-news-api');

var apiInstance = new AylienNewsApi.DefaultApi();

// Configure API key authorization: app_id
var app_id = apiInstance.apiClient.authentications['app_id'];
app_id.apiKey = "YOUR_APP_ID";

// Configure API key authorization: app_key
var app_key = apiInstance.apiClient.authentications['app_key'];
app_key.apiKey = "YOUR_APP_KEY";

var opts = {
  'sortBy': 'social_shares_count.reddit',
  'language': ['en'],
  'publishedAtStart': 'NOW-10DAYS',
  'publishedAtEnd': 'NOW', 
  'categoriesTaxonomy': 'iab-qag',
  'categoriesId': ['IAB2-10'],
  'sourceLocationsCountry': ['IN']
};

var callback = function(error, data, response) {
  if (error) {
    console.error(error);
  } else {
    console.log('API called successfully. Returned data: ' + data);
  }
};
apiInstance.listStories(opts, callback);
import aylien_news_api
from aylien_news_api.rest import ApiException

# Configure API key authorization: app_id
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'
# Configure API key authorization: app_key
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'

# create an instance of the API class
api_instance = aylien_news_api.DefaultApi()

language = ['en']
since = 'NOW-10DAYS'
until = 'NOW'
sort_by = 'social_shares_count.reddit'
categories_taxonomy = 'iab-qag'
categories_id = ['IAB2-10']
source_locations_country = ['IN']

try:
  # List stories
  api_response = api_instance.list_stories(
    language=language,
    published_at_start=since,
    published_at_end=until,
    sort_by=sort_by,
    categories_taxonomy=categories_taxonomy,
    categories_id=categories_id,
    source_locations_country=source_locations_country
  )
  print(api_response)
except ApiException as e:
  print("Exception when calling DefaultApi->list_stories: %sn" % e)
<?php
require_once(__DIR__ . '/vendor/autoload.php');

// Configure API key authorization: app_id
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-ID', 'YOUR_APP_ID');

// Configure API key authorization: app_key
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-Key', 'YOUR_APP_KEY');

$api_instance = new Aylien\NewsApi\Api\DefaultApi();

$opts = array(
  'published_at_start' => 'NOW-10DAYS',
  'published_at_end' => 'NOW',
  'language' => ['en'],
  'sort_by' => 'social_shares_count.reddit',
  'categories_taxonomy' => 'iab-qag',
  'categories_id' => ['IAB2-10'],
  'source_locations_country' => ['IN']
);

try {
  $result = $api_instance->listStories($opts);
  print_r($result);
} catch (Exception $e) {
  echo 'Exception when calling DefaultApi->listStories: ', $e->getMessage(), PHP_EOL;
}
?>
package com.aylien.newsapisample;

import com.aylien.newsapi.*;
import com.aylien.newsapi.auth.*;
import com.aylien.newsapi.models.*;
import com.aylien.newsapi.parameters.*;
import com.aylien.newsapi.api.DefaultApi;

import java.util.*;

public class Main {

  public static void main(String[] args) {
    ApiClient defaultClient = Configuration.getDefaultApiClient();

    // Configure API key authorization: app_id
    ApiKeyAuth app_id = (ApiKeyAuth) defaultClient.getAuthentication("app_id");
    app_id.setApiKey("YOUR_APP_ID");

    // Configure API key authorization: app_key
    ApiKeyAuth app_key = (ApiKeyAuth) defaultClient.getAuthentication("app_key");
    app_key.setApiKey("YOUR_APP_KEY");

    DefaultApi apiInstance = new DefaultApi();

    List language = Arrays.asList("en");
    String since = "NOW-10DAYS";
    String until = "NOW";
    List sourceLocationsCountry = Arrays.asList("IN");
    String sortBy = "social_shares_count.reddit";
    String categoriesTaxonomy = "iab-qag";
    List categoriesId = Arrays.asList("IAB2-10");

    StoriesParams.Builder storiesBuilder = StoriesParams.newBuilder();

    storiesBuilder.setPublishedAtStart(since);
    storiesBuilder.setPublishedAtEnd(until);
    storiesBuilder.setLanguage(language);
    storiesBuilder.setCategoriesTaxonomy(categoriesTaxonomy);
    storiesBuilder.setCategoriesId(categoriesId);
    storiesBuilder.setSourceLocationsCountry(sourceLocationsCountry);
    storiesBuilder.setSortBy(sortBy);

    try {
      Stories result = apiInstance.listStories(storiesBuilder.build());
      System.out.println(result);
    } catch (ApiException e) {
      System.err.println("Exception when calling DefaultApi#listStories");
      e.printStackTrace();
    }
  }
}
# Load the gem
require 'aylien_news_api'

# Setup authorization
AylienNewsApi.configure do |config|
  # Configure API key authorization: app_id
  config.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'

  # Configure API key authorization: app_key
  config.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'
end

api_instance = AylienNewsApi::DefaultApi.new

opts = {
  :published_at_start => "NOW-10DAYS",
  :published_at_end => "NOW",
  :language => ['en'],
  :sort_by => 'social_shares_count.reddit',
  :categories_taxonomy => 'iab-qag',
  :categories_id => ['IAB2-10'],
  :source_locations_country => ['IN']
}


begin
  #List stories
  result = api_instance.list_stories(opts)
  puts result
rescue AylienNewsApi::ApiError => e
  puts "Exception when calling DefaultApi->list_stories: #{e}"
end
package main

// Import the library
import (
  "fmt"
  newsapi "github.com/AYLIEN/aylien_newsapi_go"
)

func main() {
  api := newsapi.NewDefaultApi()

  // Configure API key authorization: app_id
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-ID"] = "YOUR_APP_ID"

  // Configure API key authorization: app_key
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-Key"] = "YOUR_APP_KEY"

  language := []string{"en"}
  publishedAtStart := "NOW-10DAYS"
  publishedAtEnd := "NOW"
  categoriesTaxonomy := "iab-qag"
  categoriesId := []string{"IAB2-10"}
  sourceLocationsCountry := []string{"IN"}
  sortBy := "social_shares_count.reddit"

  storiesParams := &newsapi.StoriesParams{
    Language:               language,
    PublishedAtStart:       publishedAtStart,
    PublishedAtEnd:         publishedAtEnd,
    CategoriesTaxonomy:     categoriesTaxonomy,
    CategoriesId:           categoriesId,
    SourceLocationsCountry: sourceLocationsCountry,
    SortBy:                 sortBy}

  storiesResponse, res, err := api.ListStories(storiesParams)
  if err != nil {
    panic(err)
  }

  _ = res

  fmt.Println(storiesResponse)
}
using System;
using Aylien.NewsApi.Api;
using Aylien.NewsApi.Client;
using Aylien.NewsApi.Model;
using System.Collections.Generic;

namespace ConsoleApplicationExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Configure API key authorization: app_id
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-ID", "YOUR_APP_ID");

            // Configure API key authorization: app_key
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-Key", "YOUR_APP_KEY");

            var apiInstance = new DefaultApi();

            var language = new List { "en" };
            var publishedAtStart = "NOW-10DAYS";
            var publishedAtEnd = "NOW";
            var categoriesTaxonomy = "iab-qag";
            var categoriesId = new List { "IAB2-10" };
            var sourceLocationsCountry = new List { "IN" };
            var sortBy = "social_shares_count.reddit";

            try
            {
                // List Stories
                Stories result = apiInstance.ListStories(
                    language: language,
                    publishedAtStart: publishedAtStart,
                    publishedAtEnd: publishedAtEnd,
                    categoriesTaxonomy: categoriesTaxonomy,
                    categoriesId: categoriesId,
                    sourceLocationsCountry: sourceLocationsCountry,
                    sortBy: sortBy
                );
                Console.WriteLine(result);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception when calling DefaultApi.ListStories: " + e.Message);
            }
        }
    }
}

Based on Source Scope

Description

Source scope refers to the geographical regions a news source covers. For example, a news source might cover local, national or international news they might also only cover news related to a particular city, state or country. The source scope allows you to filter stories by scope.

Examples

The following example shows how to retrieve stories in English, are about Startup Fundraising published by sources who cover London city news, were published between 30 days ago and now and sorted by published at date time.

var AylienNewsApi = require('aylien-news-api');

var apiInstance = new AylienNewsApi.DefaultApi();

// Configure API key authorization: app_id
var app_id = apiInstance.apiClient.authentications['app_id'];
app_id.apiKey = "YOUR_APP_ID";

// Configure API key authorization: app_key
var app_key = apiInstance.apiClient.authentications['app_key'];
app_key.apiKey = "YOUR_APP_KEY";

var opts = {
  'title': 'startup AND (raise OR raised OR raising OR raises)',
  'sortBy': 'published_at',
  'language': ['en'],
  'publishedAtStart': 'NOW-30DAYS',
  'publishedAtEnd': 'NOW', 
  'categoriesTaxonomy': 'iab-qag',
  'categoriesId': ['IAB3'],
  'sourceScopesCity': ['London']
};

var callback = function(error, data, response) {
  if (error) {
    console.error(error);
  } else {
    console.log('API called successfully. Returned data: ' + data);
  }
};
apiInstance.listStories(opts, callback);
import aylien_news_api
from aylien_news_api.rest import ApiException

# Configure API key authorization: app_id
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'
# Configure API key authorization: app_key
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'

# create an instance of the API class
api_instance = aylien_news_api.DefaultApi()

title = 'startup AND (raise OR raised OR raising OR raises)'
language = ['en']
since = 'NOW-30DAYS'
until = 'NOW'
sort_by = 'published_at'
categories_taxonomy = 'iab-qag'
categories_id = ['IAB3']
source_scopes_city = ['London']

try:
  # List stories
  api_response = api_instance.list_stories(
    title=title,
    language=language,
    published_at_start=since,
    published_at_end=until,
    sort_by=sort_by,
    categories_taxonomy=categories_taxonomy,
    categories_id=categories_id,
    source_scopes_city=source_scopes_city
  )
  print(api_response)
except ApiException as e:
  print("Exception when calling DefaultApi->list_stories: %sn" % e)
<?php
require_once(__DIR__ . '/vendor/autoload.php');

// Configure API key authorization: app_id
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-ID', 'YOUR_APP_ID');

// Configure API key authorization: app_key
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-Key', 'YOUR_APP_KEY');

$api_instance = new Aylien\NewsApi\Api\DefaultApi();

$opts = array(
  'title' => 'startup AND (raise OR raised OR raising OR raises)',
  'published_at_start' => 'NOW-30DAYS',
  'published_at_end' => 'NOW',
  'language' => ['en'],
  'sort_by' => 'published_at',
  'categories_taxonomy' => 'iab-qag',
  'categories_id' => ['IAB3'],
  'source_scopes_city' => ['London']
);

try {
  $result = $api_instance->listStories($opts);
  print_r($result);
} catch (Exception $e) {
  echo 'Exception when calling DefaultApi->listStories: ', $e->getMessage(), PHP_EOL;
}
?>
package com.aylien.newsapisample;

import com.aylien.newsapi.*;
import com.aylien.newsapi.auth.*;
import com.aylien.newsapi.models.*;
import com.aylien.newsapi.parameters.*;
import com.aylien.newsapi.api.DefaultApi;

import java.util.*;

public class Main {

  public static void main(String[] args) {
    ApiClient defaultClient = Configuration.getDefaultApiClient();

    // Configure API key authorization: app_id
    ApiKeyAuth app_id = (ApiKeyAuth) defaultClient.getAuthentication("app_id");
    app_id.setApiKey("YOUR_APP_ID");

    // Configure API key authorization: app_key
    ApiKeyAuth app_key = (ApiKeyAuth) defaultClient.getAuthentication("app_key");
    app_key.setApiKey("YOUR_APP_KEY");

    DefaultApi apiInstance = new DefaultApi();

    String title = "startup AND (raise OR raised OR raising OR raises)";
    List language = Arrays.asList("en");
    String since = "NOW-30DAYS";
    String until = "NOW";
    List sourceScopesCity = Arrays.asList("London");
    String sortBy = "published_at";
    String categoriesTaxonomy = "iab-qag";
    List categoriesId = Arrays.asList("IAB3");

    StoriesParams.Builder storiesBuilder = StoriesParams.newBuilder();

    storiesBuilder.setTitle(title);
    storiesBuilder.setPublishedAtStart(since);
    storiesBuilder.setPublishedAtEnd(until);
    storiesBuilder.setLanguage(language);
    storiesBuilder.setCategoriesTaxonomy(categoriesTaxonomy);
    storiesBuilder.setCategoriesId(categoriesId);
    storiesBuilder.setSourceScopesCity(sourceScopesCity);
    storiesBuilder.setSortBy(sortBy);

    try {
      Stories result = apiInstance.listStories(storiesBuilder.build());
      System.out.println(result);
    } catch (ApiException e) {
      System.err.println("Exception when calling DefaultApi#listStories");
      e.printStackTrace();
    }
  }
}
# Load the gem
require 'aylien_news_api'

# Setup authorization
AylienNewsApi.configure do |config|
  # Configure API key authorization: app_id
  config.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'

  # Configure API key authorization: app_key
  config.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'
end

api_instance = AylienNewsApi::DefaultApi.new

opts = {
  :title => "startup AND (raise OR raised OR raising OR raises)",
  :published_at_start => "NOW-30DAYS",
  :published_at_end => "NOW",
  :language => ['en'],
  :sort_by => 'published_at',
  :categories_taxonomy => 'iab-qag',
  :categories_id => ['IAB3'],
  :source_scopes_city => ['London']
}


begin
  #List stories
  result = api_instance.list_stories(opts)
  puts result
rescue AylienNewsApi::ApiError => e
  puts "Exception when calling DefaultApi->list_stories: #{e}"
end
package main

// Import the library
import (
  "fmt"
  newsapi "github.com/AYLIEN/aylien_newsapi_go"
)

func main() {
  api := newsapi.NewDefaultApi()

  // Configure API key authorization: app_id
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-ID"] = "YOUR_APP_ID"

  // Configure API key authorization: app_key
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-Key"] = "YOUR_APP_KEY"

  title := "startup AND (raise OR raised OR raising OR raises)"
  language := []string{"en"}
  publishedAtStart := "NOW-30DAYS"
  publishedAtEnd := "NOW"
  categoriesTaxonomy := "iab-qag"
  categoriesId := []string{"IAB3"}
  sourceScopesCity := []string{"London"}
  sortBy := "published_at"

  storiesParams := &newsapi.StoriesParams{
    Title:              title,
    Language:           language,
    PublishedAtStart:   publishedAtStart,
    PublishedAtEnd:     publishedAtEnd,
    CategoriesTaxonomy: categoriesTaxonomy,
    CategoriesId:       categoriesId,
    SourceScopesCity:   sourceScopesCity,
    SortBy:             sortBy}

  storiesResponse, res, err := api.ListStories(storiesParams)
  if err != nil {
    panic(err)
  }

  _ = res

  fmt.Println(storiesResponse)
}
using System;
using Aylien.NewsApi.Api;
using Aylien.NewsApi.Client;
using Aylien.NewsApi.Model;
using System.Collections.Generic;

namespace ConsoleApplicationExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Configure API key authorization: app_id
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-ID", "YOUR_APP_ID");

            // Configure API key authorization: app_key
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-Key", "YOUR_APP_KEY");

            var apiInstance = new DefaultApi();

            var title = "startup AND (raise OR raised OR raising OR raises)";
            var language = new List { "en" };
            var publishedAtStart = "NOW-30DAYS";
            var publishedAtEnd = "NOW";
            var categoriesTaxonomy = "iab-qag";
            var categoriesId = new List { "IAB3" };
            var sourceScopesCity = new List { "London" };
            var sortBy = "published_at";

            try
            {
                // List Stories
                Stories result = apiInstance.ListStories(
                    title: title,
                    language: language,
                    publishedAtStart: publishedAtStart,
                    publishedAtEnd: publishedAtEnd,
                    categoriesTaxonomy: categoriesTaxonomy,
                    categoriesId: categoriesId,
                    sourceScopesCity: sourceScopesCity,
                    sortBy: sortBy
                );
                Console.WriteLine(result);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception when calling DefaultApi.ListStories: " + e.Message);
            }
        }
    }
}

Based on Mentioned Locations

Description

Mentioned Locations is used to identify when a location as a keyword or entity is mentioned in the title or body of a story.

Examples

The following example shows how to retrieve stories in English, are about Electrical Cars with San Francisco mentioned in their body, were published between 30 days ago and now and sorted by published at date time.

var AylienNewsApi = require('aylien-news-api');

var apiInstance = new AylienNewsApi.DefaultApi();

// Configure API key authorization: app_id
var app_id = apiInstance.apiClient.authentications['app_id'];
app_id.apiKey = "YOUR_APP_ID";

// Configure API key authorization: app_key
var app_key = apiInstance.apiClient.authentications['app_key'];
app_key.apiKey = "YOUR_APP_KEY";

var opts = {
  'sortBy': 'published_at',
  'language': ['en'],
  'publishedAtStart': 'NOW-30DAYS',
  'publishedAtEnd': 'NOW', 
  'categoriesTaxonomy': 'iab-qag',
  'categoriesId': ['IAB2-10'],
  'entitiesBodyLinksDbpedia': [
    'http://dbpedia.org/resource/San_Francisco'
  ]
};

var callback = function(error, data, response) {
  if (error) {
    console.error(error);
  } else {
    console.log('API called successfully. Returned data: ' + data);
  }
};
apiInstance.listStories(opts, callback);
import aylien_news_api
from aylien_news_api.rest import ApiException

# Configure API key authorization: app_id
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'
# Configure API key authorization: app_key
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'

# create an instance of the API class
api_instance = aylien_news_api.DefaultApi()

language = ['en']
since = 'NOW-30DAYS'
until = 'NOW'
sort_by = 'published_at'
categories_taxonomy = 'iab-qag'
categories_id = ['IAB2-10']
entities_body_links_dbpedia = ['http://dbpedia.org/resource/San_Francisco']

try:
  # List stories
  api_response = api_instance.list_stories(
    language=language,
    published_at_start=since,
    published_at_end=until,
    sort_by=sort_by,
    categories_taxonomy=categories_taxonomy,
    categories_id=categories_id,
    entities_body_links_dbpedia=entities_body_links_dbpedia
  )
  print(api_response)
except ApiException as e:
  print("Exception when calling DefaultApi->list_stories: %sn" % e)
<?php
require_once(__DIR__ . '/vendor/autoload.php');

// Configure API key authorization: app_id
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-ID', 'YOUR_APP_ID');

// Configure API key authorization: app_key
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-Key', 'YOUR_APP_KEY');

$api_instance = new Aylien\NewsApi\Api\DefaultApi();

$opts = array(
  'published_at_start' => 'NOW-30DAYS',
  'published_at_end' => 'NOW',
  'language' => ['en'],
  'sort_by' => 'published_at',
  'categories_taxonomy' => 'iab-qag',
  'categories_id' => ['IAB2-10'],
  'entities_body_links_dbpedia' => ['http://dbpedia.org/resource/San_Francisco']
);

try {
  $result = $api_instance->listStories($opts);
  print_r($result);
} catch (Exception $e) {
  echo 'Exception when calling DefaultApi->listStories: ', $e->getMessage(), PHP_EOL;
}
?>
package com.aylien.newsapisample;

import com.aylien.newsapi.*;
import com.aylien.newsapi.auth.*;
import com.aylien.newsapi.models.*;
import com.aylien.newsapi.parameters.*;
import com.aylien.newsapi.api.DefaultApi;

import java.util.*;

public class Main {

  public static void main(String[] args) {
    ApiClient defaultClient = Configuration.getDefaultApiClient();

    // Configure API key authorization: app_id
    ApiKeyAuth app_id = (ApiKeyAuth) defaultClient.getAuthentication("app_id");
    app_id.setApiKey("YOUR_APP_ID");

    // Configure API key authorization: app_key
    ApiKeyAuth app_key = (ApiKeyAuth) defaultClient.getAuthentication("app_key");
    app_key.setApiKey("YOUR_APP_KEY");

    DefaultApi apiInstance = new DefaultApi();

    List language = Arrays.asList("en");
    String since = "NOW-30DAYS";
    String until = "NOW";
    List entitiesBodyLinksDbpedia = Arrays.asList("http://dbpedia.org/resource/San_Francisco");
    String sortBy = "published_at";
    String categoriesTaxonomy = "iab-qag";
    List categoriesId = Arrays.asList("IAB2-10");

    StoriesParams.Builder storiesBuilder = StoriesParams.newBuilder();

    storiesBuilder.setPublishedAtStart(since);
    storiesBuilder.setPublishedAtEnd(until);
    storiesBuilder.setLanguage(language);
    storiesBuilder.setCategoriesTaxonomy(categoriesTaxonomy);
    storiesBuilder.setCategoriesId(categoriesId);
    storiesBuilder.setEntitiesBodyLinksDbpedia(entitiesBodyLinksDbpedia);
    storiesBuilder.setSortBy(sortBy);

    try {
      Stories result = apiInstance.listStories(storiesBuilder.build());
      System.out.println(result);
    } catch (ApiException e) {
      System.err.println("Exception when calling DefaultApi#listStories");
      e.printStackTrace();
    }
  }
}
# Load the gem
require 'aylien_news_api'

# Setup authorization
AylienNewsApi.configure do |config|
  # Configure API key authorization: app_id
  config.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'

  # Configure API key authorization: app_key
  config.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'
end

api_instance = AylienNewsApi::DefaultApi.new

opts = {
  :published_at_start => "NOW-30DAYS",
  :published_at_end => "NOW",
  :language => ['en'],
  :sort_by => 'published_at',
  :categories_taxonomy => 'iab-qag',
  :categories_id => ['IAB2-10'],
  :entities_body_links_dbpedia => ['http://dbpedia.org/resource/San_Francisco']
}


begin
  #List stories
  result = api_instance.list_stories(opts)
  puts result
rescue AylienNewsApi::ApiError => e
  puts "Exception when calling DefaultApi->list_stories: #{e}"
end
package main

// Import the library
import (
  "fmt"
  newsapi "github.com/AYLIEN/aylien_newsapi_go"
)

func main() {
  api := newsapi.NewDefaultApi()

  // Configure API key authorization: app_id
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-ID"] = "YOUR_APP_ID"

  // Configure API key authorization: app_key
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-Key"] = "YOUR_APP_KEY"

  language := []string{"en"}
  publishedAtStart := "NOW-30DAYS"
  publishedAtEnd := "NOW"
  categoriesTaxonomy := "iab-qag"
  categoriesId := []string{"IAB2-10"}
  entitiesBodyLinksDbpedia := []string{"http://dbpedia.org/resource/San_Francisco"}
  sortBy := "published_at"

  storiesParams := &newsapi.StoriesParams{
    Language:                  language,
    PublishedAtStart:          publishedAtStart,
    PublishedAtEnd:            publishedAtEnd,
    CategoriesTaxonomy:        categoriesTaxonomy,
    CategoriesId:              categoriesId,
    EntitiesBodyLinksDbpedia: entitiesBodyLinksDbpedia,
    SortBy: sortBy}

  storiesResponse, res, err := api.ListStories(storiesParams)
  if err != nil {
    panic(err)
  }

  _ = res

  fmt.Println(storiesResponse)
}
using System;
using Aylien.NewsApi.Api;
using Aylien.NewsApi.Client;
using Aylien.NewsApi.Model;
using System.Collections.Generic;

namespace ConsoleApplicationExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Configure API key authorization: app_id
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-ID", "YOUR_APP_ID");

            // Configure API key authorization: app_key
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-Key", "YOUR_APP_KEY");

            var apiInstance = new DefaultApi();

            var language = new List { "en" };
            var publishedAtStart = "NOW-30DAYS";
            var publishedAtEnd = "NOW";
            var categoriesTaxonomy = "iab-qag";
            var categoriesId = new List { "IAB2-10" };
            var entitiesBodyLinksDbpedia = new List {
                "http://dbpedia.org/resource/San_Francisco"
            };
            var sortBy = "published_at";

            try
            {
                // List Stories
                Stories result = apiInstance.ListStories(
                    language: language,
                    publishedAtStart: publishedAtStart,
                    publishedAtEnd: publishedAtEnd,
                    categoriesTaxonomy: categoriesTaxonomy,
                    categoriesId: categoriesId,
                    entitiesBodyLinksDbpedia: entitiesBodyLinksDbpedia,
                    sortBy: sortBy
                );
                Console.WriteLine(result);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception when calling DefaultApi.ListStories: " + e.Message);
            }
        }
    }
}

Taxonomies

Our classifier is capable of classifying content into two taxonomies. Below you can see a list of these taxonomies and their definitions.

Taxonomy Supported Languages Number of classes Levels of depth Commonly used for Taxonomy ID Definition
IPTC Subject Codes en 1400 3 News articles, Blog posts iptc-subjectcode View
IAB QAG en 392 2 Websites, Advertisement (e.g. in OpenRTB, details) iab-qag View

Traversing Taxonomies

Our supported taxonomies are made up of categories and subcategories, or parent categories and child categories, for example with Football being a child category of Sport.

We have standardized all our of our supported taxonomies into a tree-like structure, which allows you to easily traverse from child categories to parent categories, recursively.

Examples

The following example shows articles that are in English, are about Science and were published between 1 day ago and now.

var AylienNewsApi = require('aylien-news-api');

var apiInstance = new AylienNewsApi.DefaultApi();

// Configure API key authorization: app_id
var app_id = apiInstance.apiClient.authentications['app_id'];
app_id.apiKey = "YOUR_APP_ID";

// Configure API key authorization: app_key
var app_key = apiInstance.apiClient.authentications['app_key'];
app_key.apiKey = "YOUR_APP_KEY";

var opts = {
  'categoriesTaxonomy': 'iab-qag',
  'categoriesId': ['IAB15'],
  'language': ['en'],
  'publishedAtStart': 'NOW-1DAY',
  'publishedAtEnd': 'NOW'
};

var callback = function(error, data, response) {
  if (error) {
    console.error(error);
  } else {
    console.log('The API has been called successfully.');
    console.log('=====================================');
    for (var i = 0; i < data.stories.length; i++){
      console.log(data.stories[i].title + " / " + data.stories[i].source.name);
    }
  }
};
apiInstance.listStories(opts, callback);
import aylien_news_api
from aylien_news_api.rest import ApiException

# Configure API key authorization: app_id
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'
# Configure API key authorization: app_key
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'

# create an instance of the API class
api_instance = aylien_news_api.DefaultApi()

opts = {
  'categories_taxonomy': 'iab-qag',
  'categories_id': ['IAB15'],
  'language': ['en'],
  'published_at_start': 'NOW-1DAY',
  'published_at_end': 'NOW'
}

try:
    # List stories
    api_response = api_instance.list_stories(**opts)
    print('The API has been called successfully.')
    print('=====================================')
    for story in api_response.stories:
      print(story.title + " / " + story.source.name)
except ApiException as e:
    print("Exception when calling DefaultApi->list_stories: %sn" % e)
<?php
require_once(__DIR__ . '/../vendor/autoload.php');

// Configure API key authorization: app_id
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-ID', 'YOUR_APP_ID');

// Configure API key authorization: app_key
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-Key', 'YOUR_APP_KEY');

$api_instance = new Aylien\NewsApi\Api\DefaultApi();

$opts = array(
  'categories_taxonomy' => 'iab-qag',
  'categories_id' => ['IAB15'],
  'language' => ['en'],
  'published_at_start' => 'NOW-1DAY',
  'published_at_end' => 'NOW'
);

try {
    $result = $api_instance->listStories($opts);
    print_r("The API has been called successfully.\n");
    print_r("=====================================\n");
    for($i = 0; $i < sizeof($result->getStories()); $i++){
      print_r($result->getStories()[$i]->getTitle() . " / " .
        $result->getStories()[$i]->getSource()->getName() . "\n");
    }
} catch (Exception $e) {
    print_r($e->getResponseObject()->getErrors());
    echo 'Exception when calling DefaultApi->listStories: ', $e->getMessage(), "\n";
}
?>
import com.aylien.newsapi.*;
import com.aylien.newsapi.auth.*;
import com.aylien.newsapi.models.*;
import com.aylien.newsapi.parameters.*;
import com.aylien.newsapi.api.DefaultApi;

import java.util.*;

public class Main {

    public static void main(String[] args) {
        ApiClient defaultClient = Configuration.getDefaultApiClient();

        // Configure API key authorization: app_id
        ApiKeyAuth app_id = (ApiKeyAuth) defaultClient.getAuthentication("app_id");
        app_id.setApiKey("YOUR_APP_ID");

        // Configure API key authorization: app_key
        ApiKeyAuth app_key = (ApiKeyAuth) defaultClient.getAuthentication("app_key");
        app_key.setApiKey("YOUR_APP_KEY");

        DefaultApi apiInstance = new DefaultApi();

        StoriesParams.Builder storiesBuilder = StoriesParams.newBuilder();

        storiesBuilder.setCategoriesTaxonomy("iab-qag");
        storiesBuilder.setCategoriesId(Arrays.asList("IAB15"));
        storiesBuilder.setLanguage(Arrays.asList("en"));
        storiesBuilder.setPublishedAtStart("NOW-1DAY");
        storiesBuilder.setPublishedAtEnd("NOW");

        try {
            Stories result = apiInstance.listStories(storiesBuilder.build());
            for (Iterator i = result.getStories().iterator(); i.hasNext();){
                Story story = i.next();
                System.out.println(story.getTitle() + " / " + story.getSource().getName());
            }
        } catch (ApiException e) {
            System.err.println("Exception when calling DefaultApi#listStories");
            e.printStackTrace();
        }
    }
}
# Load the gem
require 'aylien_news_api'

# Setup authorization
AylienNewsApi.configure do |config|
  # Configure API key authorization: app_id
  config.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'

  # Configure API key authorization: app_key
  config.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'
end

api_instance = AylienNewsApi::DefaultApi.new

opts = {
  :categories_taxonomy => 'iab-qag',
  :categories_id => ['IAB15'],
  :language => ['en'],
  :published_at_start => "NOW-1DAY",
  :published_at_end => "NOW"
}


begin
  #List stories
  result = api_instance.list_stories(opts)

  puts 'The API has been called successfully.'
  puts '====================================='
  result.stories.each do |story|
    puts "#{story.title} / #{story.source.name}"
  end
rescue AylienNewsApi::ApiError => e
  puts "Exception when calling DefaultApi->list_stories: #{e}"
  puts e.response_body
end
package main

// Import the library
import (
  "fmt"
  newsapi "github.com/AYLIEN/aylien_newsapi_go"
)

func main() {
  api := newsapi.NewDefaultApi()

  // Configure API key authorization: app_id
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-ID"] = "YOUR_APP_ID"

  // Configure API key authorization: app_key
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-Key"] = "YOUR_APP_KEY"

  storiesParams := &newsapi.StoriesParams{
    CategoriesTaxonomy: "iab-qag",
    CategoriesId:       []string{"IAB15"},
    Language:           []string{"en"},
    PublishedAtStart:   "NOW-1DAY",
    PublishedAtEnd:     "NOW"}

  storiesResponse, res, err := api.ListStories(storiesParams)
  if err != nil {
    panic(err)
  }
  _ = res

  for _, story := range storiesResponse.Stories {
    fmt.Println(story.Title, "/", story.Source.Name)
  }
}
using System;
using Aylien.NewsApi.Api;
using Aylien.NewsApi.Client;
using Aylien.NewsApi.Model;
using System.Collections.Generic;

namespace WorkingWithCategoriesExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Configure API key authorization: app_id
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-ID", "YOUR_APP_ID");

            // Configure API key authorization: app_key
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-Key", "YOUR_APP_KEY");

            var apiInstance = new DefaultApi();

            try
            {
                // List stories
                Stories storiesResponse = apiInstance.ListStories(
                    categoriesTaxonomy: "iab-qag",
                    categoriesId: new List { "IAB15" },
                    language: new List { "en" },
                    publishedAtStart: "NOW-1DAY",
                    publishedAtEnd: "NOW"
                );

                foreach (var story in storiesResponse._Stories)
                {
                    Console.WriteLine(story.Title + " / " + story.Source.Name);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception when calling DefaultApi.ListStories: " + e.Message);
            }
        }
    }
}

Media Elements

Many stories contain media such as images or videos as well as text, which can be valuable to some users, depending on what they are building. Some users are only interested in stories with video content to increase click through rate, whereas other users do not want videos in their results if they are concerned with the end-user's loading time, as videos take slightly longer to load on poorer connections.

The News API allows you to:

  • Specify whether your results should include these media or not
  • Specify the amount of images or videos your results should include (this can be an exact number, a range, or a minimum or maximum)
  • Sort your results according to how many images or videos they contain
  • Specify the format of the media in your stories
  • Display quantitative trends in media with the histograms endpoint

Specifying the amount of media in stories

It is possible to specify whether the stories returned by your query should contain media or not, and also to specify the number of images and videos in each story by using the media.images.count or the media.videos.count parameter.

  • By setting media.images.count.min to 1, you are specifying that your query only return stories with at least one image.
  • By setting media.videos.count.min to 1, and media.videos.count.max also to 1, you are specifying that you only want results that contain exactly one video.
  • By setting media.videos.count.max to 0, you are excluding any stories with videos from your results.

Sorting by media count

To display stories with more images before stories with fewer images in your results, set the sort_by parameter to media.images.count, and the sort_direction parameter to desc. Whenever you use the sort_by parameter, the sort direction will automatically be in descending order (i.e. stories with the most results in the parameter will be shown first). In order to reverse this default, set the sort_by parameter to asc, which will sort the results in ascending order.

Media format & size

It is possible to return or exclude stories that contain images in a specified format, by using the media.images.format[] parameter. These can help avoid any technical issues you can foresee with these formats.

The image formats you can use as a parameter are:

  • BMP
  • GIF
  • JPEG
  • PNG
  • TIFF
  • PSD
  • ICO
  • CUR
  • WEBP
  • SVG

It is also possible to specify maximum and minimum height, width, and content length by appending .min or .max to the following parameters:

  • media.images.width
  • media.images.height
  • media.images.content_length

Examples

The code below gathers stories that mention fitness with exactly one video and no GIF images from the last month.

var AylienNewsApi = require('aylien-news-api');

var apiInstance = new AylienNewsApi.DefaultApi();

// Configure API key authorization: app_id
var app_id = apiInstance.apiClient.authentications['app_id'];
app_id.apiKey = "YOUR_APP_ID";

// Configure API key authorization: app_key
var app_key = apiInstance.apiClient.authentications['app_key'];
app_key.apiKey = "YOUR_APP_KEY";

var opts = {
  'categoriesTaxonomy': 'iab-qag',
  'categoriesId': ['IAB7'],
  'text': 'fitness',
  'language': ['en'],
  'mediaVideosCountMin': 1,
  'mediaVideosCountMax': 1,
  'notMediaImagesFormat': ['GIF'],
  'publishedAtStart': 'NOW-1MONTH',
  'publishedAtEnd': 'NOW',
  'sortBy': 'relevance'
};

var callback = function(error, data, response) {
  if (error) {
    console.error(error);
  } else {
    console.log('The API has been called successfully.');
    console.log('=====================================');
    for (var i = 0; i < data.stories.length; i++){
      console.log(data.stories[i].title + " / " + data.stories[i].source.name);
    }
  }
};
apiInstance.listStories(opts, callback);
import aylien_news_api
from aylien_news_api.rest import ApiException

# Configure API key authorization: app_id
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'
# Configure API key authorization: app_key
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'

# create an instance of the API class
api_instance = aylien_news_api.DefaultApi()

opts = {
  'categories_taxonomy': 'iab-qag',
  'categories_id': ['IAB7'],
  'text': 'fitness',
  'language': ['en'],
  'media_videos_count_min': 1,
  'media_videos_count_max': 1,
  'not_media_images_format': ['GIF'],
  'published_at_start': 'NOW-1MONTH',
  'published_at_end': 'NOW',
  'sort_by': 'relevance'
}

try:
    # List stories
    api_response = api_instance.list_stories(**opts)
    print('The API has been called successfully.')
    print('=====================================')
    for story in api_response.stories:
      print(story.title + " / " + story.source.name)
except ApiException as e:
    print("Exception when calling DefaultApi->list_stories: %sn" % e)
<?php
require_once(__DIR__ . '/../vendor/autoload.php');

// Configure API key authorization: app_id
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-ID', 'YOUR_APP_ID');

// Configure API key authorization: app_key
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-Key', 'YOUR_APP_KEY');

$api_instance = new Aylien\NewsApi\Api\DefaultApi();

$opts = array(
  'categories_taxonomy' => 'iab-qag',
  'categories_id' => ['IAB7'],
  'text' => 'fitness', 
  'language' => ['en'],
  'media_videos_count_min' => 1,
  'media_videos_count_max' => 1,
  'not_media_images_format' => ['GIF'],
  'published_at_start' => 'NOW-1MONTH',
  'published_at_end' => 'NOW',
  'sort_by' => 'relevance'
);

try {
    $result = $api_instance->listStories($opts);
    print_r("The API has been called successfully.\n");
    print_r("=====================================\n");
    for($i = 0; $i < sizeof($result->getStories()); $i++){
      print_r($result->getStories()[$i]->getTitle() . " / " .
        $result->getStories()[$i]->getSource()->getName() . "\n");
    }
} catch (Exception $e) {
    print_r($e->getResponseObject()->getErrors());
    echo 'Exception when calling DefaultApi->listStories: ', $e->getMessage(), "\n";
}
?>
import com.aylien.newsapi.*;
import com.aylien.newsapi.auth.*;
import com.aylien.newsapi.models.*;
import com.aylien.newsapi.parameters.*;
import com.aylien.newsapi.api.DefaultApi;

import java.util.*;

public class Main {

    public static void main(String[] args) {
        ApiClient defaultClient = Configuration.getDefaultApiClient();

        // Configure API key authorization: app_id
        ApiKeyAuth app_id = (ApiKeyAuth) defaultClient.getAuthentication("app_id");
        app_id.setApiKey("YOUR_APP_ID");

        // Configure API key authorization: app_key
        ApiKeyAuth app_key = (ApiKeyAuth) defaultClient.getAuthentication("app_key");
        app_key.setApiKey("YOUR_APP_KEY");

        DefaultApi apiInstance = new DefaultApi();

        StoriesParams.Builder storiesBuilder = StoriesParams.newBuilder();

        storiesBuilder.setCategoriesTaxonomy("iab-qag");
        storiesBuilder.setCategoriesId(Arrays.asList("IAB7"));
        storiesBuilder.setText("fitness");
        storiesBuilder.setLanguage(Arrays.asList("en"));
        storiesBuilder.setMediaVideosCountMin(1);
        storiesBuilder.setMediaVideosCountMax(1);
        storiesBuilder.setNotMediaImagesFormat(Arrays.asList("GIF"));
        storiesBuilder.setPublishedAtStart("NOW-1MONTH");
        storiesBuilder.setPublishedAtEnd("NOW");
        storiesBuilder.setSortBy("relevance");

        try {
            Stories result = apiInstance.listStories(storiesBuilder.build());
            for (Iterator i = result.getStories().iterator(); i.hasNext();){
                Story story = i.next();
                System.out.println(story.getTitle() + " / " + story.getSource().getName());
            }
        } catch (ApiException e) {
            System.err.println("Exception when calling DefaultApi#listStories");
            e.printStackTrace();
        }
    }
}
# Load the gem
require 'aylien_news_api'

# Setup authorization
AylienNewsApi.configure do |config|
  # Configure API key authorization: app_id
  config.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'

  # Configure API key authorization: app_key
  config.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'
end

api_instance = AylienNewsApi::DefaultApi.new

opts = {
  :categories_taxonomy => 'iab-qag',
  :categories_id => ['IAB7'],
  :text => 'fitness',
  :language => ['en'],
  :media_videos_count_min => 1,
  :media_videos_count_max => 1,
  :not_media_images_format => ['GIF'],
  :published_at_start => "NOW-1MONTH",
  :published_at_end => "NOW",
  :sort_by => 'relevance'
}


begin
  #List stories
  result = api_instance.list_stories(opts)

  puts 'The API has been called successfully.'
  puts '====================================='
  result.stories.each do |story|
    puts "#{story.title} / #{story.source.name}"
  end
rescue AylienNewsApi::ApiError => e
  puts "Exception when calling DefaultApi->list_stories: #{e}"
  puts e.response_body
end
package main

// Import the library
import (
  "fmt"
  newsapi "github.com/AYLIEN/aylien_newsapi_go"
)

func main() {
  api := newsapi.NewDefaultApi()

  // Configure API key authorization: app_id
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-ID"] = "YOUR_APP_ID"

  // Configure API key authorization: app_key
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-Key"] = "YOUR_APP_KEY"

  storiesParams := &newsapi.StoriesParams{
    CategoriesTaxonomy:   "iab-qag",
    CategoriesId:         []string{"IAB7"},
    Text:                 "fitness",
    Language:             []string{"en"},
    MediaVideosCountMin:  "1",
    MediaVideosCountMax:  "1",
    NotMediaImagesFormat: []string{"GIF"},
    PublishedAtStart:     "NOW-1MONTH",
    PublishedAtEnd:       "NOW",
    SortBy:               "relevance"}

  storiesResponse, res, err := api.ListStories(storiesParams)
  if err != nil {
    panic(err)
  }
  _ = res

  for _, story := range storiesResponse.Stories {
    fmt.Println(story.Title, "/", story.Source.Name)
  }
}
using System;
using Aylien.NewsApi.Api;
using Aylien.NewsApi.Client;
using Aylien.NewsApi.Model;
using System.Collections.Generic;

namespace WorkingWithMediaResultsExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Configure API key authorization: app_id
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-ID", "YOUR_APP_ID");

            // Configure API key authorization: app_key
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-Key", "YOUR_APP_KEY");

            var apiInstance = new DefaultApi();

            try
            {
                // List stories
                Stories storiesResponse = apiInstance.ListStories(
                    categoriesTaxonomy: "iab-qag",
                    categoriesId: new List { "IAB7" },
                    text: "fitness",
                    language: new List { "en" },
                    mediaVideosCountMin: 1,
                    mediaVideosCountMax: 1,
                    notMediaImagesFormat: new List { "GIF" },
                    publishedAtStart: "NOW-1MONTH",
                    publishedAtEnd: "NOW",
                    sortBy: "relevance"
                );

                foreach (var story in storiesResponse._Stories)
                {
                    Console.WriteLine(story.Title + " / " + story.Source.Name);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception when calling DefaultApi.ListStories: " + e.Message);
            }
        }
    }
}

Alexa Rankings

The Alexa traffic rank is an estimate of a site's popularity on the internet. It is determined by measuring the volume of traffic a site gets over a rolling 3 month period. The Alexa rank is a scale of 0-50,000+. Sites with a lower Alexa rank will have higher volumes of traffic. For example, Google has an Alexa rank of 1.

Alexa can provide a rank for a website based on traffic volume from the entire world or based on traffic volume from any single nation you input.

  • Global ranking, based on how popular a website is globally
  • National ranking, based on how popular a site is in a given country. This is available for every country in the world, and is accessed by adding the ISO 3166-1 alpha-2 country code to your parameter.

Examples

The following example shows articles that are in English, are about Science, that published by sources with an Alexa rank between 25 and 100 and were published between 1 day ago and now.

var AylienNewsApi = require('aylien-news-api');

var apiInstance = new AylienNewsApi.DefaultApi();

// Configure API key authorization: app_id
var app_id = apiInstance.apiClient.authentications['app_id'];
app_id.apiKey = "YOUR_APP_ID";

// Configure API key authorization: app_key
var app_key = apiInstance.apiClient.authentications['app_key'];
app_key.apiKey = "YOUR_APP_KEY";

var opts = {
  'language': ['en'],
  'publishedAtStart': 'NOW-1DAY',
  'publishedAtEnd': 'NOW',
  'categoriesTaxonomy': 'iab-qag',
  'categoriesId': ['IAB15'],
  'sourceRankingsAlexaRankMin': 25,
  'sourceRankingsAlexaRankMax': 100
};

var callback = function(error, data, response) {
  if (error) {
    console.error(error);
  } else {
    console.log('API called successfully. Returned data: ' + data);
  }
};
apiInstance.listStories(opts, callback);
import aylien_news_api
from aylien_news_api.rest import ApiException

# Configure API key authorization: app_id
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'
# Configure API key authorization: app_key
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'

# create an instance of the API class
api_instance = aylien_news_api.DefaultApi()

language = ['en']
since = 'NOW-1DAY'
until = 'NOW'
categories_taxonomy = 'iab-qag'
categories_id = ['IAB15']
source_rankings_alexa_rank_min = 25
source_rankings_alexa_rank_max = 100


try:
    # List stories
    api_response = api_instance.list_stories(
      language=language,
      published_at_start=since,
      published_at_end=until,
      categories_taxonomy=categories_taxonomy,
      categories_id=categories_id,
      source_rankings_alexa_rank_min=source_rankings_alexa_rank_min,
      source_rankings_alexa_rank_max=source_rankings_alexa_rank_max
    )
    print(api_response)
except ApiException as e:
    print("Exception when calling DefaultApi->list_stories: %sn" % e)
<?php
require_once(__DIR__ . '/vendor/autoload.php');

// Configure API key authorization: app_id
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-ID', 'YOUR_APP_ID');

// Configure API key authorization: app_key
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-Key', 'YOUR_APP_KEY');

$api_instance = new Aylien\NewsApi\Api\DefaultApi();

$opts = array(
  'published_at_start' => 'NOW-1DAY',
  'published_at_end' => 'NOW',
  'language' => ['en'],
  'categories_taxonomy' => 'iab-qag',
  'categories_id' => ['IAB15'],
  'source_rankings_alexa_rank_min' => 25,
  'source_rankings_alexa_rank_max' => 100
);

try {
    $result = $api_instance->listStories($opts);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling DefaultApi->listStories: ', $e->getMessage(), "\n";
}
?>
package com.aylien.newsapisample;

import com.aylien.newsapi.*;
import com.aylien.newsapi.auth.*;
import com.aylien.newsapi.models.*;
import com.aylien.newsapi.parameters.*;
import com.aylien.newsapi.api.DefaultApi;

import java.util.*;

public class Main {

  public static void main(String[] args) {
    ApiClient defaultClient = Configuration.getDefaultApiClient();

    // Configure API key authorization: app_id
    ApiKeyAuth app_id = (ApiKeyAuth) defaultClient.getAuthentication("app_id");
    app_id.setApiKey("YOUR_APP_ID");

    // Configure API key authorization: app_key
    ApiKeyAuth app_key = (ApiKeyAuth) defaultClient.getAuthentication("app_key");
    app_key.setApiKey("YOUR_APP_KEY");

    DefaultApi apiInstance = new DefaultApi();

    StoriesParams.Builder storiesBuilder = StoriesParams.newBuilder();

    List language = Arrays.asList("en");
    String since = "NOW-1DAY";
    String until = "NOW";
    String categoriesTaxonomy = "iab-qag";
    List categoriesId = Arrays.asList("IAB15");
    Integer sourceRankingsAlexaRankMin = 25;
    Integer sourceRankingsAlexaRankMax = 100;

    storiesBuilder.setLanguage(language);
    storiesBuilder.setPublishedAtStart(since);
    storiesBuilder.setPublishedAtEnd(until);
    storiesBuilder.setCategoriesTaxonomy(categoriesTaxonomy);
    storiesBuilder.setCategoriesId(categoriesId);
    storiesBuilder.setSourceRankingsAlexaRankMin(sourceRankingsAlexaRankMin);
    storiesBuilder.setSourceRankingsAlexaRankMax(sourceRankingsAlexaRankMax);

    try {
      Stories result = apiInstance.listStories(storiesBuilder.build());
      System.out.println(result);
    } catch (ApiException e) {
      System.err.println("Exception when calling DefaultApi#listStories");
      e.printStackTrace();
    }
  }
}
# Load the gem
require 'aylien_news_api'

# Setup authorization
AylienNewsApi.configure do |config|
  # Configure API key authorization: app_id
  config.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'

  # Configure API key authorization: app_key
  config.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'
end

api_instance = AylienNewsApi::DefaultApi.new

opts = {
  :published_at_start => "NOW-1DAY",
  :published_at_end => "NOW",
  :language => ["en"],
  :categories_taxonomy => "iab-qag",
  :categories_id => ["IAB15"],
  :source_rankings_alexa_rank_min => 25,
  :source_rankings_alexa_rank_max => 100
}


begin
  #List stories
  result = api_instance.list_stories(opts)
  puts result
rescue AylienNewsApi::ApiError => e
  puts "Exception when calling DefaultApi->list_stories: #{e}"
end
package main

// Import the library
import (
  "fmt"
  newsapi "github.com/AYLIEN/aylien_newsapi_go"
)

func main() {
  api := newsapi.NewDefaultApi()

  // Configure API key authorization: app_id
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-ID"] = "YOUR_APP_ID"

  // Configure API key authorization: app_key
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-Key"] = "YOUR_APP_KEY"

  until := "NOW"
  since := "NOW-1DAY"
  language := []string{"en"}
  categoriesTaxonomy := "iab-qag"
  categoriesId := []string{"IAB15"}
  sourceRankingsAlexaRankMin := int32(25)
  sourceRankingsAlexaRankMax := int32(100)

  storiesParams := &newsapi.StoriesParams{
    Language:                   language,
    PublishedAtStart:           since,
    PublishedAtEnd:             until,
    CategoriesTaxonomy:         categoriesTaxonomy,
    CategoriesId:               categoriesId,
    SourceRankingsAlexaRankMin: sourceRankingsAlexaRankMin,
    SourceRankingsAlexaRankMax: sourceRankingsAlexaRankMax}

  storiesResponse, res, err := api.ListStories(storiesParams)
  if err != nil {
    panic(err)
  }
  _ = res

  fmt.Println(storiesResponse)
}
using System;
using Aylien.NewsApi.Api;
using Aylien.NewsApi.Client;
using Aylien.NewsApi.Model;
using System.Collections.Generic;

namespace ConsoleApplicationExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Configure API key authorization: app_id
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-ID", "YOUR_APP_ID");

            // Configure API key authorization: app_key
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-Key", "YOUR_APP_KEY");

            var apiInstance = new DefaultApi();

            var since = "NOW-1DAY";
            var until = "NOW";
            var language = new List { "en" };
            var categoriesTaxonomy = "iab-qag";
            var categoriesId = new List { "IAB15" };
            var sourceRankingsAlexaRankMin = 10;
            var sourceRankingsAlexaRankMax = 100;

            try
            {
                // List stories
                Stories result = apiInstance.ListStories(
                    publishedAtStart: since,
                    publishedAtEnd: until,
                    language: language,
                    categoriesTaxonomy: categoriesTaxonomy,
                    categoriesId: categoriesId,
                    sourceRankingsAlexaRankMin: sourceRankingsAlexaRankMin,
                    sourceRankingsAlexaRankMax: sourceRankingsAlexaRankMax
                );
                Console.WriteLine(result);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception when calling DefaultApi.ListStories: " + e.Message);
            }
        }
    }
}

Clustering News Articles

Clustering is a data mining technique used to group similarly related objects together in groups or collections. It's an unsupervised classification method, meaning that data is classified without any pre-trained labels or categories, and is used for exploratory data analysis to find hidden patterns or groupings in data. It's a common technique used in text mining to identify similar, near duplicate and duplicate documents.

Clustering with the News API

Clustering is available in the following News API endpoints:

The News API offers three algorithms that you can choose from for clustering, depending on the type of data and format of results that you require.

STC (Suffix Tree Clustering)

STC is a linear time clustering algorithm (linear in the size of the document set), which is based on identifying phrases that are common to groups of documents. A phrase is an ordered sequence of one or more words. This algorithm treats documents as a string of words rather than a collection of words and thus operates using the proximity of information between words. Learn more

K-means

K-means clustering aims to partition n observations into k clusters in which each observation belongs to the cluster with the nearest mean, serving as a prototype of the cluster. Learn more

Lingo

Algorithm for clustering search results, which emphasizes cluster description quality, using algebraic transformations of the term-document matrix and frequent phrase extraction using suffix arrays. Learn more

Examples

The following example shows results for the "Brexit AND Ireland" search query, using the lingo algorithm and only returning English language stories.

var AylienNewsApi = require('aylien-news-api');

var apiInstance = new AylienNewsApi.DefaultApi();

// Configure API key authorization: app_id
var app_id = apiInstance.apiClient.authentications['app_id'];
app_id.apiKey = "YOUR_APP_ID";

// Configure API key authorization: app_key
var app_key = apiInstance.apiClient.authentications['app_key'];
app_key.apiKey = "YOUR_APP_KEY";

var opts = {
  'text': 'ireland AND brexit',
  'language': ['en'],
  'cluster': true,
  'cluster_algorithm': 'lingo',
  'per_page': 100
};

var callback = function(error, data, response) {
  if (error) {
    console.error(error);
  } else {
    console.log('API called successfully. Returned data: ' + JSON.stringify(data));
  }
};
apiInstance.listStories(opts, callback);
import aylien_news_api
from aylien_news_api.rest import ApiException

# Configure API key authorization: app_id
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'
# Configure API key authorization: app_key
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'

# create an instance of the API class
api_instance = aylien_news_api.DefaultApi()

text = 'ireland AND brexit'
language = ['en']
cluster = True
cluster_algorithm = 'lingo'
per_page = 100

try:
    # List stories
    api_response = api_instance.list_stories(
      language=language,
      text=text,
      cluster=cluster,
      cluster_algorithm=cluster_algorithm,
      per_page=per_page
    )
    print(api_response)
except ApiException as e:
    print("Exception when calling DefaultApi->list_stories: %sn" % e)
<?php
require_once(__DIR__ . '/vendor/autoload.php');

// Configure API key authorization: app_id
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-ID', 'YOUR_APP_ID');

// Configure API key authorization: app_key
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-Key', 'YOUR_APP_KEY');

$api_instance = new Aylien\NewsApi\Api\DefaultApi();

$opts = array(
  'language' => ['en'],
  'text' => 'ireland AND brexit',
  'cluster' => true,
  'cluster_algorithm' => 'lingo',
  'per_page' => 100
);

try {
    $result = $api_instance->listStories($opts);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling DefaultApi->listStories: ', $e->getMessage(), "\n";
}
?>
package com.aylien.newsapisample;

import com.aylien.newsapi.*;
import com.aylien.newsapi.auth.*;
import com.aylien.newsapi.models.*;
import com.aylien.newsapi.parameters.*;
import com.aylien.newsapi.api.DefaultApi;

import java.util.*;

public class Main {

    public static void main(String[] args) {
        ApiClient defaultClient = Configuration.getDefaultApiClient();

        // Configure API key authorization: app_id
        ApiKeyAuth app_id = (ApiKeyAuth) defaultClient.getAuthentication("app_id");
        app_id.setApiKey("YOUR_APP_ID");

        // Configure API key authorization: app_key
        ApiKeyAuth app_key = (ApiKeyAuth) defaultClient.getAuthentication("app_key");
        app_key.setApiKey("YOUR_APP_KEY");

        DefaultApi apiInstance = new DefaultApi();

        StoriesParams.Builder storiesBuilder = StoriesParams.newBuilder();

        List language = Arrays.asList("en");
        String text = "ireland AND brexit";
        boolean cluster = true;
        String clusterAlgorithm = "lingo";
        Integer perPage = 100;

        storiesBuilder.setLanguage(language);
        storiesBuilder.setText(text);
        storiesBuilder.setCluster(cluster);
        storiesBuilder.setClusterAlgorithm(clusterAlgorithm);
        storiesBuilder.setPerPage(perPage);

        try {
            Stories result = apiInstance.listStories(storiesBuilder.build());
            System.out.println(result);
        } catch (ApiException e) {
            System.err.println("Exception when calling DefaultApi#listStories");
            e.printStackTrace();
        }
    }
}
# Load the gem
require 'aylien_news_api'

# Setup authorization
AylienNewsApi.configure do |config|
  # Configure API key authorization: app_id
  config.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'

  # Configure API key authorization: app_key
  config.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'
end

api_instance = AylienNewsApi::DefaultApi.new

opts = {
  :language => ["en"],
  :text => "ireland AND brexit",
  :cluster => true,
  :cluster_algorithm => "lingo",
  :per_page => 100
}

begin
  #List stories
  result = api_instance.list_stories(opts)
  puts result
rescue AylienNewsApi::ApiError => e
  puts "Exception when calling DefaultApi->list_stories: #{e}"
end
package main

// Import the library
import (
  "fmt"
  newsapi "github.com/AYLIEN/aylien_newsapi_go"
)

func main() {
  api := newsapi.NewDefaultApi()

  // Configure API key authorization: app_id
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-ID"] = "YOUR_APP_ID"

  // Configure API key authorization: app_key
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-Key"] = "YOUR_APP_KEY"

  text := "ireland AND brexit"
  cluster := "true"
  clusterAlgorithm := "lingo"
  language := []string{"en"}
  perPage := int32(100)

  storiesParams := &newsapi.StoriesParams{
    Language:         language,
    Text:             text,
    Cluster:          cluster,
    ClusterAlgorithm: clusterAlgorithm,
    PerPage:          perPage}

  storiesResponse, res, err := api.ListStories(storiesParams)
  if err != nil {
    panic(err)
  }
  _ = res

  fmt.Println(storiesResponse)
}
using System;
using Aylien.NewsApi.Api;
using Aylien.NewsApi.Client;
using Aylien.NewsApi.Model;
using System.Collections.Generic;

namespace ConsoleApplicationExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Configure API key authorization: app_id
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-ID", "YOUR_APP_ID");

            // Configure API key authorization: app_key
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-Key", "YOUR_APP_KEY");

            var apiInstance = new DefaultApi();

            var text = "ireland AND brexit";
            var cluster = true;
            var clusterAlgorithm = "lingo";
            var language = new List { "en" };
            var perPage = 100;

            try
            {
                // List stories
                Stories result = apiInstance.ListStories(
                    text: text,
                    cluster: cluster,
                    language: language,
                    clusterAlgorithm: clusterAlgorithm,
                    perPage: perPage
                );
                Console.WriteLine(result);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception when calling DefaultApi.ListStories: " + e.Message);
            }
        }
    }
}

Working with Links In Count

The links in count is an estimate of the number of sites linking in, or backlinking, to a website. Generally sites with higher links in counts have more authority and higher traffic.

Examples

The following example shows articles that are in English, are about Science, that published by sources with back linking count between 100000 and 200000 and were published between 1 day ago and now.

var AylienNewsApi = require('aylien-news-api');

var apiInstance = new AylienNewsApi.DefaultApi();

// Configure API key authorization: app_id
var app_id = apiInstance.apiClient.authentications['app_id'];
app_id.apiKey = "YOUR_APP_ID";

// Configure API key authorization: app_key
var app_key = apiInstance.apiClient.authentications['app_key'];
app_key.apiKey = "YOUR_APP_KEY";

var opts = {
  'language': ['en'],
  'publishedAtStart': 'NOW-1DAY',
  'publishedAtEnd': 'NOW',
  'categoriesTaxonomy': 'iab-qag',
  'categoriesId': ['IAB15'],
  'sourceLinksInCountMin': 100000,
  'sourceLinksInCountMax': 200000
};

var callback = function(error, data, response) {
  if (error) {
    console.error(error);
  } else {
    console.log('API called successfully. Returned data: ' + data);
  }
};
apiInstance.listStories(opts, callback);
import aylien_news_api
from aylien_news_api.rest import ApiException

# Configure API key authorization: app_id
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'
# Configure API key authorization: app_key
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'

# create an instance of the API class
api_instance = aylien_news_api.DefaultApi()

language = ['en']
since = 'NOW-1DAY'
until = 'NOW'
categories_taxonomy = 'iab-qag'
categories_id = ['IAB15']
source_links_in_count_min = 100000
source_links_in_count_max = 200000


try:
    # List stories
    api_response = api_instance.list_stories(
      language=language,
      published_at_start=since,
      published_at_end=until,
      categories_taxonomy=categories_taxonomy,
      categories_id=categories_id,
      source_links_in_count_min=source_links_in_count_min,
      source_links_in_count_max=source_links_in_count_max
    )
    print(api_response)
except ApiException as e:
    print("Exception when calling DefaultApi->list_stories: %sn" % e)
<?php
require_once(__DIR__ . '/vendor/autoload.php');

// Configure API key authorization: app_id
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-ID', 'YOUR_APP_ID');

// Configure API key authorization: app_key
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-Key', 'YOUR_APP_KEY');

$api_instance = new Aylien\NewsApi\Api\DefaultApi();

$opts = array(
  'published_at_start' => 'NOW-1DAY',
  'published_at_end' => 'NOW',
  'language' => ['en'],
  'categories_taxonomy' => 'iab-qag',
  'categories_id' => ['IAB15'],
  'source_links_in_count_min' => 100000,
  'source_links_in_count_max' => 200000
);

try {
    $result = $api_instance->listStories($opts);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling DefaultApi->listStories: ', $e->getMessage(), "\n";
}
?>
package com.aylien.newsapisample;

import com.aylien.newsapi.*;
import com.aylien.newsapi.auth.*;
import com.aylien.newsapi.models.*;
import com.aylien.newsapi.parameters.*;
import com.aylien.newsapi.api.DefaultApi;

import java.util.*;

public class Main {

  public static void main(String[] args) {
    ApiClient defaultClient = Configuration.getDefaultApiClient();

    // Configure API key authorization: app_id
    ApiKeyAuth app_id = (ApiKeyAuth) defaultClient.getAuthentication("app_id");
    app_id.setApiKey("YOUR_APP_ID");

    // Configure API key authorization: app_key
    ApiKeyAuth app_key = (ApiKeyAuth) defaultClient.getAuthentication("app_key");
    app_key.setApiKey("YOUR_APP_KEY");

    DefaultApi apiInstance = new DefaultApi();

    StoriesParams.Builder storiesBuilder = StoriesParams.newBuilder();

    List language = Arrays.asList("en");
    String since = "NOW-1DAY";
    String until = "NOW";
    String categoriesTaxonomy = "iab-qag";
    List categoriesId = Arrays.asList("IAB15");
    Integer sourceLinksInCountMin = 100000;
    Integer sourceLinksInCountMax = 200000;

    storiesBuilder.setLanguage(language);
    storiesBuilder.setPublishedAtStart(since);
    storiesBuilder.setPublishedAtEnd(until);
    storiesBuilder.setCategoriesTaxonomy(categoriesTaxonomy);
    storiesBuilder.setCategoriesId(categoriesId);
    storiesBuilder.setSourceLinksInCountMin(sourceLinksInCountMin);
    storiesBuilder.setSourceLinksInCountMax(sourceLinksInCountMax);

    try {
      Stories result = apiInstance.listStories(storiesBuilder.build());
      System.out.println(result);
    } catch (ApiException e) {
      System.err.println("Exception when calling DefaultApi#listStories");
      e.printStackTrace();
    }
  }
}
# Load the gem
require 'aylien_news_api'

# Setup authorization
AylienNewsApi.configure do |config|
  # Configure API key authorization: app_id
  config.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'

  # Configure API key authorization: app_key
  config.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'
end

api_instance = AylienNewsApi::DefaultApi.new

opts = {
  :published_at_start => "NOW-1DAY",
  :published_at_end => "NOW",
  :language => ["en"],
  :categories_taxonomy => "iab-qag",
  :categories_id => ["IAB15"],
  :source_links_in_count_min => 100000,
  :source_links_in_count_max => 200000
}


begin
  #List stories
  result = api_instance.list_stories(opts)
  puts result
rescue AylienNewsApi::ApiError => e
  puts "Exception when calling DefaultApi->list_stories: #{e}"
end
package main

// Import the library
import (
  "fmt"
  newsapi "github.com/AYLIEN/aylien_newsapi_go"
)

func main() {
  api := newsapi.NewDefaultApi()

  // Configure API key authorization: app_id
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-ID"] = "YOUR_APP_ID"

  // Configure API key authorization: app_key
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-Key"] = "YOUR_APP_KEY"

  until := "NOW"
  since := "NOW-1DAY"
  language := []string{"en"}
  categoriesTaxonomy := "iab-qag"
  categoriesId := []string{"IAB15"}
  sourceLinksInCountMin := int32(100000)
  sourceLinksInCountMax := int32(200000)

  storiesParams := &newsapi.StoriesParams{
    Language:              language,
    PublishedAtStart:      since,
    PublishedAtEnd:        until,
    CategoriesTaxonomy:    categoriesTaxonomy,
    CategoriesId:          categoriesId,
    SourceLinksInCountMin: sourceLinksInCountMin,
    SourceLinksInCountMax: sourceLinksInCountMax}

  storiesResponse, res, err := api.ListStories(storiesParams)
  if err != nil {
    panic(err)
  }
  _ = res

  fmt.Println(storiesResponse)
}
using System;
using Aylien.NewsApi.Api;
using Aylien.NewsApi.Client;
using Aylien.NewsApi.Model;
using System.Collections.Generic;

namespace ConsoleApplicationExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Configure API key authorization: app_id
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-ID", "YOUR_APP_ID");

            // Configure API key authorization: app_key
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-Key", "YOUR_APP_KEY");

            var apiInstance = new DefaultApi();

            var since = "NOW-1DAY";
            var until = "NOW";
            var language = new List { "en" };
            var categoriesTaxonomy = "iab-qag";
            var categoriesId = new List { "IAB15" };
            var sourceLinksInCountMin = 100000;
            var sourceLinksInCountMax = 200000;

            try
            {
                // List stories
                Stories result = apiInstance.ListStories(
                    publishedAtStart: since,
                    publishedAtEnd: until,
                    language: language,
                    categoriesTaxonomy: categoriesTaxonomy,
                    categoriesId: categoriesId,
                    sourceLinksInCountMin: sourceLinksInCountMin,
                    sourceLinksInCountMax: sourceLinksInCountMax
                );
                Console.WriteLine(result);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception when calling DefaultApi.ListStories: " + e.Message);
            }
        }
    }
}