Making Your First Calls

The AYLIEN News API is the most powerful way of sourcing, searching, and syndicating analyzed and enriched news content. On this page, we’ll show you how easy it is to get up and running andmaking your first calls.

We’ll take you step-by-step through a few of the key capabilities of the News API. We’ll help you install your SDK, show you how easy it is to build a targeted search, and show you the power the quantitative analysis endpoints offered through the API.

Read more about the News API

Before we start:

Not an SDK fan? We use our SDKs in these examples because they're the quickest way to get started accessing the News API but don't worry, you can use with HTTP requests instead. The URLs for calling each endpoint are listed in the documentation pages for each one.

Want to skip ahead to the more advanced stuff? Check out the Interactive Documentation, where every parameter for every endpoint is listed.

With that out of the way, let's dive in!

The JSON story object

Results from your News API search are returned as Stories in JSON format containing up to 20 top-level fields. A full story object will contain 92 unique data points, most of which you can use as query parameters in calls to the Stories endpoint.

We can group the data in the JSON object into three types:

  • the story data (e.g. the story body, title),
  • story metadata (e.g. word count, publication date and time),
  • NLP enrichments - insights generated by our NLP engine about the story (the sentiment expressed, the topics discussed, and the entities mentioned).

Installng your SDK

pip install aylien-news-api
// npm
npm install aylien-news-api

// git

npm install AYLIEN/aylien_newsapi_nodejs

gem install aylien_news_api
go get github.com/AYLIEN/aylien_newsapi_go
{
  "require": {
    "aylien/newsapi": "~1.0.0"
  }
}
// then run "composer install"
// use NuGet package manager
Install-Package Aylien.NewsApi
// requiers Maven
// add this to your project's POM:
<dependency>
    <groupId>com.aylien.newsapi</groupId>
    <artifactId>client</artifactId>
    <version>0.5.1</version>
    <scope>compile</scope>
</dependency>

// Gradle
compile "com.aylien.newsapi:client:0.5.1"

//sbt
"com.aylien.newsapi" % "client" % "0.5.1"

You can install SDKs using various package managers or by cloning repos from GitHub.

The instructions on this page are abbreviated, you can find full instructons for installing your chosen SDK here.

Basic story search: keywords, dates, sorting


import aylien_news_api
from aylien_news_api.rest import ApiException
from pprint import pprint as pp

## Configure API credentials
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'
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()

## List our parameters as search operators
opts= {
    'title': 'Apple',
    'sort_by': 'relevance',
    'language': ['en'],
    'published_at_start': 'NOW-7DAYS',
    'published_at_end': 'NOW',
    'per_page': 1
}

try:
    ## Make a call to the Stories endpoint for stories that meet the criteria of the search operators
    api_response = api_instance.list_stories(**opts)
    pp(api_response)

except ApiException as e:
    print('Exception when calling DefaultApi->list_stories: %s\n' % e)
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': "Apple",
  'language': ["en"],
  'publishedAtStart': "NOW-7DAYS",
  'publishedAtEnd': "NOW",
  'sortBy': "relevance",
  'perPage': 1
};

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);
# 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: "Apple",
  language: ["en"],
  published_at_start: "NOW-7DAYS",
  published_at_end: "NOW",
  sort_by: "relevance",
  per_page: 1
}

begin
  #List Stories
  result = api_instance.list_stories(opts)
  puts result
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"

  title := "Apple"
  language := []string{"en"}
  publishedAtStart := "NOW-7DAYS"
  publishedAtEnd := "NOW"
  sortBy := "relevance"
  perPage := int32(1)

  storiesParams := &newsapi.StoriesParams{
    Title:                          title,
    Language:                       language,
    PublishedAtStart:               publishedAtStart,
    PublishedAtEnd:                 publishedAtEnd,
    SortBy:                         sortBy,
    PerPage:                        perPage}

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

  _ = res

  fmt.Println(storiesResponse)
}
<?php
/* 
  View all parameters and methods here:
  https://github.com/AYLIEN/aylien_newsapi_php/blob/master/docs/Api/DefaultApi.md#listStories
*/

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' => "Apple",
    'language' => array("en"),
    'published_at_start' => "NOW-7DAYS",
    'published_at_end' => "NOW",
    'sort_by' => "relevance",
    'per_page' => 1
);

try {
    $result = $api_instance->listStories($opts);
    print_r($result);
} catch (Exception $e) {
    print_r($e->getResponseObject()->getErrors());
    echo 'Exception when calling DefaultApi->listStories: ', $e->getMessage(), PHP_EOL;
}
?>
/* 
  View all parameters and methods here:
  https://github.com/AYLIEN/aylien_newsapi_csharp/blob/master/docs/DefaultApi.md#liststories
*/

using System;
using System.Diagnostics;
using Aylien.NewsApi.Api;
using Aylien.NewsApi.Client;
using Aylien.NewsApi.Model;
using System.Collections.Generic;

