Getting Started

The AYLIEN News API is the most powerful way of sourcing, searching, and syndicating analyzed and enriched news content. It is accessed by sending HTTP requests to our server, which return JSON data to your client.

Here you’ll find everything you need to know about using the News API. If you’re a new user, you’ll need to grab an API Key here.

Using the API

You can call the API by sending HTTP POST or GET requests to https://api.newsapi.aylien.com/api/v1, followed by the endpoint name.

As your subscription is based on a story allowance, requests sent to endpoints that do not return stories do not count towards your allowance. Requests made to the Time Series, Trends, Coverages, and Histograms endpoints do not count towards your allowance.

To allow our servers to operate best for all of our users, requests from a single user are limited to 3 hits per second and 60 hits per minute on each endpoint.

Authorization

Requests to the API are authorized by adding the headers below, which you receive when you sign up:

  • X-AYLIEN-NewsAPI-Application-ID must be set to your Application ID.
  • X-AYLIEN-NewsAPI-Application-Key must be set to your Application Key.

Endpoints

When you send a request to our servers, you will send it to one of our seven endpoints, and each of these endpoints returns a different type of information. For example, our Stories endpoint returns stories along with data about each story, while the Time Series endpoint returns quantitative data on news content over time.

Each endpoint offers dozens of parameters – input fields where you specify your query, making it as detailed as you like. You do not have to fill in information for each parameter, just include parameters that are important to your query.

Since our subscription pricing is based on an allowance of stories, only the Stories, Related Stories, and Coverages endpoints count towards this allowance. The Autocompletes, Time Series, Trends, and Histograms endpoints do not count toward your allowance.

To see what information each endpoint returns, take a look in the documentation pages for each one, or jump right in and start making queries to them.

HTTP Statuses

Along with the HTTP methods that the API responds to, it will also return standard HTTP statuses, including error codes.

In the event of a problem, the status will contain an error code, while the body of the response will usually contain additional information about the problem that was encountered.

In general, if the status returned is in the 200 range, it indicates that the request was fulfilled successfully and that no error was encountered.

Return codes in the 400 range typically indicate that there was an issue with the request that was sent. Among other things, this could mean that you did not authenticate correctly, that you are requesting an action that you do not have authorization for, that the object you are requesting does not exist, or that your request is malformed.

If you receive a status in the 500 range, this generally indicates a server-side problem. This means that we are having an issue on our end and cannot fulfill your request currently.

Error Codes & Responses

Code Text Description
200 OK Success!
400 Bad Request The server cannot or will not process the request due to an apparent client error.
401 Unauthorized Authentication credentials were missing or incorrect.
404 Not Found The URI requested is invalid or the resource requested, such as a story, does not exist.
405 Method Not Allowed A request method is not supported for the requested resource.
414 URI Too Long The URI provided was too long for the server to process. The maximum Request URI size is 2 kB.
422 Unprocessable Entity The request was invalid or cannot be otherwise served.
429 Too Many Requests Usage limits are exceeded.
500 Internal Server Error An unexpected error has occurred and engineers have been informed. If you continue to have problems, contact support@aylien.com.
503 Service Unavailable The server is currently unavailable (because it is overloaded or down for maintenance).

Rate Limits

Rate limiting of the API is primarily considered on a per-application basis — or, more accurately described, per application ID you control.

Hits

Each endpoint is subject to a rate limit of 60 hits per minute and 3 hits per second.

Story Volumes

There are no limits on volume of stories for paid users unless they've asked for a Capped Spend. Trial users have a total volume limit of 14,000 stories during their trial period.

Response

When an application exceeds the rate limit for a given API endpoint, the AYLIEN News API will now return an HTTP 429 "Too Many Requests" response code. There are three response headers you can use to check your quota allowance, the number of hits remaining on your quota, and the time and date your quota will be reset:

  • X-RateLimit-Limit : The number of allowed requests in the current period
  • X-RateLimit-Remaining : The number of remaining requests in the current period
  • X-RateLimit-Reset : The remaining window before the rate limit resets in UTC epoch seconds

If you're using one of our SDKs, you can use the following methods to retrieve the above values:

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': 'trump',
  'sortBy': 'social_shares_count.facebook',
  'language': ['en'],
  'publishedAtStart': 'NOW-7DAYS',
  'publishedAtEnd': 'NOW', 
  'entitiesBodyLinksDbpedia': [
    'http://dbpedia.org/resource/Donald_Trump',
    'http://dbpedia.org/resource/Hillary_Rodham_Clinton'
  ]
};

