Product

Getting started with the News API Part 1: Search

Introduction

At AYLIEN we pride ourselves on creating robust, scalable, developer friendly tools. We do our best to make it as easy as possible for our users to get up and running with our APIs. In this post we’re going to talk you through the process of making calls to our News API.

Our News API allows you to search and source news content from around the web in realtime. We use Machine Learning and Natural Language Processing to monitor, source and index news content at scale, providing an enriched and flexible news data source.

While making calls to the API is relatively simple, the possibilities for what you can do with the API are endless and the number of endpoints and parameters available can sometimes feel a little overwhelming to new users. For that reason we have decided to put together a series of blog posts aimed at guiding our users through some basic capabilities of the API.

This post will serve as a gentle introduction to the basic search capabilities of the API. Part 2 will then focus on how to analyze and draw meaningful insights from your stories.

First things first – familiarize yourself with the API

We recommend that you spend some time creating example queries using our demo/query builder. Once you’ve familiarised yourself with the concept of the API we’d strongly recommend spending some time in the interactive documentation section of our website to learn more about the various endpoints and parameters available in the API.

When you’ve got your head around how the API works, you can begin making some basic calls and collecting stories.

Making calls:

We’ve created SDKs for some of the most popular programming languages which make using the API super easy. Throughout this blog we’ve also included some code snippets for you to copy and build on.


1. Basic Search

Firstly, let’s look at how we can start monitoring news content and collecting stories. For the purpose of this guide we’ll assume the role of a news agency who want to gather news stories and insights around the presidential elections in the US.

Our API supports Boolean Search which allows you to build simple search queries using standard boolean operators. This means that you can build general or more targeted queries based on your interests and requirements.

The easiest way to start getting useful data from the API is to start collecting stories based around a search that interests you. As an example, let’s create a search that retrieves stories relevant to the US elections based on simple criteria;

Let’s build a query to retrieve stories that mention Donald Trump and Hillary Clinton that were published in the last 10 days and were written in Spanish.

The `text` parameter allows us to search by keyword. The ‘language’ parameter let’s you choose the language the stories are written in, and the `publishedAt` parameter allows you to easily set timeframes around when the articles you wish to retrieve have been published.

Note: Make sure you replace the APP_ID and APP_KEY placeholders with your own API credentials. If you haven’t got an API account you can sign up here.

Combined: “Donald Trump” AND “Hillary Clinton” in Spanish from the past 10 days

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(
  'text' => '"Hillary Clinton" AND "Donald Trump"',
  'published_at_start' => 'NOW-10DAYS',
  'published_at_end' => 'NOW',
  'language' => ['es']
);