namespace Example
{
    public class ListStoriesExample
    {
        static void Main(string[] args)
        {
          Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-ID", "YOUR_APP_ID");
          Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-Key", "YOUR_APP_KEY");

            var apiInstance = new DefaultApi();
            var title = "Apple";
            var language = new List<string>() { "en"};
            var publishedAtStart = "NOW-10DAYS";
            var publishedAtEnd = "NOW";
            var sortBy = "relevance";
            var perPage = 1;

            try
            {
                // List Stories
                Stories result = apiInstance.ListStories(
                    title: title,
                    language: language,
                    publishedAtStart: publishedAtStart,
                    publishedAtEnd: publishedAtEnd,
                    sortBy: sortBy,
                    perPage: perPage
                );
                Debug.WriteLine(result);
            }
            catch (Exception e)
            {
                Debug.Print("Exception when calling DefaultApi.ListStories: " + e.Message);
            }
        }
    }
}
/* 
  View all parameters and methods here:
  https://github.com/AYLIEN/aylien_newsapi_java/blob/master/docs/DefaultApi.md#listStories
*/

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.Arrays;
import java.util.List;

public class Basic {

    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 = "Apple";
        List<String> language = Arrays.asList("en");
        String publishedAtStart = "NOW-7DAYS";
        String publishedAtEnd = "NOW";
        String sortBy = "relevance";
        Integer perPage = 1;

        StoriesParams.Builder storiesBuilder = StoriesParams.newBuilder();

        storiesBuilder.setTitle(title);
        storiesBuilder.setLanguage(language);
        storiesBuilder.setPublishedAtStart(publishedAtStart);
        storiesBuilder.setPublishedAtEnd(publishedAtEnd);
        storiesBuilder.setSortBy(sortBy);
        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();
        }
    }
}

The script on the right will get you started with your first call to the News API's Stories endpoint (remember to paste in your credentials before you run it).

There are 87 separate parameters for querying the Stories endpoint, some of which support Boolean operators. The parameters in the template code will retrieve the most relevant story published in the last seven days that contains the string "Apple" in the title.

The published_at parameters accept both Date Math Syntax and dates in the format 2019-03-02T00:00:00Z.

The per_page parameter here has been supplied with the value of 1, meaning we will retrieve one story, but this can be set as high as 100. If you want to source more than 100 stories, you can use cursor. The per_page parameter defaults to 10, so not including this field in your search will return 10 stories.

The sort_by parameter allows you to sort results according to six criteria:

  • Relevance
  • Recency
  • Hotness
  • Number of photos/videos
  • Alexa ranking of domain (global/national)

Targeted story search: categories, entities, sentiment


import aylien_news_api
from aylien_news_api.rest import ApiException

aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'
api_instance = aylien_news_api.DefaultApi()

opts= {
    'entities_title_links_dbpedia': ['http://dbpedia.org/resource/Apple'],
    'categories_taxonomy': 'iptc-subjectcode',
    'categories_id': ['10000000'],
    'sentiment_body_polarity': 'neutral',
    'sort_by': 'recency',
    'language': ['en'],
    'published_at_start': 'NOW-1MONTH',
    'published_at_end': 'NOW',
    'per_page': 1
}

try:
    api_response = api_instance.list_stories(**opts)
    story = api_response.stories[0]

    ## Select the information that interests us from the story object
    print(story.title)
    print(story.media[0].url)
    print(story.links.permalink)
    print(story.summary.sentences[:2])

except ApiException as e:
    print('Exception when calling DefaultApi->list_stories: %s\n' % e)
var AylienNewsApi = require('aylien-news-api');

var apiInstance = new AylienNewsApi.DefaultApi();


var app_id = apiInstance.apiClient.authentications['app_id'];
app_id.apiKey = "YOUR_APP_ID";

var app_key = apiInstance.apiClient.authentications['app_key'];
app_key.apiKey = "YOUR_APP_KEY";

var opts = {
  'entitiesBodyLinksDbpedia': ["http://dbpedia.org/resource/Apple"],
  'sentimentBodyPolarity': "neutral",
  'categoriesTaxonomy': "iptc-subjectcode",
  'categoriesId': ["10000000"],
  'language': ["en"],
  'publishedAtStart': "NOW-1MONTH",
  'publishedAtEnd': "NOW",
  'sortBy': "recency",
  'perPage': 1
};

var callback = function(error, data, response) {
  if (error) {
    console.error(error);
  } else {
    var title   = data['stories'][0]['title'];
    var media   = data['stories'][0]['media'][0]['url'];
    var url     = data['stories'][0]['links']['permalink'];
    var summary = data['stories'][0]['summary']['sentences'][0];
    console.log(title + '\n' + media + '\n' + url + '\n' + summary + '\n' + shares);
  }
};
apiInstance.listStories(opts, callback);
require 'aylien_news_api'

