Laravelを利用して世界中のニュース情報を取得可能なNewsAPIから最新のニュース情報を取得する

はじめに

News APIは世界中のニュース情報を取得することができるAPIです。

今回は、このAPIの利用方法についての備忘録です

 

APIキーを取得する

まずは、下記サイトにアクセスし、「Get API Key」をクリックし、専用キーを取得します。

 

次に、「First Name」「Email Address」「Password」を入力し「Submit」をクリックします。

 

「Your API key is: XXXXXXXX」と表示されます。

これが専用キーです。

 

準備

まずはComposerを利用して、「guzzlehttp/guzzle」パッケージをインストールします。

$ composer require guzzlehttp/guzzle

まず、「.env」ファイルに先ほど取得したAPIキーとapiのURLを記載します。

NEWS_API_KEY=[APIキー]
NEWS_API_URL='https://newsapi.org/v2/'

次に、「configフォルダ」に「newsapi.php」ファイルを作成し以下の様に記載します。

 env('NEWS_API_URL', null),
    'news_api_key' => env('NEWS_API_KEY', null),
];

これで、準備は完了です。

 

使い方

ここでは、トップヘッドラインニュースを10件取得するサンプルを紹介します。

&nbsp

・controller

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7;

class SampleController
{
    public function index()
    {
        $count = 10;

        try {
            $client = new Client();
            $apiRequest = $client->request('GET', config('app.news_api_url') .'top-headlines?country=jp&pageSize='.$count.'&apiKey=' . config('app.news_api_key'));
            $response = json_decode($apiRequest->getBody()->getContents(), true);

            $news = [];

            for ($idx = 0; $idx < $count; $idx++) {
                array_push($news, [
                    'name' => $resonpose['articles'][$idx]['title'],
                    'url' => $resonpose['articles'][$idx]['url'],
                    'thumbnail' => $resonpose['articles'][$idx]['urlToImage'],
                ]);
            }
        } catch (RequestException $e) {
            //For handling exception
            echo Psr7\str($e->getRequest());
            if ($e->hasResponse()) {
                echo Psr7\str($e->getResponse());
            }
        }

        return view('index', compact('news'))
    }
}

・view

@foreach($news as $data)
{{$data['name']}}
@endforeach

シンプルでいいですね。

News APIの詳細

News APIは50,000を超えるニュースソースやブログから最新のニュース記事を検索し、取得することができるAPIです。

下記にアクセスし、どの様な情報を取得できるか確認することができます。

 

もし、アカウントを持っていない場合は、下記よりアカウントを作成してください。

 

最後に

Rakuten Rapid APIで探すと様々なAPIを検索できます。

今回はNews APIを利用しましたが、いろいろ試してみるのも良いかと思います。

 

タイトルとURLをコピーしました