try {
    $result = $api_instance->listStories($opts);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling DefaultApi->listStories: ', $e->getMessage(), "\n";
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 = '"Hillary Clinton" AND "Donald Trump"'
language = ['es']
since = 'NOW-10DAYS'
until = 'NOW'

try:
    # List stories
    api_response = api_instance.list_stories(text=text, language=language, published_at_start=since, published_at_end=until)
    print(api_response)
except ApiException as e:
    print("Exception when calling DefaultApi->list_stories: %s\n" % e)
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();

        String text = "\"Hillary Clinton\" AND \"Donald Trump\"";
        List language = new ArrayList() {{
            add("es");
        }};
        String since = "NOW-10DAYS";
        String until = "NOW";

        storiesBuilder.setText(text);
        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 = {
  :text => '"Hillary Clinton" AND "Donald Trump"',
  :published_at_start => "NOW-10DAYS",
  :published_at_end => "NOW",
  :language => ['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"

	text := "\"Hillary Clinton\" AND \"Donald Trump\""
	until := "NOW"
	since := "NOW-10DAYS"
	language := []string{"es"}

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

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

	fmt.Println(storiesResponse)
}
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' : '"Hillary Clinton" AND "Donald Trump"',
  'language' : ['es'],
  'publishedAtStart': 'NOW-10DAYS',
  '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);

 


2. Targeted search

So we’ve looked at how you can use keywords and some other basic parameters like the ‘published at’ time to build some useful queries. Now let’s look at how you can use some other parameters and endpoints to build some more targeted searches.

As with any election, opinions often tend to vary by geographic location. This is evident each time a US presidential election takes place as individual states are deemed ‘Red’ or ‘Blue’ depending on their republican or democratic bias. As we know, however, it is often the ‘swing’ states that well, swing the outcome one way or the other! These states and the news around them can be of particular interest to analysts, writers and the candidates themselves.

With this in mind, we’ll now show you how to narrow your search to focus on particular entities (places, people, companies, etc), from within specific categories and news sources. The parameters we will use here are:

  • `entities.body.links.dbpedia`
  • `categories.taxonomy`
  • `categories.ID`
  • `source.name`

For this example, we will search for mentions of two entities, which are traditionally two swing states: Ohio and Florida. We also want to ensure we are only collecting relevant stories so we will search for articles that are classified as in the Law, Government and Politics category. We will also only focus our search on three popular news sources: CNN, CBS News and Reuters

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(
  'text' => 'Trump',
  'published_at_start' => 'NOW-10DAYS',
  'published_at_end' => 'NOW',
  'categories_id' => ['IAB11'],
  'categories_taxonomy' => 'iab-qag',
  'source_name' => ['CNN', 'CBS', 'Reuters'],
  'entities_body_links_dbpedia' => [
    'http://dbpedia.org/resource/Ohio',
    'http://dbpedia.org/resource/Florida'
  ],
  'language' => ['en']
);

try {
    $result = $api_instance->listStories($opts);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling DefaultApi->listStories: ', $e->getMessage(), "\n";
}
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 = 'Trump'
since = 'NOW-10DAYS'
until = 'NOW'
categories_id = ['IAB11']
categories_taxonomy = 'iab-qag'
source_name = ['CNN', 'CBS', 'Reuters']
entities = [
  'http://dbpedia.org/resource/Ohio',
  'http://dbpedia.org/resource/Florida'
]
language = ['en']


try:
    # List stories
    api_response = api_instance.list_stories(text=text, categories_taxonomy=categories_taxonomy, categories_id=categories_id, entities_body_links_dbpedia=entities, source_name=source_name, language=language, published_at_start=since, published_at_end=until)
    print(api_response)
except ApiException as e:
    print("Exception when calling DefaultApi->list_stories: %s\n" % e)
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();

        String text = "Trump";
        String since = "NOW-10DAYS";
        String until = "NOW";
        List categoriesId = new ArrayList() {{
            add("IAB11");
        }};
        String categoriesTaxonomy = "iab-qag";
        List sourceName = new ArrayList() {{
            add("CNN");
            add("CBS");
            add("Reuters");
        }};
        List entitiesBodyLinksDbpedia = new ArrayList() {{
            add("http://dbpedia.org/resource/Ohio");
            add("http://dbpedia.org/resource/Florida");
        }};
        List language = new ArrayList() {{
            add("en");
        }};

        storiesBuilder.setText(text);
        storiesBuilder.setPublishedAtStart(since);
        storiesBuilder.setPublishedAtEnd(until);
        storiesBuilder.setCategoriesId(categoriesId);
        storiesBuilder.setCategoriesTaxonomy(categoriesTaxonomy);
        storiesBuilder.setSourceName(sourceName);
        storiesBuilder.setEntitiesBodyLinksDbpedia(entitiesBodyLinksDbpedia);
        storiesBuilder.setLanguage(language);

        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 = {
  :text => 'Trump',
  :published_at_start => "NOW-10DAYS",
  :published_at_end => "NOW",
  :categories_id => ['IAB11'],
  :categories_taxonomy => 'iab-qag',
  :source_name => ['CNN', 'CBS', 'Reuters'],
  :entities_body_links_dbpedia => [
    'http://dbpedia.org/resource/Ohio',
    'http://dbpedia.org/resource/Florida'
  ],
  :language => ['en']
}


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 := "Trump"
	until := "NOW"
	since := "NOW-10DAYS"
	categoriesId := []string{"IAB11"}
	categoriesTaxonomy := "iab-qag"
	sourceName := []string{"CNN", "CBS", "Reuters"}
	entitiesBodyLinksDbpedia := []string{
		"http://dbpedia.org/resource/Ohio",
		"http://dbpedia.org/resource/Florida"}
	language := []string{"en"}

	storiesParams := &newsapi.StoriesParams{
		Text:                     text,
		PublishedAtStart:         since,
		PublishedAtEnd:           until,
		CategoriesId:             categoriesId,
		CategoriesTaxonomy:       categoriesTaxonomy,
		SourceName:               sourceName,
		EntitiesBodyLinksDbpedia: entitiesBodyLinksDbpedia,
		Language:                 language}

	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 text = "Trump";
            string since = "NOW-10DAYS";
            string until = "NOW";
            List categoriesId = new List{ "IAB11" };
            string categoriesTaxonomy = "iab-qag";
            List sourceName = new List{ "CNN", "CBS", "Reuters" };
            List entitiesBodyLinksDbpedia = new List{
              "http://dbpedia.org/resource/Ohio",
              "http://dbpedia.org/resource/Florida"
            };
            List language = new List { "en" };

            try
            {
                // List stories
                Stories result = apiInstance.ListStories(text: text, publishedAtStart: since, publishedAtEnd: until, categoriesId: categoriesId, categoriesTaxonomy: categoriesTaxonomy, sourceName: sourceName, entitiesBodyLinksDbpedia: entitiesBodyLinksDbpedia, language: language);
                Debug.WriteLine(result);
            }
            catch (Exception e)
            {
                Debug.Print("Exception when calling DefaultApi.ListStories: " + e.Message );
            }
        }
    }
}
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': 'Trump',
  'publishedAtStart': 'NOW-10DAYS',
  'publishedAtEnd': 'NOW',
  'categoriesId': ['IAB11'],
  'categoriesTaxonomy': 'iab-qag',
  'sourceName': ['CNN', 'CBS', 'Reuters'],
  'entitiesBodyLinksDbpedia': [
    'http://dbpedia.org/resource/Ohio',
    'http://dbpedia.org/resource/Florida'
  ], 
  'language': ['en'],
};

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

