Home > Programming > Amazon product information via Amazon Web Services

Amazon product information via Amazon Web Services

I recently suggested to a client that a good way to increase their sales on Amazon would be to show the Amazon price next to the “Buy from Amazon” link. I figured that there would be a simple, straightforward solution to this. I thought to myself “Amazon will have an API for that; they’ll have useful, up-to-date documentation …”

Nothing in life is as easy as it should be

Nothing in life is as easy as it should be

Well, I’m sure all of their documentation was useful, once, but not much was up-to-date. I ended up spending over an hour reading through various instructions, tutorials and references, before I was able to work out how to produce a simple REST request.

I’m hoping that by sharing my solution with you, you won’t have to go through all the brain-ache I had to endure. Feel free to leave a comment if it helped, or if any of the information didn’t work for you. This is my first how-to post so I welcome any feedback.

The AWS Signed Request Helper

I’m assuming you have an Amazon Web Services account. If not, click the link to get one.

The AWS Signed Request Helper is your friend

After spending what felt like days reading through everything I could find on the subject, everything clicked when I discovered Amazon Web Services’ Signed Request Helper. This useful little tool lets you specify the basic request parameters, and will walk you through the steps required to turn that into a fully functioning signed REST URL. Note that all requests are time-stamped, so you won’t be able to use a URL you made with the Signed Request Helper for longer than about 15 minutes. Here’s a sample session with the Signed Request Helper:

Unsigned URL:

http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService
&Version=2009-03-31
&Operation=ItemSearch
&SearchIndex=Books
&Keywords=harry+potter

Name-Value Pairs:

Service=AWSECommerceService
Version=2009-03-31
Operation=ItemSearch
SearchIndex=Books
Keywords=harry+potter
Timestamp=2010-02-09T22:27:04.000Z
AWSAccessKeyId=HIDDEN

Sorted Pairs:

AWSAccessKeyId=HIDDEN
Keywords=harry%20potter
Operation=ItemSearch
SearchIndex=Books
Service=AWSECommerceService
Timestamp=2010-02-09T22%3A27%3A04.000Z
Version=2009-03-31

String-To-Sign:

GET
ecs.amazonaws.com
/onca/xml
AWSAccessKeyId=HIDDEN&Keywords=harry%20potter&Operation=ItemSearch&SearchIndex=Books&Service=AWSECommerceService&Timestamp=2010-02-09T22%3A27%3A04.000Z&Version=2009-03-31

Signed URL:

http://ecs.amazonaws.com/onca/xml?AWSAccessKeyId=HIDDEN&Keywords=harry%20potter&Operation=ItemSearch&SearchIndex=Books&Service=AWSECommerceService&Timestamp=2010-02-09T22%3A27%3A04.000Z&Version=2009-03-31&Signature=7hZh9Dzo2WPh8JhEoAMs8mm2I6OgMaxL8pZifFcaVZY%3D

Huh?

If you’re unsure about what that all meant, here’s an explanation of each step:

Unsigned URL

The unsigned URL is what you’d use if Amazon had a simple REST API that didn’t require any authentication or signing. We’ve supplied a number of parameters. If you want to know more about these parameters, have a look at Amazon’s documentation on the ItemSearch Operation and the ItemLookup Operation.

Name-Value Pairs

This splits the query string into its constituent parts. You’ll notice that two new parameters have been added: Timestamp and AWSAccessKeyId. Timestamp is a current timestamp, specially-formatted. You’ll be able to find your AWSAccessKeyId when you log into Amazon Web Services.

Sorted Pairs

Now the Name-Value pairs have been sorted in byte order and URL encoded (e.g. + has been changed to %20).

String-To-Sign

This is the HTTP request representation of the original URL. Note the newlines – these must be included in the string for the next stage to work properly.

Signed URL

This is where the voodoo happens. The String-To-Sign and your AWS secret key are used to create an HMAC-SHA signature. For some more in-depth information on this procedure have a look at Amazon’s description.

HMAC Authentication Process

A sample implementation

Now let’s code it up. I’m going to be using PHP; implementation in other languages is left as an exercise to the reader.

This example will show how to get information on an item from Amazon.co.uk using the AWS API. We will be creating a function that will produce a signed REST URL from an Amazon product code. I’ve borrowed heavily from Amazon’s Introduction to AWS for PHP Developers, which is a useful resource, but with some crucial bits that were out of date.

