Implementing the NewsAPI within your PHP application has never been smoother. The principle behind its design is simplicity without forfeiting power or flexibility.
Add it to your project via Composer.
composer require gfargo/newsapi
This wrapper utilizes the Requests library from Ryan McCue.
Official website & documentation can be found here.
Once included in your project, setup should be very straightforward. Only requirement is a valid API key provided by NewsAPI.org.
\NewsAPI\Client::setAccessToken('276537c6a3824cdd9eae393c024ff732');
Making requests to the API is done via query
method, which accepts three parameters. Below are a few examples.
Query
parameters:
(string) $endpoint
Target endpoint. Options aretop
,everything
, andsources
.(array) $query_params
Query parameters passed to NewsAPI.org(array) $request_options
Options passed to Requests library to control CURL.
Examples:
// All articles featuring the keyword 'Open Source'
$request = NewsAPI\Client::query( 'everything', [ 'q' => 'Open Source' ] );
// Top headlines for articles featuring the keyword 'Technology'
$request = NewsAPI\Client::query( 'top', [ 'q' => 'Technology' ] );
// Top articles from 'Business' category
$request = NewsAPI\Client::query( 'top', [ 'category' => 'business' ] );
Each query returns a Request_Response
object, more on this here.
In short the Requests
library makes dealing with the API responses much easier.
$request = NewsAPI\Client::query( 'top', [ 'category' => 'business' ] );
$request->status_code // int(200)
$request->headers['content-type'] // string(31) "application/json; charset=utf-8"
$request->url // string(54) "https://newsapi.org/v2/top-headlines?category=business"
$request->body // string(14385) "{...}"