The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Web::NewsAPI::Result - Object representing a News API query result.

SYNOPSIS

use v5.10;
use Web::NewsAPI;

my $newsapi = Web::NewsAPI->new(
   api_key => $my_secret_api_key,
);

say "Here are some top American-news headlines about science...";
my $result = $newsapi->top_headlines(
   category => 'science', country => 'us',
);

my $count = $result->total_results;
say "There are $count such headlines in the news right now.";

say "Here are the top headlines...";
print_articles();

say "And here's page two...";
$result->turn_page;
print_articles();

sub print_articles {
    for my $article ( $result->articles ) {
       say $article->title;
       say $article->description;
       print "\n";
    }
}

DESCRIPTION

Objects of this class represent the result of a News API query, such as top-headlines or everything. Generally, you won't create these objects yourself; you'll get them as a result of calling methods on a Web::NewsAPI object.

An Web::NewsAPI::Result object gives you methods to retrieve one "page" of articles, change the current page or page-size, and get the count of all articles in the current set.

METHODS

Object attributes

page

my $current_page = $result->page;
$result->page( 2 );

The current page of results that "artciles" will return, expressed as an integer.

Default: 1.

page_size

my $page_size = $result->page_size;
$result->page_size( 10 );

How many articles to return per call to "articles".

Default: 20.

Object methods

articles

my @articles = $result->articles;

Returns all the Web::NewsAPI::Article objects that constitute the current page of results.

total_results

my $count = $result->total_results;

Returns the total number of results that News API has for the given query parameters.

turn_page

$result->turn_page;

Increment the current page.

turn_page_back

$result->turn_page_back;

Decrement the current page, unless the current page number is already 1.

NOTES

Note that, due to the essential nature of News API, the size and contents of a given article set can shift in between page-turns (or page-size changes).

For example: Say that you create an article set through a call to "top_articles" in Web::NewsAPI, and view the first page of results. If you call "turn_page" and list the articles again, there is a chance that one or more articles towards the end of the first page's list now lead the second page's list. This can occur when more news has happened in between the first page's query and the second, effectively causing new entries at the top of the first page and pushing all the older results down.

This sort of behavior occurs due to the nature of news, and software using this module should be aware of it.

AUTHOR

Jason McIntosh (jmac@jmac.org)