AylienNewsApi.configure do |config|
  config.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'
  config.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'
end
api_instance = AylienNewsApi::DefaultApi.new

opts = { 
  entities_title_links_dbpedia: ["http://dbpedia.org/resource/Apple"],
  sentiment_body_polarity: "neutral",
  categories_taxonomy: "iptc-subjectcode",
  categories_id: ["10000000"],
  language: ["en"],
  published_at_start: "NOW-1MONTH",
  published_at_end: "NOW",
  sort_by: "recency",
  per_page: 1
}

begin

  result = api_instance.list_stories(opts)

  ## Select some JSON fields from teh first story result  
  story = result.stories[0]
  puts story.title
  puts story.media[0].url
  puts story.links.permalink
  puts story.summary.sentences[0, 2]

rescue AylienNewsApi::ApiError => e
  puts "Exception when calling DefaultApi->list_stories: #{e}"
  puts e.response_body
end
package main

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

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

  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-ID"] = "YOUR_APP_ID"
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-Key"] = "YOUR_APP_KEY"

  entitiesTitleLinksDbpedia := []string{"http://dbpedia.org/resource/Apple"}
  categoriesTaxonomy := "iptc-subjectcode"
  categoriesId := []string{"10000000"}
  sentimentBodyPolarity := "neutral"
  language := []string{"en"}
  publishedAtStart := "NOW-1MONTH"
  publishedAtEnd := "NOW"
  sortBy := "hotness"
  perPage := int32(1)

  storiesParams := &newsapi.StoriesParams{
    EntitiesTitleLinksDbpedia:      entitiesTitleLinksDbpedia,
    CategoriesTaxonomy:             categoriesTaxonomy,
    CategoriesId:                   categoriesId,
    SentimentBodyPolarity:          sentimentBodyPolarity,
    Language:                       language,
    PublishedAtStart:               publishedAtStart,
    PublishedAtEnd:                 publishedAtEnd,
    SortBy:                         sortBy,
    PerPage:                        perPage}

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

  _ = res
  for _, story := range storiesResponse.Stories {
    fmt.Println(story.Title, " / ", story.Source.Name, "\n")
    fmt.Println(story.Links.Permalink, "\n")
    fmt.Println(story.Summary.Sentences[0:3])
  }
}
<?php
/* 
  View all parameters and methods here:
  https://github.com/AYLIEN/aylien_newsapi_php/blob/master/docs/Api/DefaultApi.md#listStories
*/

require_once(__DIR__ . '/vendor/autoload.php');

Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-ID', 'YOUR_APP_ID');
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-Key', 'YOUR_APP_KEY');

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


$opts = array(
    'entities_title_links_dbpedia' => array("http://dbpedia.org/resource/Apple"),
    'sentimentBodyPolarity' => "neutral",
    'categoriesTaxonomy' => "iptc-subjectcode",
    'categoriesId' => array("10000000"),
    'language' => array("en"),
    'published_at_start' => "NOW-1MONTH",
    'published_at_end' => "NOW",
    'sort_by' => "recency",
    'per_page' => 1
);

try {
    $result = $api_instance->listStories($opts);
    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(), PHP_EOL;
}
?>
using System;
using System.Diagnostics;
using Aylien.NewsApi.Api;
using Aylien.NewsApi.Client;
using Aylien.NewsApi.Model;
using System.Collections.Generic;