The first thing to do is place your AWS credentials in a safe place. I usually use a directory called ‘safeinc’ in the parent directory to the web root. Make a file in that directory called aws.conf, as follows:

; AWS credentials
; Access Key Id
access_key = "Your access key"
; Secret Access Key
secret_key = "Your secret key"

Now it’s time to make a PHP file for our function. This function is going to take an ASIN (Amazon Standard Identification Number) and return a URL.

function makeUrl($itemId) {
  //load and parse credentials
  $creds = parse_ini_file($_SERVER["DOCUMENT_ROOT"] . '/../safeinc/aws.conf');
  //set up the base AWS URL. This can be changed to .com if necessary.
  $awsUrl = 'ecs.amazonaws.co.uk';
  $params = array(
          //AWS version date
          'Version' => '2009-03-31',
          //Look up an item by ASIN
          'Operation' => 'ItemLookup',
          //The ASIN
          'ItemId' => strval($itemId),
          //The AWS service being used
          'Service' => 'AWSECommerceService',
          //The timestamp must use this format
          'Timestamp' => gmdate('Y-m-d\TH:i:s.000\Z'),
          //Your Access Key
          'AWSAccessKeyId' => $creds['access_key'],
          //To make sure the response includes the Amazon price use this
          'ResponseGroup' => 'Offers',
          //Get Amazon prices, not third party merchants.
          'Merchant' => 'Amazon'
          );
  //Sort the params array by key
  uksort($params, 'strnatcmp');

We’ve reached the Sorted Pairs stage now, with hopefully no massive surprises. The next step is to produce the String-To-Sign.

  $qstr = '';
  foreach($params as $key => $param) {
    //each key-param combo will produce '&key=param'
    $qstr .= "&{$key}=".rawurlencode($param);
  }
  //Need to remove the initial '&'
  $qstr = substr($qstr, 1);

  //Note the newlines, and lack of '?' before query string
  $stringToSign = "GET\n"
    . $awsUrl . "\n"
    . "/onca/xml\n"
    . $qstr;

The final step is to produce the signature to make the signed URL. We’re going to be using PHP’s hash_hmac function for this.

  //hash_hmac's function signature:
  //string hash_hmac ( string $algo , string $data , string $key [, bool $raw_output = false ] )
  //The last parameter will be the signature, which must be base64-encoded.
  $params['Signature'] = base64_encode(hash_hmac('sha256',
                         $stringToSign,
                         $creds['secret_key'],
                         true)
                   );

  //Construct the URL
  $req = "http://$awsUrl/onca/xml?" . http_build_query($params);
  return $req;
}

Well, there you have it

Hopefully that solves your Amazon API woes. It turns out that it’s not really a difficult process, but you have to jump through a lot of hoops to get there. It’s a shame Amazon’s documentation isn’t more up-to-date, but then again, maybe that’s what blog posts like this one are there for. If this helped, or if you’ve spotted any mistakes or inaccuracies, let me know in the comments.

