Railsで楽天APIで商品検索機能を実装してみた!

f:id:ihatov08:20160829131540j:plain

意外と簡単に実装できました!

gemをインストール

専用のgemが用意されているのでインストールしましょう!

gemfile

gem 'rakuten_web_service'
$ bundle install

イニシアライザーの定義

ファイル名は自由につけてください。
また、事前に楽天web serviceにでアプリIDを発行してください!

config/initializers/rakuten.rb

RakutenWebService.configuration do |c|
# (Required) Appliction ID for your application.
c.application_id = '取得したアプリケーションID'
# (Optional) Affiliate ID for your Rakuten account.
c.affiliate_id = '取得したアフィリエイトID' # default: nil
# (Optional) # of retries to send requests when the client receives
# When the number of requests in some period overcomes the limit, the endpoints will return
# too many requests error. Then the client tries to retry to send the same request after a
# while.
c.max_retries = 3 # default: 5
# (Optional) Enable debug mode. When set true, the client streams out all HTTP requests and
# responses to the standard error.
c.debug = true # default: false
end

サーバー再起動も忘れずに!

ルーティング

これも自由につけてください!

config/routes.rb

get 'rakuten_search' => 'rakuten#search'

このルーティングでrakuten_controller.rbにsearchアクション、views/rakuten/search.html.erbで作成することにしました!

コントローラ

params[:keyword]をviewから受け取るように設定しました。

controllers/rakuten_controller.rb

class RakutenController < ApplicationController
def search
if params[:keyword]
@items = RakutenWebService::Ichiba::Item.search(keyword: params[:keyword])
end
end
end

view

params[:keyword]を送るviewは以下のように作成します。

views/rakuten/search.html.erb

<%= form_tag :rakuten_search, method: :get do  %>
<%= label_tag :keyword, 'キーワード検索' %>
<%= text_field_tag 'keyword', params[:keyword] %>
<%= submit_tag "検索" %>
<% end %>

検索結果を表示するviewは以下のように作成します。
画像取得のコードが気持ち悪いですが、階層構造的にこうなってしまいました。もっとうまい書き方ないかな〜

views/rakuten/search.html.erb

<table>
<thead>
<tr>
<th>商品名</th>
<th>価格</th>
<th>画像</th>
</tr>
</thead>
<tbody>
<% if @items.present? %>
<% @items.each do |item| %>
<tr>
<td><%= link_to item.name, "#{item.url}" %></td>
<td align="right"><%= number_with_delimiter(item.price) %></td>
<td><%= image_tag item["smallImageUrls"][0]["imageUrl"] %></td>
</tr>
<% end %>
<% end %>
</tbody>
</table>

最低限の機能は上記コードでうまくいくはずです!
他はgemの詳細や楽天APIのサイトを調べればわかるはずです!

webservice.rakuten.co.jp

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です