namespace Example
{
    public class ListStoriesExample
    {
        static void Main(string[] args)
        {
          Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-ID", "YOUR_APP_ID");
          Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-Key", "YOUR_APP_KEY");

            var apiInstance = new DefaultApi();
            var entitiesTitleLinksDbpedia = new List<string>() { "http://dbpedia.org/resource/Apple" };
            var language = new List<string>() { "en"};
            var publishedAtStart = "NOW-10DAYS";
            var publishedAtEnd = "NOW";
            var categoriesTaxonomy = "iab-qag";
            var categoriesId = new List<string>() { "IAB15" };
            var sentimentBodyPolarity = "neutral";
            var sortBy = "published_at";
            var perPage = 1;

            try
            {
                // List Stories
                Stories result = apiInstance.ListStories(
                    entitiesTitleLinksDbpedia: entitiesTitleLinksDbpedia,
                    categoriesTaxonomy: categoriesTaxonomy,
                    categoriesId: categoriesId,
                    language: language,
                    publishedAtStart: publishedAtStart,
                    publishedAtEnd: publishedAtEnd,
                    sentimentBodyPolarity: sentimentBodyPolarity,
                    sortBy: sortBy,
                    perPage: perPage
                );
                Debug.WriteLine(result);
            }
            catch (Exception e)
            {
                Debug.Print("Exception when calling DefaultApi.ListStories: " + e.Message);
            }
        }
    }
}
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.Arrays;
import java.util.Iterator;
import java.util.List;

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<String> entitiesTitleLinksDbpedia = Arrays.asList("http://dbpedia.org/resource/Apple");
        String categoriesTaxonomy = "iptc-subjectcode";
        List<String> categoriesId = Arrays.asList("04000000");
        String sentimentBodyPolarity = "neutral";
        List<String> language = Arrays.asList("en");
        String publishedAtStart = "NOW-1MONTH";
        String publishedAtEnd = "NOW";
        Integer perPage = 1;

        StoriesParams.Builder storiesBuilder = StoriesParams.newBuilder();

        storiesBuilder.setEntitiesTitleLinksDbpedia(entitiesTitleLinksDbpedia);
        storiesBuilder.setCategoriesTaxonomy(categoriesTaxonomy);
        storiesBuilder.setCategoriesId(categoriesId);
        storiesBuilder.setSentimentBodyPolarity(sentimentBodyPolarity);
        storiesBuilder.setLanguage(language);
        storiesBuilder.setPublishedAtStart(publishedAtStart);
        storiesBuilder.setPublishedAtEnd(publishedAtEnd);
        storiesBuilder.setSortBy(sortBy);
        storiesBuilder.setPerPage(perPage);

        try {
            Stories result = apiInstance.listStories(storiesBuilder.build());
            for (Iterator<Story> i = result.getStories().iterator(); i.hasNext();){
                System.out.println("----------------------------------------------");
                Story story = i.next();
                System.out.println("---Title");
                System.out.println(story.getTitle() + " / " + story.getSource().getName());
                System.out.println("---Body");
                System.out.println(story.getBody());
                System.out.println("---First two sentences of Summary");
                System.out.println(story.getSummary().getSentences().subList(0,1));
            }
        } catch (ApiException e) {
            System.err.println("Exception when calling DefaultApi#listStories");
            e.printStackTrace();
        }
    }
}

To leverage some more of the News API’s capabilities, we’re going to use a sample script that utilizes some of the NLP enrichments as parameters in our search, namely the categories, entities, and sentiment parameters.

Instead of searching for the keyword of "Apple", this script on the right uses the entities parameter to search separately for apples (the fruit) and Apple (the company) and limit our search to the lifestyle category of the IPTC taxonomy. To search for the latter, replace Apple with Apple_Inc..

Also, instead of returning the entire story object JSON again, we’re going to select some of the JSON fields to create a consumable summary.

"Could this be the dawn of a new hard cider era for New Jersey apple growers?"

Apple

- "The rebirth of New Jersey’s hard cider industry could be in the hands of a 29-year-old Rutgers University researcher."
- "Megan Muehlbauer, a scientist at the university’s New Jersey Agricultural Experiment Station, has been testing dozens of varieties of traditional heirloom apples used for hard cider to find ones that can successfully grow in the state."

Again, be sure to to play around with the parameters and check out the support guides. For categories:

For entities:

Expanding and refining your search with Boolean operators


import aylien_news_api
from aylien_news_api.rest import ApiException
from pprint import pprint as pp

aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'
api_instance = aylien_news_api.DefaultApi()

opts= {
    'text': 'Trump AND Clinton',
    'categories_taxonomy': 'iptc-subjectcode',
    'categories_id': ['11000000'],
    'not_categories_id': ['15000000', '16000000'],
    'sentiment_body_polarity': 'neutral',
    'language': ['en', 'es'],
    'published_at_start': 'NOW-1MONTH',
    'published_at_end': 'NOW',
    'per_page': 1
}

try:
    api_response = api_instance.list_stories(**opts)
    story = api_response['stories'][0]
    pp(story)

except ApiException as e:
    print('Exception when calling DefaultApi->list_stories: %s\n' % e)
var AylienNewsApi = require('aylien-news-api');

var apiInstance = new AylienNewsApi.DefaultApi();

var app_id = apiInstance.apiClient.authentications['app_id'];
app_id.apiKey = "YOUR_APP_ID";

var app_key = apiInstance.apiClient.authentications['app_key'];
app_key.apiKey = "YOUR_APP_KEY";

var opts = {
  'title': "Trump AND Clinton",
  'categoriesTaxonomy': "iptc-subjectcode",
  'notCategoriesId': ["11000000"],
  'not_sentiment_body_polarity': "neutral",
  'language': ["en", "es"],
  'publishedAtStart': "NOW-1MONTH",
  'publishedAtEnd': "NOW",
  'perPage': 1
};

var callback = function(error, data, response) {
  if (error) {
    console.error(error);
  } else {
    var title   = data['stories'][0]['title'];
    var media   = data['stories'][0]['media'][0]['url'];
    var url     = data['stories'][0]['links']['permalink'];
    var summary = data['stories'][0]['summary']['sentences'][0];
    console.log(title + '\n' + media + '\n' + url + '\n' + summary);
  }
};
apiInstance.listStories(opts, callback);
require 'aylien_news_api'

