Working with Media Results

About

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

The News API allows you to:

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

Specifying the amount of media in stories

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

By setting media.images.count.min to 1, you are specifying that your query only return stories with at least one image.

By setting media.videos.count.min to 1, and media.videos.count.max also to 1, you are specifying that you only want results that contain exactly one video.

By setting media.videos.count.max to 0, you are excluding any stories with videos from your results.

Sorting by media count

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

Media format & size

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

The image formats you can use as a parameter are:

BMP
GIF
JPEG
PNG
TIFF
PSD
ICO
CUR
WEBP
SVG

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

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

Examples

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

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

var apiInstance = new AylienNewsApi.DefaultApi();

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

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

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

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

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

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

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

try:
    # List stories
    api_response = api_instance.list_stories(**opts)
    print('The API has been called successfully.')
    print('=====================================')
    for story in api_response.stories:
      print(story.title + " / " + story.source.name)
except ApiException as e:
    print("Exception when calling DefaultApi->list_stories: %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(
  'categories_taxonomy' => 'iab-qag',
  'categories_id' => ['IAB7'],
  'text' => 'fitness', 
  'language' => ['en'],
  'media_videos_count_min' => 1,
  'media_videos_count_max' => 1,
  'not_media_images_format' => ['GIF'],
  'published_at_start' => 'NOW-1MONTH',
  'published_at_end' => 'NOW',
  'sort_by' => 'relevance'
);

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

import java.util.*;

public class Main {

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

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

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

        DefaultApi apiInstance = new DefaultApi();

        StoriesParams.Builder storiesBuilder = StoriesParams.newBuilder();

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

        try {
            Stories result = apiInstance.listStories(storiesBuilder.build());
            for (Iterator<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 = {
  :categories_taxonomy => 'iab-qag',
  :categories_id => ['IAB7'],
  :text => 'fitness',
  :language => ['en'],
  :media_videos_count_min => 1,
  :media_videos_count_max => 1,
  :not_media_images_format => ['GIF'],
  :published_at_start => "NOW-1MONTH",
  :published_at_end => "NOW",
  :sort_by => 'relevance'
}


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

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

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

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

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

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

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

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

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

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

            var apiInstance = new DefaultApi();

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

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