Our next search will focus on finding stories with a particular sentiment polarity from a particular geographic region. While our previous entities search focused on stories about specific locations (Ohio & Florida), this search will focus on stories from outlets in a specific location.

We’re going to search for negative stories, mentioning Trump, from sources based in Mexico.

As before, we will use the `text` parameter to indicate ‘Trump’ as our keyword. You could also use `title` if you wished to search for mentions of Trump in the article title only. The parameter sentiment.title.polarity is set to ‘negative’ and `source.locations.country` to ‘MX’.

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(
  'text' => 'trump',
  'source_locations_country' => ['MX'],
  'sentiment_title_polarity' => 'negative',
  'published_at_start' => 'NOW-60DAYS',
  'published_at_end' => 'NOW'
);

try {
    $result = $api_instance->listStories($opts);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling DefaultApi->listStories: ', $e->getMessage(), "\n";
}
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 = 'trump'
country = ['MX']
sentiment = 'negative'
since = 'NOW-60DAYS'
until = 'NOW'

try:
    # List stories
    api_response = api_instance.list_stories(text=text, source_locations_country=country, sentiment_title_polarity=sentiment, published_at_start=since, published_at_end=until)
    print(api_response)
except ApiException as e:
    print("Exception when calling DefaultApi->list_stories: %s\n" % e)
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();

        String text = "trump";
        List sourceLocationsCountry = new ArrayList() {{
            add("MX");
        }};
        String sentimentTitlePolarity = "negative";
        String since = "NOW-60DAYS";
        String until = "NOW";

        storiesBuilder.setText(text);
        storiesBuilder.setSentimentTitlePolarity(sentimentTitlePolarity);
        storiesBuilder.setSourceLocationsCountry(sourceLocationsCountry);
        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 = {
  :text => "trump",
  :source_locations_country => ['MX'],
  :sentiment_title_polarity => 'negative',
  :published_at_start => "NOW-60DAYS",
  :published_at_end => "NOW"
}


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 := "trump"
	sourceLocationsCountry := []string{"MX"}
	sentimentTitlePolarity := "negative"
	until := "NOW"
	since := "NOW-60DAYS"

	storiesParams := &newsapi.StoriesParams{
		Text: text,
		SourceLocationsCountry: sourceLocationsCountry,
		SentimentTitlePolarity: sentimentTitlePolarity,
		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 text = "trump";
            string since = "NOW-60DAYS";
            string until = "NOW";
            List sourceLocationsCountry = new List { "MX" };
            string sentimentTitlePolarity = "negative";

            try
            {
                // List stories
                Stories result = apiInstance.ListStories(text: text, publishedAtStart: since, publishedAtEnd: until, sourceLocationsCountry: sourceLocationsCountry, sentimentTitlePolarity: sentimentTitlePolarity);
                Debug.WriteLine(result);
            }
            catch (Exception e)
            {
                Debug.Print("Exception when calling DefaultApi.ListStories: " + e.Message );
            }
        }
    }
}
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': 'trump',
  'sourceLocationsCountry': ['MX'],
  'sentimentTitlePolarity': 'negative',
  'publishedAtStart': 'NOW-60DAYS',
  '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);


What’s next?

There you have it. We hope that this gentle introduction to using our News API has helped you get started with the basics, making calls and creating specific search queries. Of course, the API is more than just a news aggregator and we have merely scratched the surface of what this awesome tool is capable of today. You will see the true power and benefits of the API as you begin to explore some of the more advanced capabilities it offers from an analysis and insights point of view.

Check back next week for Part 2 where we will be showing you how easy it is to use the API to look for insights, trends and correlations in news content.

 




News API - Sign up




Author


Avatar

Noel Bambrick

Customer Success Manager @ AYLIEN A graduate of the Dublin Institute of Technology and Digital Marketing Institute in Ireland, Noel heads up Customer Success here at AYLIEN. A keen runner, writer and traveller, Noel joined the team having previously gained experience with SaaS companies in Australia and Canada. Twitter: @noelbambrick