3
4

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を叩く方法(Guzzle)

Last updated at Posted at 2021-03-04

Laravel5.8を使用している。

手順

guzzleをインストール

composer require guzzlehttp/guzzle

コントローラーに処理を書く

今回はぐるなびAPIでレストラン検索をするから、
RestaurantControllerを作成し、その中にget_restaurantアクションを作成した。

RestaurantController
public function get_restaurant()
    {
        $client = new \GuzzleHttp\Client();
        $response = $client->request(
            'GET',
            'https://api.gnavi.co.jp/RestSearchAPI/v3/',
            ['query' => [
                'keyid' => '123123123123123',
                'pref' => 'PREF39', 
                'freeword' => '餃子',   
                'hit_per_page' => 30
            ],
            'http_errors' => false //404エラーも通す指定
            ]
        );

        $data = [
            'res' => json_decode($response->getBody(), true)
        ];
        return view('restaurant.index', $data);

まず、Clientのインスタンスを作成し、その中に
メソッド URL クエリ
を入れて、リクエストとして送っている。

getBody()メソッドで中身を取得することはできるが、これはオブジェクトが返されるため、
json_decodeでjson形式に変換している。

また、requestメソッドの第3引数に400番台のエラーも表示の対象にする指定を追加している。

ビューを編集

restaurant/index.blade.php
@foreach ($res['rest'] as $r) 
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">おすすめ</div>

                <div class="card-body">
                    <h4>{{ $r['name'] }}</h4>
                    <br>
                    <p>{{ $r['pr']['pr_long'] }}</p>
                </div>
            </div>
        </div>
        @endforeach

ぐるなびAPIのレストラン検索機能では、
['rest']の中に複数のお店の情報が格納されており、さらに、その一つ一つのお店に
店名やその他詳細がぞれぞれ格納されているから、

rest-0-name
      -url
      -pr
  
    -1-name
      -url
      -pr

    -2-name
      -url
      -pr

このような順番で格納されている

3
4
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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?