LoginSignup
82

More than 5 years have passed since last update.

RailsでAmazon APIを使って商品を検索する方法

Last updated at Posted at 2014-12-16

いつ使えるの?

RailsからAmazonで商品を検索したいとき。

公式リポジトリ

amazon-ecs

amazon-ecsをインストール

Gemfile
gem 'amazon-ecs'
$ bunde install --path vendor/bundle

config/application.rb などを編集

config/application.rb
require File.expand_path('../boot', __FILE__)

require 'rails/all'
require 'amazon/ecs' # 追記
Bundler.require(:default, Rails.env)

# ここから
module Test
  class Application < Rails::Application
    Amazon::Ecs.options = {
      :associate_tag =>     '987654321',
      :AWS_access_key_id => 'mosmosmosmosmosmosmosmos',
      :AWS_secret_key =>   'mosmosmosmosmosmosmosmos'
    }
end
# ここまでを追記

associate_tagとして、アソシエイトのIDも記入できます。

コントローラーを編集

app/controllers/home_controller.rb

class HomeController < ApplicationController

  def index
    @res = Amazon::Ecs.item_search("検索したいキーワード",
             :search_index   => 'Books',
             :response_group => 'Medium',
             :country        => 'jp'
           )
  end
end

Amazon::Ecs にある item_search というメソッドを使って Amazon にアクセスします。レスポンスはAmazon::Ecs::Response オブジェクトになって返ってきます。

本のタイトルと画像を取得(1件)

app/views/home/index.html.erb

<%= @res.first_item.get('ItemAttributes/Title') %>
<img src="<%= @res.first_item.get('MediumImage/URL') %>" />

http://localhost:3000/home/index にアクセスすると、first_item で本のタイトルと画像を1件取得しています。

・BooksやDVDなど、検索したいものを search_index で指定
・response_group は、Small, Medium, Large が扱える

response_group の値を変えることによって、取得する情報量が変化させることができます。これでRailsで、簡単にAmazonから商品を検索できます。

シンプル!

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
82