1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravelで楽天APIを叩いて商品情報を取得する

Posted at

はじめに#

 APIとは、Application Programming Interfaceの略です。Interfaceとは、何かと何かをつなぐものといった意味があり、この場合はアプリケーションやプログラムをつなぐものになります。これにより、APIを提供する外部のソフトウェアへリクエストを送り、認証機能や商品情報取得といった外部ソフトウェアの機能を使うことが出来ます。
 APIを使った機能は我々の生活に深く浸透しており、例えばカード決済やSNSログインなどがこれにあたります。

Laravelで楽天APIから商品情報を取得#

 Laravelで楽天APIを使用するにはまず、RakutenDevelopersでアプリIDを取得する必要があります。スクリーンショット 2021-09-19 7.23.25.png
アプリ名とかURLは適当で大丈夫です。アプリIDさえ取得できればOKです。

次に、ComposerでSDKをインストールします。Rakuten Web Service SDK for PHPのことで、PHPから楽天APIに簡単にアクセスできるSDK(Software Development Kit)になります。楽天APIを簡単に使えるようになるライブラリという認識で大丈夫だと思います。

$ composer require rakuten-ws/rws-php-sdk

このようにコマンド入力すると、インストールすることが出来ます。

ここまでくればあとはAPIにアクセスするだけです。
まずは.envファイルにアプリケーションIDを設定します。

.env
RAKUTEN_APPLICATION_ID='アプリケーションIDを入れてください'

次に、config/app.phpに.envファイルに設定した環境変数を定義します。

config/app.php
return [
  //略
  'rakuten_id' => env('RAKUTEN_APPLICATION_ID', false),
];

次に、楽天APIにアクセスします。

controller.php
use RakutenRws_Client;

class HomeController extends Controller{
  
   public function get_rakuten_items()
      {
        $client = new RakutenRws_Client();

        define("RAKUTEN_APPLICATION_ID", config('app.rakuten_id'));

        $client->setApplicationId(RAKUTEN_APPLICATION_ID);

        $response = $client->execute('IchibaItemSearch',array(
            'keyword' => '任意のキーワードを入れてください'
        ));

        if(!$response->isOk()){
            return 'Error:'.$response->getMessage();
        } else {
            $items = [];
            foreach($response as $key => $rakutenItem){
                $items[$key]['title'] = $rakutenItem['itemName'];
                $items[$key]['price'] = $rakutenItem['itemPrice'];
                $items[$key]['url'] = $rakutenItem['itemUrl'];
                
                if($rakutenItem['imageFlag']){
                    $imgSrc = $rakutenItem['mediumImageUrls'][0]['imageUrl'];
                    $items[$key]['img'] = preg_replace('/^http:/','https:',$imgSrc);
                }
            }
            return $items;
        }
    }
}

これで$itemsという配列に商品情報を格納することが出来ます!

終わりに#

 APIは未経験からエンジニアを目指す我々にとっても必須の知識ですので、ぜひ扱えるようにしておきましょう!

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?