Amazon Web Services with PHP and SimpleXML

Technorati Technorati Tags:

RSS Subscription
Posted In:
Dec 30th, 2009 @ 8:30 pm PST
(1) Comment

This post has an update: AWS Product Advertising API Requires a Signed Request

Amazon web services (AWS) are accessible via the REST architecture which makes them an excellent introduction to using web services. Since a REST–based web service is really nothing more than an HTTP GET request with a query string attached, and an XML document response, most web developers should be comfortable consuming web services by this method. Personally, I had no problems incorporating book prices into this site using the Amazon Associates Web Service, and I'd like to share what I hope will be some useful tips to help get you started on your own application.

There are a couple, very simple things you need to do before you can use the Amazon Associates Web Service:

  1. Create an Amazon Associates Web Service account, it's FREE
  2. Obtain your unique "Access Key ID " from Amazons account activation email response

Making an Amazon Web Service Request

As previously mentioned, Amazon offers their web services via REST (and SOAP, which won't be covered), i.e. an URL with a query string that effectivley tells Amazon what sort of information you want to retrieve from their databases. Since an URL is where it all begins and the devil is in the details (a query string in this case), I'll start with a full blown example and then break down each part of the URL in turn. Here is a valid Amazon web service REST request:

http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId={YOUR ACCESS KEY ID}&Operation=ItemLookup&ItemId=1933988355&ResponseGroup=Medium,Offers

You see, it is nothing more than an URL with some name=value pairs attached as a query string. All that's needed to consume this web service is a standard HTTP GET request and tools for parsing the returned XML document to extract the desired data. But I'm getting ahead of myself here, let me use the following code view to break down the parts of the URL in more detail.

http://ecs.amazonaws.com/onca/xml
?Service=AWSECommerceService
&AWSAccessKeyId={YOUR ACCESS KEY ID}
&Operation=ItemLookup
&ItemId=1933988355
&ResponseGroup=Medium,Offers
Line #1: Request Destination
This is the endpoint for all Amazon Associates Web Service requests and will only change if you are requesting the service from a location outside the US (CA also has it's own endpoint, but isn't mandatory).
Line #2: Service=AWSECommerceService
Note the "?" indicating that this is where the query string portion of the URL begins. Amazon hosts multiple web services, so this line is necessary to inform their servers that you're requesting the associates service.
Line #3: AWSAccessKeyId={YOUR ACCESS KEY ID}
This name=value pair speaks for itself. Be sure to use your own access key ID and DON'T INCLUDE THE CURLY BRACES.
Line #4: Operation=ItemLookup
This is where the flexibility in making requests begins. The "Operation" parameter is synonymous with function or method, and informs Amazon of what kind of data you are interested in retrieving. For this example I am performing and "ItemLookup" operation which by default returns basic information about the item I am looking up. You can adjust the amount and type of data returned by using different values for the "ResponseGroup" parameter described below.
Line #5: ItemId=1933988355
This name=value pair is required with the "ItemLookup" operation. It must be a valid item ID as defined by Amazon, and for books is usually their ISBN-10. Here I have used the ISBN-10 for my "jQuery in Action" book. You can assign up to 10 ItemId's separated by commas.
Line #6: ResponseGroup=Medium,Offers
This name=value pair help target the information returned. I have used two values here separated by a comma.

Basically, lines #1 thru #3 will be the same for all requests, while the rest of the parameters and their values will change between requests. It is important to note that the parameters/values are case-sensitive, and the URL should be properly encoded which means no spaces, etc. The anatomy of this URL was pretty basic and used a limited amount of the available parameters offered by Amazon's API, but should be sufficient to get you up and running with AWS. If you are interested in other parameters/values offered, you can see the entire Amazon Associates Web Service API & Developers Guide. In my opinion, the most useful and important parameters to get you started are Operation, and ResponseGroup.

Receiving an Amazon Web Service Response

With the request out of the way, it's time to start talking about the response. If the request was successful Amazon should dutily respond with an XML document related to the parameters/values for your request. For example, below is a snippet of the response you will receive using the example URL:

<?xml version="1.0" ?> 
<ItemLookupResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2005-10-05">
  <OperationRequest>
    <HTTPHeaders>
      <Header Name="UserAgent" Value="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5"/>
    </HTTPHeaders>
    <RequestId>55ab1e6b-5618-44fc-8710-b01edd371054</RequestId>
    <Arguments>
      <Argument Name="Operation" Value="ItemLookup"/>
      <Argument Name="Service" Value="AWSECommerceService"/>
      <Argument Name="ItemId" Value="1933988355"/>
      <Argument Name="AWSAccessKeyId" Value="{YOUR ACCESS KEY ID}"/>
      <Argument Name="ResponseGroup" Value="Medium,Offers"/>
    </Arguments>
    <RequestProcessingTime>0.0272860000000000</RequestProcessingTime>
  </OperationRequest>
          .
          .
          .
</ItemLookupResponse>

After you receive your access key ID you can check out the entire XML document yourself by copying and pasting the example URL in a browser and inserting your ID in the appropriate location. It's essential that you do this to familiarize yourself with the structure of the XML document you need to parse. Below is a chunk of XML that I will show you how to parse for the highlighted FormattedPrice element using SimpleXML, an extension installed by default in PHP 5.

<OfferListing>
  <OfferListingId>5Tvh54syh%2FsERJjUf0P%2BJb8s7CDadku%2F7YsL6AbRNbWogXMrkniBeGKziajF9C%2FYirvP02bmw7wOVNW11KjFIQ%3D%3D</OfferListingId> 
  <Price>
    <Amount>2639</Amount> 
    <CurrencyCode>USD</CurrencyCode> 
    <FormattedPrice>$26.39</FormattedPrice> 
  </Price>
  <Availability>Usually ships in 24 hours</Availability> 
  <IsEligibleForSuperSaverShipping>1</IsEligibleForSuperSaverShipping> 
</OfferListing>

And this is how you would use PHP & SimpleXML to make the request and parse the XML response.

<?php
     $xml_doc = simplexml_load_file("http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId={YOUR ACCESS KEY ID}&Operation=ItemLookup&ItemId=1933988355&ResponseGroup=Medium,Offers");
     $price = $xml_doc->Items->Item[0]->Offers->Offer->OfferListing->Price->FormattedPrice;
     do_something_with($price); //Your custom function goes here
?>

Yep, thats all it takes. As you can see the FormattedPrice element is nested pretty deep within the XML, but with SimpleXML it's easy to navigate the document. The simplexml_load_file() function basically returns the XML document's element and attribute values to properties of the same name in a new object. You then access each property using member selection notation (->). PHP's SimpleXML API documentation is a great resource that offers more detailed examples.

With essentially 2 lines of code you can have Amazon's selling price for any book stored in the $price variable. It's now up to you to figure out how you want to use it in your application.

Summary

Since you can retrieve data from Amazon's web services using REST, they provide an easy introduction to the current vastness of web service API's out there. Additionally, PHP and it's SimpleXML extension comprise an effective toolkit for requesting and later parsing XML respones from AWS. Here are some links to documentation that may be of aid when setting out to build your own custom application using AWS with PHP and SimpleXML:

Amazon Associates Web ServiceAmazon Associates Web Service APIPHP SimpleXML API

Only a very small amount of what AWS offer was covered here, but armed with an understanding of how to properly make a request, the cornucopia of Amazon's treasure trove is at your disposal. So ask away, and have fun with your free data from Amazon!

Share this Post

There is 1 comment for this post.

#1
Jennifer
May 29th, 2009 @ 1:31 am PDT

Thanks for the help getting started with amazons web services. I had a hard time finding some of the documentation, but your links helped me find the way.

Add a comment to this post!

(Thanks!)

HTML Allowed (but not necessary): <p>, <a href=' '>*, <em>, <pre>, <code> & <blockquote>.  *rel='nofollow' is set for all <a> tags.