var callback = function(error, data, response) {
  if (error) {
    console.error(error);
  } else {
    console.log('API called successfully. Rate limit headers are as follows:');
    console.log('X-RateLimit-Limit:', response.headers['x-ratelimit-limit']);
    console.log('X-RateLimit-Remaining:', response.headers['x-ratelimit-remaining']);
    console.log('X-RateLimit-Reset:', response.headers['x-ratelimit-reset']);
  }
};
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 = {
  'title': 'trump',
  'sort_by': 'social_shares_count.facebook',
  'language': ['en'],
  'published_at_start': 'NOW-7DAYS',
  'published_at_end': 'NOW',
  'entities_body_links_dbpedia': [
    'http://dbpedia.org/resource/Donald_Trump',
    'http://dbpedia.org/resource/Hillary_Rodham_Clinton'
  ]
}

try:
    # List stories
    api_response = api_instance.list_stories_with_http_info(**opts)

    print('API called successfully. Rate limit headers are as follows:')
    print("X-RateLimit-Limit: %s" % api_response[2]['X-RateLimit-Limit'])
    print("X-RateLimit-Remaining: %s" % api_response[2]['X-RateLimit-Remaining'])
    print("X-RateLimit-Reset: %s" % api_response[2]['X-RateLimit-Reset'])
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' => 'trump',
  'published_at_start' => 'NOW-7DAYS',
  'published_at_end' => 'NOW',
  'entities_body_links_dbpedia' => [
    'http://dbpedia.org/resource/Donald_Trump',
    'http://dbpedia.org/resource/Hillary_Rodham_Clinton'
  ],
  'language' => ['en'],
  'sort_by' => 'social_shares_count.facebook'
);

try {
    $result = $api_instance->listStoriesWithHttpInfo($opts);
    print_r("API called successfully. Rate limit headers are as follows:\n"); 
    print_r("X-RateLimit-Limit: " . $result[2]['X-RateLimit-Limit'] . "\n");
    print_r("X-RateLimit-Remaining: " . $result[2]['X-RateLimit-Remaining'] . "\n");
    print_r("X-RateLimit-Reset: " . $result[2]['X-RateLimit-Reset'] . "\n");
} catch (Exception $e) {
    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.setTitle("trump");
        storiesBuilder.setSortBy("social_shares_count.facebook");
        storiesBuilder.setLanguage(Arrays.asList("en"));
        storiesBuilder.setPublishedAtStart("NOW-7DAYS");
        storiesBuilder.setPublishedAtEnd("NOW");
        storiesBuilder.setEntitiesBodyLinksDbpedia(Arrays.asList(
                "http://dbpedia.org/resource/Donald_Trump",
                "http://dbpedia.org/resource/Hillary_Rodham_Clinton"
        ));

        try {
            Stories result = apiInstance.listStories(storiesBuilder.build());
            Map> responseHeaders = defaultClient.getResponseHeaders();

            System.out.println("API called successfully. Rate limit headers are as follows:");
            System.out.println("X-RateLimit-Limit: " + responseHeaders.get("X-RateLimit-Limit").get(0));
            System.out.println("X-RateLimit-Remaining: " + responseHeaders.get("X-RateLimit-Remaining").get(0));
            System.out.println("X-RateLimit-Reset: " + responseHeaders.get("X-RateLimit-Reset").get(0));
        } 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 => 'trump',
  :published_at_start => "NOW-7DAYS",
  :published_at_end => "NOW",
  :entities_body_links_dbpedia => [
    'http://dbpedia.org/resource/Donald_Trump',
    'http://dbpedia.org/resource/Hillary_Rodham_Clinton'
  ],
  :language => ['en'],
  :sort_by => 'social_shares_count.facebook'
}


begin
  #List stories
  result = api_instance.list_stories_with_http_info(opts)
  puts 'API called successfully. Rate limit headers are as follows:'
  puts "X-RateLimit-Limit: #{result[2]['X-RateLimit-Limit']}"
  puts "X-RateLimit-Remaining: #{result[2]['X-RateLimit-Remaining']}"
  puts "X-RateLimit-Reset: #{result[2]['X-RateLimit-Reset']}"
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"

  storiesParams := &newsapi.StoriesParams{
    Title:            "trump",
    Language:         []string{"en"},
    PublishedAtStart: "NOW-7DAYS",
    PublishedAtEnd:   "NOW",
    EntitiesBodyLinksDbpedia: []string{
      "http://dbpedia.org/resource/Donald_Trump",
      "http://dbpedia.org/resource/Hillary_Rodham_Clinton",
    },
    SortBy: "social_shares_count.facebook"}

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

  fmt.Println("API called successfully. Rate limit headers are as follows:")
  fmt.Println("X-Ratelimit-Limit: " + res.Header["X-Ratelimit-Limit"][0])
  fmt.Println("X-Ratelimit-Remaining: " + res.Header["X-Ratelimit-Remaining"][0])
  fmt.Println("X-Ratelimit-Reset: " + res.Header["X-Ratelimit-Reset"][0])
}
using System;
using Aylien.NewsApi.Api;
using Aylien.NewsApi.Client;
using Aylien.NewsApi.Model;
using System.Collections.Generic;

