2012-10 << 2012-11 >> 2012-12

2012-11-10 (土)

*AmazonのAPI呼んでみる

rubyからAmazonのAPI使うのに ruby-aaws を使っていたのだけど,最新のrubyだとなんか警告出てるし,設定ファイルとかも好みじゃなかったので自分で書いてみることに.

class AWSECommerceService
  require 'net/http'
  require 'rexml/document'
  require 'openssl'

  def initialize conf
    @conf = conf
  end

  def geturl(params, conf)
    params["Timestamp"] =  Time.now.utc.strftime('%Y-%m-%dT%H:%M:%SZ')
    params["AWSAccessKeyId"] = conf['access_key']
    paramstr = params.map{|k,v| k.to_s+"="+URI.encode(v.to_s,/[^\w\.-]/)}.sort.join("&")
    uri = URI.parse(conf['ep'])
    reqstr = "GET\n%s\n%s\n%s" % [ uri.host, uri.path, paramstr ]
    hmac = OpenSSL::HMAC.digest( OpenSSL::Digest::Digest.new( 'sha256' ), conf['secret_key'], reqstr )
    base64_hmac = [ hmac ].pack( 'm' ).chomp

    conf['ep'] + "?" + paramstr + "&Signature=" + URI.encode(base64_hmac, /[^\w\.-]/)
  end

  def items_lookup type, ids
    params = {
      "AssociateTag" => "XXX",
      "IdType" => type,
      "ItemId" => ids,
      "Operation" => "ItemLookup",
      "ResponseGroup" => "Images", # Large
      "SearchIndex" => "Books",
      "Service" => "AWSECommerceService",
      "Version" => "2009-03-31"
    }
    url = geturl(params, @conf)
    #puts url
    res = (Net::HTTP.get URI.parse(url))
    doc = REXML::Document.new(res)
    items = []
    doc.root.elements.each('Items/Item') {|e|
      items << {
        "id" => e.text('ASIN'),
        "thumbnail" => e.text('MediumImage/URL')
      }
    }
    items
  end

  def item_lookup type, id
    items_lookup(type,id)[0]
  end

end

とこんな感じに.サムネイルだけ欲しかったので,そこしか取ってません.

2012-10 << 2012-11 >> 2012-12