Sorting Results

About

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

The sort_by parameter can take one of seven values:

Relevance
Using the relevance value returns the stories that most closely matches your search input. The parameter value is relevance.
Recency
There are two ways of sorting your results by recency:
  • Using the recency value gives a higher rank to stories that were published more recently but also gives weight to your query too.
  • Using published_at as the value here will rank your results based only on how recently your returned stores were published.
Hotness
Using the hotness value gives a higher rank to stories that were published more recently but also gives weight to social media sharing, inbound links, and Alexa ranking.
Social shares
It is possible to sort your results by the social shares on any:
Shares on Facebook
Shares on LinkedIn
Upvotes on Reddit
Shares on Google Plus
Total number of shares on the four networks above
Number of photos
This value allows users to rank results based on the number of photos on the page. The parameter value is media.images.count.
Number of videos
This value allows users to rank results based on the number of videos on the page. The parameter value is media.videos.count.
Alexa Ranking
Alexa is a ranking system that ranks websites based on the volume of traffic they have generated over the previous 3 months. The more traffic a website receives, the higher its ranking. For example, Google.com has a ranking of 1, BBC.co.uk has a ranking of around 100, and so on. Alexa gives two options to users when seeking the ranking of sites:

a global ranking, based on how popular a website is globally

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

For more information, take a look at our page on working with Alexa rankings.

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

Examples

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

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

var apiInstance = new AylienNewsApi.DefaultApi();

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

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

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

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

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

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

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

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

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

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

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

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

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

import java.util.*;

public class Main {

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

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

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

        DefaultApi apiInstance = new DefaultApi();

        StoriesParams.Builder storiesBuilder = StoriesParams.newBuilder();

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

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

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

api_instance = AylienNewsApi::DefaultApi.new

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


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

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

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

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

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

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

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

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

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

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

            var apiInstance = new DefaultApi();

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

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