AylienNewsApi.configure do |config|
  config.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'
  config.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'
end
api_instance = AylienNewsApi::DefaultApi.new

api_instance = AylienNewsApi::DefaultApi.new

opts = { 
  title: 'Trump AND Clinton',
  categories_taxonomy: "iptc-subjectcode",
  not_categories_id: ["04000000"],
  not_sentiment_body_polarity: "neutral",
  language: ["en", "es"],
  published_at_start: "NOW-1MONTH",
  published_at_end: "NOW",
  per_page: 1
}

begin
  #List Stories
  result = api_instance.list_stories(opts)
  puts result
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()

  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-ID"] = "YOUR_APP_ID"
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-Key"] = "YOUR_APP_KEY"

  title := "Trump AND Clinton"
  categoriesTaxonomy := "iptc-subjectcode"
  categoriesId := []string{"04000000", "05000000"}
  notCategoriesId := []string{"15000000"}
  notSentimentBodyPolarity := "positive"
  language := []string{"en"}
  publishedAtStart := "NOW-1MONTH"
  publishedAtEnd := "NOW"
  perPage := int32(1)

  storiesParams := &newsapi.StoriesParams{
    Title:                          title,
    CategoriesTaxonomy:             categoriesTaxonomy,
    CategoriesId:                   categoriesId,
    NotCategoriesId:                notCategoriesId,
    NotSentimentBodyPolarity:       notSentimentBodyPolarity,
    Language:                       language,
    PublishedAtStart:               publishedAtStart,
    PublishedAtEnd:                 publishedAtEnd,
    PerPage:                        perPage}

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

  _ = res

  fmt.Println(storiesResponse)
}
<?php
require_once(__DIR__ . '/vendor/autoload.php');

Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-ID', 'YOUR_APP_ID');
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-Key', 'YOUR_APP_KEY');

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


$opts = array(
    'title' => "Trump AND Clinton",
    'categoriesTaxonomy' => "iptc-subjectcode",
    'notCategoriesId' => array("04000000"),
    'notSentimentBodyPolarity' => "neutral",
    'language' => array("en", "es"),
    'published_at_start' => "NOW-1MONTH",
    'published_at_end' => "NOW",
    'per_page' => 1
);

try {
    $result = $api_instance->listStories($opts);
    print_r($result);
} catch (Exception $e) {
    print_r($e->getResponseObject()->getErrors());
    echo 'Exception when calling DefaultApi->listStories: ', $e->getMessage(), PHP_EOL;
}
?>
using System;
using System.Diagnostics;
using Aylien.NewsApi.Api;
using Aylien.NewsApi.Client;
using Aylien.NewsApi.Model;
using System.Collections.Generic;

namespace Example
{
    public class ListStoriesExample
    {
        static void Main(string[] args)
        {
          Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-ID", "YOUR_APP_ID");
          Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-Key", "YOUR_APP_KEY");

            var apiInstance = new DefaultApi();
            var title = "Trump AND Clinton" ;
            var language = new List<string>() { "en"};
            var publishedAtStart = "NOW-10DAYS";
            var publishedAtEnd = "NOW";
            var categoriesTaxonomy = "iptc-newscodes";
            var categoriesId = new List<string>() { "04000000" };
            var notCategoriesId = new List<string>() { "01000000" };
            var notSentimentBodyPolarity = "positive";
            var perPage = 1;

            try
            {
                // List Stories
                Stories result = apiInstance.ListStories(
                    title: Title,
                    categoriesTaxonomy: categoriesTaxonomy,
                    categoriesId: categoriesId,
                    notCategoriesId: notCategoriesId,
                    language: language,
                    publishedAtStart: publishedAtStart,
                    publishedAtEnd: publishedAtEnd,
                    notSentimentBodyPolarity: notSentimentBodyPolarity,
                    perPage: perPage
                );
                Debug.WriteLine(result);
            }
            catch (Exception e)
            {
                Debug.Print("Exception when calling DefaultApi.ListStories: " + e.Message);
            }
        }
    }
}
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.Arrays;
import java.util.List;

public class Boolean {

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

        ApiKeyAuth app_id = (ApiKeyAuth) defaultClient.getAuthentication("app_id");
        app_id.setApiKey("YOUR_APP_ID");
        ApiKeyAuth app_key = (ApiKeyAuth) defaultClient.getAuthentication("app_key");
        app_key.setApiKey("YOUR_APP_KEY");

        DefaultApi apiInstance = new DefaultApi();

        String title = "Trump AND Clinton";
        String categoriesTaxonomy = "iptc-subjectcode";
        List<String> notCategoriesId = Arrays.asList("04000000");
        String notSentimentBodyPolarity = "neutral";
        List<String> language = Arrays.asList("en");
        String publishedAtStart = "NOW-1MONTH";
        String publishedAtEnd = "NOW";
        Integer perPage = 1;

