Amazon web services via Grails

by paul on October 10, 2009

I just recently noticed that Amazon have changed the way you invoke their Product Advertising API - you now need to sign requests as described in the Example REST Requests.

I obviously haven’t been reading my emails, since the first clue came when I saw:

<Error><Code>MissingParameter</Code><Message>The request must contain the parameter Signature.</Message></Error>

Luckily, they have a java example demonstrating how to make an API request.

If you extract the source from this sample into your <GRAILS_APP>/src/java directory, then you can invoke the amazon api with code like:


import org.codehaus.groovy.grails.commons.ConfigurationHolder
import com.amazon.advertising.api.sample.*

class AmazonService {
  private static final String ENDPOINT = "ecs.amazonaws.com";
  private static final String AWS_SECRET_KEY = "put your secret key here";
  private static final String AWS_ACCESS_KEY_ID = "put your access key here";

  boolean transactional = false

  /**
   * Call amazon lookup api.
   * Returns xml document.
   */
  def getData(String asin) {
    SignedRequestsHelper helper = SignedRequestsHelper.getInstance(ENDPOINT, AWS_ACCESS_KEY_ID, AWS_SECRET_KEY);

    String requestUrl = null;
    String title = null;

    Map params = new HashMap();
    params.put("Service", "AWSECommerceService");
    params.put("Version", "2009-03-31");
    params.put("Operation", "ItemLookup");
    params.put("ItemId", asin);
    params.put("ResponseGroup", "Small,Medium");

    requestUrl = helper.sign(params);

    def xml = new URL(requestUrl).text
    return new XmlSlurper().parseText(xml)
  }
}

You could, of-course, define your access keys in the Config.groovy class if you prefer.

(To find your identifiers, see http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/index.html?ViewingCredentials.html)

Leave a Comment

Previous post: Locked subversion working copy

Next post: No module named _multiprocessing