JavaScript Client for Amazon Product Advertising API
Node.js
Monday, 05 July 2010 10:45

I'm writing a website using express.js which will need to connect to the Amazon Product Advertising API. This API is REST based with XML as the format of choice, so one would think that it is fairly simple to use. As I dug deeper it wasn't quite that simple. Amazon requires that the requests are signed in a very special way. It's not exactly rocket science to sign the request, but it is definitely not something you want to have to deal with every time you make a request. It it is a totally mundane task that is the same for every application, so I figured that there must be a library out there to do this for you.

After looking around a bit, I did not find any "official" client libraries. I did find a number of code examples that you could use to do the heavy lifting, but none that would work in JavaScript. When most of the world thinks of JavaScript, they think of client-side JavaScript. Creating the request signature requires access to your secret key with AWS which you must not share with anyone. Generating a request signature in client-side JavaScript would expose this secret key to anyone who is sophisticated enough to view source -- not good. So I can see why there wasn't much interest in creating a JavaScript libarary for this purpose.

However, my intentions were quite different. My JavaScript code will run server-side using Node.js. Therefore it is totally safe and I need said library. So, I went about creating a library called node-apac and have made it publicly available. The easiest way to get it is by using npm (Node Package Manager). If you already have npm installed, then all you have to do is type "npm install apac" (the library is called "apac" in the npm registry as opposed to node-apac per npm package name recommendations). Keep in mind that this library depends on node.js. If you try to use it in a browser you won't have any luck.

In this library, there are two classes. The main one you'll need is OperationHelper. You instantiate it only once, no matter how many API calls you make. You'll pass it a few things such as your AWS id and secret key for initialization. Then, for each API call you want to make, you'll use the execute() function, passing it operation-specific parameters. The second class provided is RequestSignatureHelper which is responsible for signing your requests. This is the class that's probably providing the most value and you can use it directly if you'd like. But, I recommend just using OperationHelper, which uses RequestSignatureHelper behind the scenes.

That's it. If you happen to be developing a node.js app that needs to access the Amazon Product Advertising API, I'm sure you'll enjoy. If you have any problems, please let me know by filing a issue.


blog comments powered by Disqus