        StoriesParams.Builder storiesBuilder = StoriesParams.newBuilder();

        storiesBuilder.setTitle(title);
        storiesBuilder.setCategoriesTaxonomy(categoriesTaxonomy);
        storiesBuilder.setNotCategoriesId(notCategoriesId);
        storiesBuilder.setNotSentimentBodyPolarity(notSentimentBodyPolarity);
        storiesBuilder.setLanguage(language);
        storiesBuilder.setPublishedAtStart(publishedAtStart);
        storiesBuilder.setPublishedAtEnd(publishedAtEnd);
        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();
        }
    }
}

We can also refine or expand our News API queries with lists and Boolean operators.

Some parameters accept lists by default (such as categories_id and entities_body_links_dbpedia), and we can easily supply more than one value to them. When more than one value is present, they are presented as an AND Boolean operator.

Important parameters such as text, title, and body accept the AND, OR, and NOT Boolean operators.

Additionally, most parameters that do not support Boolean operators have a converse parameter that allows you to exclude values. For example, although the sentiment_body_polarity parameter does not accept Boolean operators, there is a parameter not_sentiment_body_polarity that allows you to exclude stories with a given sentiment value. To see the full list of these parameters for each endpoint, look at the endpoint's documentation page

Check out the News API's documentation page on using Booleans in your searches.

Time series data


import aylien_news_api
from aylien_news_api.rest import ApiException
from pprint import pprint as pp 

aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'
api_instance = aylien_news_api.DefaultApi()

## Add the 'period' field to the search operators
opts= {
    'title': 'Trump',
    'language': ['en'],
    'published_at_start': 'NOW-7DAYS',
    'published_at_end': 'NOW',
    'period': '+1DAY'
}

try:
    ## Make a call to the Timeseries endpoint
    api_response = api_instance.list_time_series(**opts)
    print(api_response)

except ApiException as e:
    print('Exception when calling DefaultApi->list_stories: %s\n' % e)

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

var apiInstance = new AylienNewsApi.DefaultApi();

var app_id = apiInstance.apiClient.authentications['app_id'];
app_id.apiKey = "YOUR_APP_ID";

var app_key = apiInstance.apiClient.authentications['app_key'];
app_key.apiKey = "YOUR_APP_KEY";

var opts = {
  'text': 'Trump',
  'language': ["en"],
  'publishedAtStart': "NOW-7DAYS",
  'publishedAtEnd': "NOW",
  'period': '+1DAY'
};

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

AylienNewsApi.configure do |config|
  config.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'
  config.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'
end
api_instance = AylienNewsApi::DefaultApi.new

opts = {
  title: 'Trump',
  language: ["en"],
  published_at_start: "NOW-1MONTH",
  published_at_end: "NOW",
  period: "+1DAY"
}

begin
  #List Time Series
  result = api_instance.list_time_series(opts)
  puts result
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()

  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-ID"] = "YOUR_APP_ID"
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-Key"] = "YOUR_APP_KEY"

  title := "Trump"
  language := []string{"en"}
  publishedAtStart := "NOW-7DAYS/DAY"
  publishedAtEnd := "NOW/DAY"
  period := "+1DAY"

  timeSeriesParams := &newsapi.TimeSeriesParams{
    Title:                          title,
    Language:                       language,
    PublishedAtStart:               publishedAtStart,
    PublishedAtEnd:                 publishedAtEnd,
    Period:                         period}

  timeSeriesResponse, res, err := api.ListTimeSeries(timeSeriesParams)
  if err != nil {
    panic(err)
  }

  _ = res

  fmt.Println(timeSeriesResponse)
}
<?php
require_once(__DIR__ . '/vendor/autoload.php');

Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-ID', 'YOUR_APP_ID');
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-Key', 'YOUR_APP_KEY');

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


$opts = array(
    'text' => "Trump",
    'language' => array("en"),
    'published_at_start' => "NOW-7DAYS",
    'published_at_end' => "NOW",
    'period' => "+1DAY"
);

try {
    $result = $api_instance->listTimeSeries($opts);
    print_r($result);
} catch (Exception $e) {
    print_r($e->getResponseObject()->getErrors());
    echo 'Exception when calling DefaultApi->listStories: ', $e->getMessage(), PHP_EOL;
}
?>
using System;
using System.Diagnostics;
using Aylien.NewsApi.Api;
using Aylien.NewsApi.Client;
using Aylien.NewsApi.Model;
using System.Collections.Generic;

