Ruby で Amazon Product Advertising API を試したくなって gem を漁ってみたら、amazon-aaws と amazon-ecs の2つを見つけた。
どちらも API を素直にラップしていて筋が良さそうだったけど、amazon-aaws の方は AccessKey や SecretKey を .amazonrc っていう別ファイルに記述しなければいけないのが個人的に気に入らない。一方、amazon-ecs ではブロックで設定を記述できる。amazon-ecs を試してみようかな。
amazon-ecs を使って、Amazon で Ruby の書籍を検索するスクリプトを書いてみた。
require "amazon/ecs" # Amazon Product Advertising API へのアクセスに必要なキーを設定 Amazon::Ecs.configure do |options| options[:associate_tag] = "hogehoge-22" options[:AWS_access_key_id] = "Access Key" options[:AWS_secret_key] = "Secret Key" end # "Ruby" で Amazon の商品を検索 resp = Amazon::Esc.item_search("ruby", :item_page => 1, :country => "jp") resp.items.each do |item| puts item.get_elements("./ASIN") puts item.get("ItemAttributes/Title") puts item.get_element("Author") end # 『たのしい Ruby』の情報を取得 resp = Amazon::Esc.item_lookup("4797357401") puts item.get_elements("./ASIN") puts item.get("ItemAttributes/Title") puts item.get_element("Author")
Amazon Product Advertising API のレスポンスは XML だけど、それを amazon-ecs が内部で nokogiri を使ってパースしているので、情報を取り出しやすい。Amazon の商品を検索する程度なら、これで十分だな。
ちなみに、レスポンスの XML の要素を調べるのには、下記のサイトが役に立った。