7
11

More than 3 years have passed since last update.

RailsでぐるなびAPIを使って店舗検索する。

Posted at

アクセスキーの取得

https://api.gnavi.co.jp/api/ でアクセスキーを取得します。

実装する

shops_controllerを作成し、indexでぐるなびapiで店舗データ取得します。
今回は、先ほど取得したアクセスキーをcredentialsで管理しています。

shops_controller
    api_key= Rails.application.credentials.dig(:grunavi, :api_key)
    url='https://api.gnavi.co.jp/RestSearchAPI/v3/?keyid='
    url << api_key  

    if params[:search]
    word=params[:search]
    url << "&name=" << word #名前で検索
    end
    url=URI.encode(url) #エスケープ
    uri = URI.parse(url)
    json = Net::HTTP.get(uri)
    result = JSON.parse(json)
    @rests=result["rest"]

次に、検索フォームと検索結果を表示する画面を作成します。
レイアウトはBootstrapを使っています。

index.html.slim
= form_tag(shops_index_path,:method => 'get') do
  = text_field_tag :search
  = submit_tag 'Search'

- if @rests
  - @rests.each do |rest|
    .card.mb-3 style=("max-width: 1000px;")
      .row.no-gutters
        .col-lg-6
          = image_tag(rest["image_url"]["shop_image1"])
        .col-lg-6
          .card-body
            p = "名前: #{rest["name"]}"
            p = "カテゴリー: #{rest["category"]}"
            p = "住所: #{rest["address"]}"

では、検索フォームにカレーと打ってみてください。
店名にカレーが入っている店が表示されます。
スクリーンショット 2019-11-25 4.05.00.png

7
11
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
7
11