namespace Example
{
    public class ListTimeSeriesExample
    {
        static void Main(string[] args)
        {
          Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-ID", "YOUR_APP_ID");
          Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-Key", "YOUR_APP_KEY");

            var apiInstance = new DefaultApi();
            var text = "Trump" ;
            var language = new List<string>() { "en"};
            var publishedAtStart = "NOW-10DAYS";
            var publishedAtEnd = "NOW";
            var period = "+1DAY";

            try
            {
                // List Time Series
                TimeSeriesList result = apiInstance.ListTimeSeries(
                    text: text,
                    language: language,
                    publishedAtStart: publishedAtStart,
                    publishedAtEnd: publishedAtEnd,
                    period: period

                );
                Debug.WriteLine(result);
            }
            catch (Exception e)
            {
              Debug.Print("Exception when calling DefaultApi.ListStories: " + e.Message);
            }
          }
      }
  }
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.Arrays;
import java.util.List;

public class TimeSeries {

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

        ApiKeyAuth app_id = (ApiKeyAuth) defaultClient.getAuthentication("app_id");
        app_id.setApiKey("YOUR_APP_ID");
        ApiKeyAuth app_key = (ApiKeyAuth) defaultClient.getAuthentication("app_key");
        app_key.setApiKey("YOUR_APP_KEY");

        DefaultApi apiInstance = new DefaultApi();

        String field = "entities.body.links.dbpedia";
        String title = "Trump";
        List<String> language = Arrays.asList("en");
        String publishedAtStart = "NOW-1MONTH";
        String publishedAtEnd = "NOW";


        TrendsParams.Builder trendsBuilder = TrendsParams.newBuilder();

        trendsBuilder.setField(field);
        trendsBuilder.setTitle(title);
        trendsBuilder.setLanguage(language);
        trendsBuilder.setPublishedAtStart(publishedAtStart);
        trendsBuilder.setPublishedAtEnd(publishedAtEnd);


        try {
            Trends result = apiInstance.listTrends(trendsBuilder.build());
            System.out.println(result);
        } catch (ApiException e) {
            System.err.println("Exception when calling DefaultApi#listStories");
            e.printStackTrace();
        }
    }
}

In addition to retrieving stories themselves, the Time Series and Trends endpoints allow us to retrieve quantitative information about publishing trends. To get started, let's use the Time Series endpoint to get an overview of publishing trends.

Calls to this endpoint don't return stories, and therefore do not count toward your story allowance. Instead, they return time series JSON objects, like this one:

You can use the script on the right to make your first call to the Time Series endpoint.

The published_at parameters specify the time frame we want to retrieve data on, while the period parameter specifies the length of time covered by each data point return in the results.

The period parameter can be set as low as one minute, and defaults to one day. The endpoint can return up to 100 data points per page.

In this script, we will receive data from the past seven days, with one data point from each day.

If you want to receive a count of the amount of stories published in a specific time frame, set the period parameter to match the length of time between the published_at parameters.


import aylien_news_api
from aylien_news_api.rest import ApiException
from pprint import pprint as pp 

aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'
aylien_news_api.configuration.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'
api_instance = aylien_news_api.DefaultApi()

## Add the 'field' you want to retrieve data on
field = "entities.body.links.dbpedia"

opts= {
    'title': 'Trump',
    'language': ['en'],
    'published_at_start': 'NOW-7DAYS',
    'published_at_end': 'NOW'
}

try:
    ## Make a call to the Trends endpoint using the operators and field arguments
    api_response = api_instance.list_trends(field, **opts)
    print(api_response)

except ApiException as e:
    print('Exception when calling DefaultApi->list_stories: %s\n' % e)

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

var apiInstance = new AylienNewsApi.DefaultApi();

var app_id = apiInstance.apiClient.authentications['app_id'];
app_id.apiKey = "YOUR_APP_ID";

var app_key = apiInstance.apiClient.authentications['app_key'];
app_key.apiKey = "YOUR_APP_KEY";

var field = "entities.body.links.dbpedia";

var opts = {
  'text': 'Trump',
  'language': ["en"],
  'publishedAtStart': "NOW-7DAYS",
  'publishedAtEnd': "NOW",
};

var callback = function(error, data, response) {
  if (error) {
    console.error(error);
  } else {
    console.log('API called successfully. Returned data: ' + JSON.stringify(data));;
  }
};
apiInstance.listTrends(field, opts, callback);
require 'aylien_news_api'

AylienNewsApi.configure do |config|
  config.api_key['X-AYLIEN-NewsAPI-Application-ID'] = 'YOUR_APP_ID'
  config.api_key['X-AYLIEN-NewsAPI-Application-Key'] = 'YOUR_APP_KEY'
end
api_instance = AylienNewsApi::DefaultApi.new

field = "entities.body.links.dbpedia"

opts = { 
  title: 'Trump',
  language: ["en"],
  published_at_start: "NOW-1MONTH",
  published_at_end: "NOW",
  period: "+1DAY"
}