namespace RateLimitExample
{
    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
            {
                var result = apiInstance.ListStoriesWithHttpInfo(
                    title: "trump",
                    publishedAtStart: "NOW-7DAYS",
                    publishedAtEnd: "NOW",
                    language: new List { "en" },
                    entitiesBodyLinksDbpedia: new List {
                        "http://dbpedia.org/resource/Donald_Trump",
                        "http://dbpedia.org/resource/Hillary_Rodham_Clinton"
                    },
                    sortBy: "social_shares_count.facebook"
                );

                Console.WriteLine("API called successfully. Rate limit headers are as follows:");
                Console.WriteLine("X-RateLimit-Limit: " + result.Headers["X-RateLimit-Limit"]);
                Console.WriteLine("X-RateLimit-Remaining: " + result.Headers["X-RateLimit-Remaining"]);
                Console.WriteLine("X-RateLimit-Reset: " + result.Headers["X-RateLimit-Reset"]);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception when calling DefaultApi.ListStories: " + e.Message);
            }
        }
    }
}

Language Support

Our API supports multiple (human) languages which can be selected using the language[] parameter, supported by all of the endpoints. Please refer to the table below for valid language codes:

English German French Italian Spanish Portuguese
Language code (to be provided via language[] parameter) en de fr it es pt

Examples

The following example shows articles that are in Spanish or English 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', 'es'],
  'publishedAtStart': 'NOW-1DAY',
  'publishedAtEnd': 'NOW'
};

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', 'es']
since = 'NOW-1DAY'
until = 'NOW'

try:
    # List stories
    api_response = api_instance.list_stories(language=language,
                                             published_at_start=since,
                                             published_at_end=until)
    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', 'es']
);

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", "es");
        String since = "NOW-1DAY";
        String until = "NOW";

        storiesBuilder.setLanguage(language);
        storiesBuilder.setPublishedAtStart(since);
        storiesBuilder.setPublishedAtEnd(until);

        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', 'es']
}


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", "es"}

  storiesParams := &newsapi.StoriesParams{
    Language:         language,
    PublishedAtStart: since,
    PublishedAtEnd:   until}

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

  fmt.Println(storiesResponse)
}
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 Example
    {
        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();

            string since = "NOW-1DAY";
            string until = "NOW";
            List language = new List { "en", "es" };

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

GET or POST

All endpoints support GET method. The /coverages and /related_stories endpoints support both GET and POST methods.

If you're dealing with long text, please consider using POST.

URL Encoding

Remember to URL-encode your query. The following examples show how queries can be properly encoded.

Query URL-Encoded Query
published_at.start=NOW-30DAYS&categories.id[]=IAB1-5&entities.body.links.dbpedia[]=http://dbpedia.org/resource/Star_Wars&categories.taxonomy=iab-qag published_at.start=NOW-30DAYS&categories.id%5B%5D=IAB1-5&entities.body.links.dbpedia%5B%5D=http%3A%2F%2Fdbpedia.org%2Fresource%2FStar_Wars&categories.taxonomy=iab-qag
title=Trump OR Sanders&entities.title.text[]=election title=Trump+OR+Sanders&entities.title.text%5B%5D=election
title=Ireland&published_at.end=NOW-2MONTHS/DAY title=Ireland&published_at.end=NOW-2MONTHS%2FDAY

JSON or XML

By default the API returns JSON results. You can request results in JSON or XML formats for all of the endpoints.

To do so set Accept header to text/xml or application/json to change the format of your results.

Testing the News API with Postman

If you are looking for a quick and straightforward way of testing the News API and familiarizing yourself with its various endpoints and parameters, you may want to consider our Postman integration (in addition to our Interactive Documentation and our Query Builder).

Postman is a suite of tools for testing, building and documenting APIs which can be downloaded for free from here.

Once you've downloaded and installed Postman, follow the steps below to get up and running with the News API:

Step 1

Before starting, make sure you have created a News API account and have access to your App ID and Key. Click here to create a free account.

Step 2

Open Postman, and click on the Import button on the top left corner:

Opening the import dialog

Step 3

In the Import dialog, click on the Import From Link button and paste the following URL into the input box:

https://newsapi.aylien.com/swagger/spec/news-api.json

Importing the News API schema

Click on Import.

Step 4

Once the schema is imported, you should be able to see a new collection on the left hand side:

Selecting endpoints and adding headers

From here you can select an endpoint, for instance Stories > List Stories, and start configuring your request.

Adding your API credentials

The first step is to add your App ID and Key by clicking on Headers. This will reveal two fields (X-AYLIEN-NewsAPI-Application-ID and X-AYLIEN-NewsAPI-Application-Key) where you can add your credentials.

Step 5

After you've added your credentials, you can configure your request and set its parameters by clicking on Params. Doing so reveals all the available parameters for any endpoint, allowing you to view or edit any of the parameters:

Configuring your request

Once you're finished, click on Send to submit the request and retrieve the results in JSON format in the box below.