Amazon.com recently launched its Web services initiatives, allowing customers to integrate its vast online content with their own Web site. This move follows the Web services launch of another major industry player, search engine Google, which launched its Web APIs Web service (http://www.google.com/apis/) a few months ago. If you were familiar with Google's Web APIs, then Amazon.com's Web service won't be new to you. Both companies require you to obtain a free license key and download a developer kit for integrating your application with their content. Neither company has announced a fee plan for using the Web services as yet.
Amazon.com's Web services launch is welcome news. Publishers have been using Amazon.com to monitor their sales, book reviews, and most importantly, their competitors. Publishers often write custom applications to pull their books' sales rankings and ratings into their own databases, which in turn lets them gauge the performance of each individual title. Often the technique used to gather this information was screen-scaping, where a lot of reliance is placed on the format of the HTML document. With the launch of Amazon.com's Web services initiatives, publishers can now integrate the Web service into their in-house application for report generation and management reporting.
Besides benefiting publishers, Amazon's Web services also benefit Amazon's Associates, who earn a percentage of a product sale by referring site visitors to Amazon. Associates can now tap into Amazon's huge product database to better tailor their recommendations to its site visitors.
In this article, I will demonstrate how you can make use of the Amazon's Web service using Visual Studio .NET.
Downloading the Developer's Kit
The first step is to download the free Amazon Web Service Developer's Kit at http://www.amazon.com/webservices (as shown in Figure 1).
You also need to apply for a free Developer's token. The token identifies you when accessing Amazon.com's Web service. Once you complete these steps, you're ready to roll.
Building Our Sample Application
We'll use Visual Studio .NET to build a Windows application and show how it can consume Amazon's Web service. Features we'll want built into the application will include the ability to search for book titles and check book information such as list price, Amazon's discounted price, customer's rating, and book cover image.
First, launch Visual Studio .NET and create a new Windows application project. Then add a Web Reference to point to Amazon's Web service. Normally, we'd just add the URL containing the WSDL of the Web service, if the Web service was developed using .NET (with an .asmx extension). However, in the case of Amazon, there is no URL to add to our Web Reference. Instead, the WSDL document itself is provided in the Developer's Kit. So, the next step is to manually create the Web service proxy using the WSDL.exe tool:
C:\>wsdl /language:vb /o:Amazon.vb AmazonWebServices.wsdl
The above step creates a proxy class in Visual Basic .NET. To use this proxy class in your project, add the Amazon.vb class to your project, as shown in Figure 2:
You also need to add references to the
System.Web.Services assemblies. (This is because they are not automatically referenced in Windows application.)
Next, add in the various controls to our Windows Form, as shown in Figure 3:
We also want to be able to display the image of a book, so I suggest adding a Web Browser OCX control. Customizing the Toolbox allows you to add this control (see Figure 4):
The Web Browser control makes use of the image URL returned by the Web service. Amazon does not return a binary image of the cover; rather it points to a URL that contains the image. The advantages of using the Web browser control are that there is no need to perform any image processing, and images that have already been downloaded will automatically be cached by the control, thereby reducing bandwidth demands.
By clicking the Search Amazon button, we will connect to the Web service. Let's dissect the codes to see the steps involved in calling the Web service:
First, create a new instance of the proxy class (from Amazon.vb, which was added earlier):
Dim ws As New AmazonSearchService()
Next, create a new WebProxy object if your client connects to the Internet via a proxy server. This is an important step to perform or else you will not be able to connect to the Web service (you will get a connection closed error).
Dim myProxy As New System.Net.WebProxy(" yourproxy..company.com", 8080) ws.Proxy = myProxy
Now, we want to perform a keyword search and so we formulate our request using the
KeywordRequest Class. We'll need to specify the various properties within the class. Note that default values for properties are not supported at this moment, so if you leave any properties empty you will get a "404" error.
Dim keywordReq As New KeywordRequest() keywordReq.keyword = txtKeyword.Text keywordReq.type = "heavy" ' type of result expected, lite or heavy keywordReq.devtag = "XXXXX" ' the token assigned to you keywordReq.version = "1.0" ' current version number keywordReq.mode = "books" ' product category, e.g. books, dvd, etc keywordReq.tag = "webservices-20" ' your amazon.com associates ID keywordReq.page = 1 ' page requesting; for long results
After all the properties are filled in, call the Web service. The result is an object of type ProductInfo (which we have declared globally):
Try productsInfo = ws.KeywordSearchRequest( keywordReq) Catch err As Exception MsgBox("Error accessing Amazon.com's Web service. Please try again") Return End Try
This result lets us add them individually to the list box control:
lstTitles.Items.Clear() Dim i As Integer For i = 0 To productsInfo.Details.Length - 1 lstTitles.Items.Add(productsInfo.Details(i). ProductName.ToString) Next
After we've selected the titles within the list box, we can display the information pertaining to a book:
' Displays the title information lblTitle.Text = productsInfo.Details (lstTitles.SelectedIndex).ProductName lblListPrice.Text = productsInfo.Details (lstTitles.SelectedIndex).ListPrice lblAmazonPrice.Text = productsInfo.Details (lstTitles.SelectedIndex).OurPrice
As a book may have more than one author, we need to iterate through the
' Display all the author(s) of a book Dim i As Integer lblAuthors.Text = "" For i = 0 To productsInfo.Details(lstTitles. SelectedIndex).Authors.Length - 1 lblAuthors.Text += productsInfo. Details(lstTitles.SelectedIndex). Authors(i).ToString If i <> productsInfo. Details(lstTitles.SelectedIndex). Authors.Length - 1 Then ' not the last author lblAuthors.Text += ", " End If Next
Most products also have customer reviews and ratings. We can display the average customer ratings using asterisks:
' Displays the average customer ratings using asterisks If Not productsInfo.Details(lstTitles. SelectedIndex).Reviews Is Nothing Then lblRating.Text = "" For i = 1 To productsInfo.Details(lstTitles. SelectedIndex).Reviews. AvgCustomerRating lblRating.Text += "*" Next End If
Finally, let's display the book cover image using the Web Browser OCX Control. My radio buttons control the image size preference:
' Display image according to size preference If optSmall.Checked Then AxWebBrowser1.Navigate(productsInfo. Details(lstTitles.SelectedIndex). ImageUrlSmall) ElseIf optMedium.Checked Then AxWebBrowser1.Navigate(productsInfo. Details(lstTitles.SelectedIndex). ImageUrlMedium) Else AxWebBrowser1.Navigate(productsInfo. Details(lstTitles.SelectedIndex). ImageUrlLarge) End If
That's it! Run the application and try it out! Figure 5 displays what you should see:
Some Other Ffeatures of Amazon.com's Web Service
You may noticed that in the
Page property from the
KeywordRequest class, we've set the value to one:
keywordReq.page = 1 ' page requesting; for long results
By default, Amazon.com will result a maximum of ten products per request. To view the subsequent products matching the search criteria, simply set the page to the page number. So page 2 will display the 11th to 20th products, and page 3 will display the 21st to 30th products, and so on.
Besides the popular keyword search, you can also search by product categories (known as mode). For example, I can search the Books mode using:
keywordReq.mode = "books"
Or I can search the Kitchen mode using:
keywordReq.mode = "kitchen"
You can also search using the ASIN, ISBN, or UPC. ASIN (Amazon Standard Item Number) is a unique identification number for all of Amazon's products. For books, ASIN is similar to ISBN (International Standard Book Number). For CDs and cassettes, Amazon uses the UPC (Universal Product Code). In fact, the search is very comprehensive. Use the following classes for each "power" search:
Dim authorReq As New AuthorRequest()
Dim UPCReq As New UpcRequest()
Dim ASINReq As New AsinRequest()
Dim actorReq As New ActorRequest()
Dim artistReq As New ArtistRequest()
Dim directorReq As New DirectorRequest()
Dim manuReq As New ManufacturerRequest()
Dim listReq As New ListmaniaRequest()
Dim simReq As New SimilarityRequest()
Dim browseReq As New BrowseNodeRequest()
Each class has its own set of properties to which you need to assign values. Using Visual Studio .NET's Intellisense will greatly simplify this task.
Let's discuss the last class,
BrowserNodeRequest, in more detail. If you are a frequent visitor to Amazon, you've noticed that Amazon groups its products into modes (as we discussed earlier) and Browse IDs. For example, the mode "Books" is subdivided into different categories, such as:
Books, Top Selling 1000 Books, Bargain 45 Books, Technical 173507
The number next to each category is known as the Browse ID. To list the products in each Browse ID, use the
Dim browseReq As New BrowseNodeRequest() browseReq.browse_node = "602320" ' Magazines, Business browseReq.type = "heavy" browseReq.devtag = "XXXXX" browseReq.version = "1.0" browseReq.mode = "magazines" browseReq.tag = "webservices-20" browseReq.page = 1 productsInfo = ws.BrowseNodeSearchRequest(browseReq)
For example, the above codes list the products in the "Magazines, Business" category.
Besides using SOAP messages to access the Web service, Amazon also supports the XML/HTTP method. In this article, I've focused primarily on the SOAP method; you should refer to the documentation included in the Developer's kit if you want to use the XML/HTTP method. There are also a couple of advanced features that I have not covered in this article, such as using Amazon's XSLT Service, and how to add products directly into Amazon's shopping cart. Hopefully this article has provided you a jump-start to using Amazon's Web service. Have fun!
Wei-Meng Lee (Microsoft MVP) http://weimenglee.blogspot.com is a technologist and founder of Developer Learning Solutions http://www.developerlearningsolutions.com, a technology company specializing in hands-on training on the latest Microsoft technologies.
The sample code from this article can be downloaded here. (149K zip)
Copyright © 2009 O'Reilly Media, Inc.