begin
  #List Trends
  result = api_instance.list_trends(field, opts)
  puts result
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()

  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-ID"] = "YOUR_APP_ID"
  api.Configuration.APIKeyPrefix["X-AYLIEN-NewsAPI-Application-Key"] = "YOUR_APP_KEY"

  field := "entities.body.links.dbpedia"
  title := "Trump"
  language := []string{"en"}
  publishedAtStart := "NOW-7DAYS/DAY"
  publishedAtEnd := "NOW/DAY"

  trendsParams := &newsapi.TrendsParams{
    Field:                          field,
    Title:                          title,
    Language:                       language,
    PublishedAtStart:               publishedAtStart,
    PublishedAtEnd:                 publishedAtEnd}

  trendsResponse, res, err := api.ListTrends(trendsParams)
  if err != nil {
    panic(err)
  }

  _ = res

  fmt.Println(trendsResponse)
}
<?php
/* 
  View all parameters and methods here:
  https://github.com/AYLIEN/aylien_newsapi_php/blob/master/docs/Api/DefaultApi.md#listStories
*/

require_once(__DIR__ . '/vendor/autoload.php');

Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-ID', 'YOUR_APP_ID');
Aylien\NewsApi\Configuration::getDefaultConfiguration()->setApiKey('X-AYLIEN-NewsAPI-Application-Key', 'YOUR_APP_KEY');

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

$field = "entities.body.links.dbpedia";

$opts = array(
    'text' => "Trump",
    'language' => array("en"),
    'published_at_start' => "NOW-7DAYS",
    'published_at_end' => "NOW",
);

try {
    $result = $api_instance->listTrends($field, $opts);
    print_r($result);
} catch (Exception $e) {
    print_r($e->getResponseObject()->getErrors());
    echo 'Exception when calling DefaultApi->listStories: ', $e->getMessage(), PHP_EOL;
}
?>
using System;
using System.Diagnostics;
using Aylien.NewsApi.Api;
using Aylien.NewsApi.Client;
using Aylien.NewsApi.Model;
using System.Collections.Generic;

namespace Example
{
    public class ListTrendsExample
    {
        static void Main(string[] args)
        {
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-ID", "YOUR_APP_ID");
            Configuration.Default.ApiKey.Add("X-AYLIEN-NewsAPI-Application-Key", "YOUR_APP_KEY");

            var field = "entities.body.links.dbpedia";
            var apiInstance = new DefaultApi();
            var text = "Trump" ;
            var language = new List<string>() { "en"};
            var publishedAtStart = "NOW-10DAYS";
            var publishedAtEnd = "NOW";

            try
            {
                // List Trends
                TrendsList result = apiInstance.ListTrends(
                    field: field,
                    text: text,
                    language: language,
                    publishedAtStart: publishedAtStart,
                    publishedAtEnd: publishedAtEnd

                );
                Debug.WriteLine(result);
            }
            catch (Exception e)
            {
                Debug.Print("Exception when calling DefaultApi.ListStories: " + e.Message);
            }
        }
    }
}
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.Arrays;
import java.util.List;

public class Trends {

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

        ApiKeyAuth app_id = (ApiKeyAuth) defaultClient.getAuthentication("app_id");
        app_id.setApiKey("YOUR_APP_ID");
        ApiKeyAuth app_key = (ApiKeyAuth) defaultClient.getAuthentication("app_key");
        app_key.setApiKey("YOUR_APP_KEY");

        DefaultApi apiInstance = new DefaultApi();

        String field = "entities.body.links.dbpedia";
        String title = "Trump";
        List<String> language = Arrays.asList("en");
        String publishedAtStart = "NOW-1MONTH";
        String publishedAtEnd = "NOW";


        TrendsParams.Builder trendsBuilder = TrendsParams.newBuilder();

        trendsBuilder.setField(field);
        trendsBuilder.setTitle(title);
        trendsBuilder.setLanguage(language);
        trendsBuilder.setPublishedAtStart(publishedAtStart);
        trendsBuilder.setPublishedAtEnd(publishedAtEnd);


        try {
            Trends result = apiInstance.listTrends(trendsBuilder.build());
            System.out.println(result);
        } catch (ApiException e) {
            System.err.println("Exception when calling DefaultApi#listStories");
            e.printStackTrace();
        }
    }
}

The Trends endpoint is used to analyze quanitative data from the News API that is not spread over time.

The script on the right gives a sample use case of the this endpoint, returning a list of the most-mentioned entities in stories with "Trump" in the title over the past week. Once again, it returns a JSON object, like the one below.

Notice that you need to specify the field parameter to define what type of data you want to retrieve from the API. There are 14 values that the field parameter accepts.

Fields returned by the Trends endpoint
Metadata author.name source.name source.domain
Keywords keywords hashtags
Entities entities.title.text entities.title.type entities.title.links.dbpedia entities.body.text entities.body.type entities.body.links.dbpedia
Categories categories.id
Sentiment sentiment.title.polarity sentiment.body.polarity

What next?

Now that you're up and running with the News API, be sure to check out the product-oriented posts or take a look at the documentation for each endpoint.