gfargo / newsapi
PHP API wrapper for NewsAPI.org
Requires
- php: >=7.1
- rmccue/requests: ^1.7
Requires (Dev)
- phpunit/phpunit: 7.5
- squizlabs/php_codesniffer: 3.*
This package is auto-updated.
Last update: 2024-04-29 03:57:37 UTC
README
🗞 PHP wrapper for NewsAPI.org
Getting Started
Implementing the NewsAPI within your PHP application has never been smoother. The principle behind its design is simplicity without forfeiting power or flexibility.
Installation
Add it to your project via Composer.
composer require gfargo/newsapi
Dependencies
This wrapper utilizes the Requests library from Ryan McCue.
Official website & documentation can be found here.
Configuration
Once included in your project, setup should be very straightforward. Only requirement is a valid API key provided by NewsAPI.org.
Usage
Step 1. Set Access Token
\NewsAPI\Client::setAccessToken('276537c6a3824cdd9eae393c024ff732');
Step 2. Setup Query
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' ] );
Step 3. Handling Responses
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) "{...}"