Categories: Programming Tags: ,
  1. at0m
    April 30th, 2010 at 06:29 | #1

    nice tutorial,, hmm i have some question …

    why amazon need signed request ??

  2. May 8th, 2010 at 14:55 | #2

    I think they want to limit the sites using/abusing their service.

  3. at0m
    May 9th, 2010 at 09:02 | #3

    I find some problem from this script. This problem is about “&”.

    When I echo $req -> http://ecs.amazonaws.com/onca/xml?AWSAccessKeyId=xxxxxxxxxxxxx&Keywords It fine. But when I var_dump($req) -> string ‘http://ecs.amazonaws.com/onca/xml?AWSAccessKeyId=xxxxxxxxxxxx&Keywords=harry+potter& have some trouble about “&”. you can see it “amp;”

    And when I use CURL request is response operation invalid.

    How do I solve this ??

  4. May 9th, 2010 at 11:45 | #4

    It looks like you’re missing out some major parts of the script. You should have a lot more parameters than just the AWSAccessKeyId and the Keywords.

    While you’re debugging this, instead of using CURL, just visit the URL you’ve created in a web browser. The whole beauty of REST is that you can look at the results using a standard browser GET request. You should be able to find what’s going wrong that way.

  5. at0m
    May 9th, 2010 at 13:18 | #5

    From previous post I missing some my problem. Ok, This is about problem. http_build_query will use “&” instead of “&”. So, it will make problem for CURL request and return invalid response.

    I try copy from echo is ok. I copy from echo and paste in browser and it valid response. I think http_build_query is a problem with CURL request.

  6. at0m
    May 9th, 2010 at 15:57 | #6
  7. May 10th, 2010 at 12:48 | #7

    I’m glad you’ve got it sorted. Your link was mangled a bit, I’ve fixed it now.

  8. Noah
    December 17th, 2010 at 01:59 | #8

    @at0m

    Specifically, they want to prevent crackers from rewriting the AsssociateTag key in the GET url, thereby steering commissions from legit affiliate sites to their own coffers. A PITA, but completely necessary.

  9. October 5th, 2011 at 08:02 | #9

    I spent too much time working with the Amazon Product API and PHP. I recently found your link from stackoverflow. My code for accessing the Amazon Product API with PHP along with code to work with a number of other APIs is here:

    http://www.muschamp.ca/Muskie/webMashups.html

    Cheers,

  10. October 5th, 2011 at 09:38 | #10

    @Muskie Hey, thanks for sharing!

  11. Billy C
    August 20th, 2012 at 17:57 | #11

    Thanks for posting this. It’s the only thing I’ve read that has made any sense. I’m not familiar with PHP so I’ll keep looking for a ruby example but yours is the best I’ve seen. Much better than Amazon’s documentation. To be honest for doing something really simple it’s probably easier to scrape.

  12. December 28th, 2012 at 04:17 | #12

    whoah this blog is magnificent i love reading your articles. Keep up the good work! You know, lots of people are hunting around for this information, you could help them greatly.

  13. Peter Nicholls
    February 1st, 2013 at 17:20 | #13

    You know what is SO FRUSTRATING!!!!

    I am following tutorial examples in Pro PHP patterns and frameworks, I think: great i’m learning some stuff I can see happen with real world things!

    Then I banged in to this issue. HOW THE HELL ARE WE MEANT TO LEARN when documentation and help goes so bang left of field?!

    so, A HUGE thank you to you for providing this, so I can get my learning back on track.

    hoenstly, youd think there are people who actually DONT WANT people to learn how to do things sometimes……….

  14. March 14th, 2013 at 21:11 | #14

    @Skilldrick

    I’m a giver. Or I am most of the time. People follow the link, at least today according to web analytics. My code is still working and running though I don’t make any money of referring people to Amazon. ;-)

  15. September 20th, 2013 at 15:16 | #15

    Simply how to watch every single period since well as episode oof Game of Thrones.

    What to expect in season 3 and also additionally whenever the tv series airs. This will be thhe best brand new program of the 12 months and i can’t wait to watch Game of Thrones – Season 3. All of the characters battling and additionally trying to get the top hand on one another.

    watch the game of thrones – Season 3 online

    my web site … Reno and LA ([http://youtu.be/](http://youtu.be/HqLq8r87wV4 “http://youtu.be/”))

  16. October 21st, 2013 at 22:44 | #16

    Hey there, You have done an incredible job. I’ll definitely digg it and personally recommend to my friends. I’m sure they’ll be benefited from this site.

  17. February 24th, 2014 at 04:52 | #17

    Does your blog have a contact page? I’m having a tough time locating it but, I’d like to shoot youu an e-mail. I’ve gott some idreas for your blog you might be interested in hearing. Either way, great website annd I look forward to seeing it expand over time.

  18. February 28th, 2014 at 03:32 | #18

    I have been browsing online more than 2 hours today, yet I never found any interesting article like yours. It’s pretty worth enough for me.

    In my view, if all website owners and bloggers made good content as you did, the net will be much more useful than ever before.

  19. March 12th, 2014 at 04:59 | #19

    Does your site have a contact page? I’m having trouble locating it but, I’d like to send you an email.

    I’ve got some recommendations for your blog you might be interested in hearing. Either way, great site and I look forward to seeing it grow over time.

  20. March 24th, 2014 at 13:48 | #20

    Does your blog have a contact page? I’m having trouble locating it but, I’d like to send you an email. I’ve got some recommendations for your blog you might be interested in hearing. Either way, great blog and I look forward to seeing it expand over time.

  21. April 9th, 2014 at 08:41 | #21

    You can also use some free programs to customize your minecraft avatar by going here, and this is the one I used to custom create my own avatar. Not only will that allow 4J Studios to bring features from PC builds to home consoles at a faster rate, it also means that the game will be easier to port the game to the Xbox One and PS4. Too Many Spawned Creatures – If you are running Minecraft in Creative Mode, you can spawn unlimited creatures in one area.

  22. May 7th, 2014 at 13:02 | #22

    Hi, I want to subscribe for this website to obtain newest updates, thus where can i do it please help out.

  23. May 16th, 2014 at 22:44 | #23

    hi!,I like your writing so much! percentage we keep in touch extra about your post on AOL? I need a specialist in this house to resolve my problem. Maybe that is you! Having a look forward to look you.

  24. June 8th, 2014 at 13:41 | #24

    WOW just what I was searching for. Came here bby searching for business card cutter

  25. June 11th, 2014 at 00:27 | #25

    The [Dayz hack](https://www.youtube.com/watch?v=w8xDk4vgKjo “Dayz hack”) issue

    DayZ is often a video game that will acquired the opposite associated with simple starting symptoms. The idea started out as being a area challenge for the sport creator branded Dean Hallway who was simply implementing any mod for that not too popular sport ARMA a couple of. The actual mod quickly became popular and also inside of months received a lot of participants. Since that time a number of other game developers took an effort on the Dayz mod, creating a variety of edition such as: Dayz Beginning and also Dayz Epoch. The mod also got it’s own ripoff edition much like the well known Struggle Z failure which induced a lot dispute.

    Because start Dayz acquired a problem with hackers. From the first few weeks of the mods start DayZ hacks required more than computers using electric power similar to nuclear bombs and a chance to create a big base named your Thunderdome, during which avid gamers will be teleported in addition to required to battle. These are are just some of the particular types of the particular Dayz hacks that will brought about quite a few avid gamers to stop.

    Dayz Separate hackers are only seeing that poor. The overall game continues to be battling hacks because it’s pre-alpha release a few months returning. Presently they’ve already not any anti-hack diagnosis program that is creating cyberpunks running outrageous. The Dayz staff happen to be greater in patching the particular uses rather than the particular mod, nevertheless it most appears a tad too late.

    Lately Bohemia Interactive confirmed in which cyberpunks smashed into his or her servers and took your games full source program code. That is a enormous package pertaining to DayZ Standalone, this would mean cyber-terrorist will probably know every take advantage of in the game that they can use for their gain. This cyber criminals then submitted their particular prize upon Reddit, showing off their particular loot as being a bragging proper.

  26. June 16th, 2014 at 09:13 | #26

    Aw, this was an exceptionally good post. Finding the time and actual effort to generate a great article… but what can I say… I put things off a lot and don’t seem to get nearly anything done.

  27. July 31st, 2014 at 09:36 | #27

    Hi, i read yolur blog occasionally and i own a similar one and i was just curious if you get a lot of spam comments? If so how do you reduce it, aany plugin or anything yyou cann advise? I get so much lately it’s driving me crazy soo any assistance is very muh appreciated.

    Feel free to visit my web page: [Skip Hire](https://abhorrentvagran15.jux.com/3137358 “Skip Hire”)

  28. July 31st, 2014 at 14:56 | #28

    This is required whether or not the both spouses are responsible for the IRS debt. We can see the importance of this concept by noticing companies today whose operations are strictly financial advising. For costs of home-based DUI, robbery and assault immigration-linked or another tricky New York Tax Attorney, New York Bankruptcy Attorney, New York Traffic Ticket Lawyer firm trouble, he promises to zealously promoter for your own interest.

    Feel free to surf to my page :: [Boca Raton CPAt test Questions](http://verabelbinwo.edublogs.org/2014/05/02/convenient-secrets-for-accounting-across-the-uk/ “Boca Raton CPAt test Questions”)

  29. August 3rd, 2014 at 17:43 | #29

    Heya! I’m at work surfing around your blog from my nnew iphone 3gs! Just wanted to say I love reading your blog and lok forward to all your posts! Keep up the excellent work!

  30. August 13th, 2014 at 19:31 | #30

    He will sometimes guide you with extracting a unwanted food item like fatty, oily in addition to carbohydrates.

    HCG will definitely not cause weight loss single-handedly. The best time to take a pregnancy test is in the morning when your levels of HCG are at their highest.

    Here is my page :: [danger of diet pills](http://stellaosheart.pen.io/ “danger of diet pills”)

  1. July 22nd, 2014 at 03:52 | #1

Comments parsed as Markdown.