APIFinder
   The essential directory of application programming interfaces
Submit an API
DevX
Function
Language/OS
Contribute
About
Browse DevX
advertisement
Log In | Register
Using Amazon.com’s E-Commerce Web Service
Amazon's E-Commerce service is so popular for good reason. Learn how to build a simple Windows applications that will give you the foundation to do a whole lot more.  
July 11, 2006

advertisement
Amazon.com was one of the earliest public web service providers that allowed developers to tap into its huge amount of product information, such as book synopses, customers’ reviews, products images, etc. Today, Amazon provides a full range of web services targeting different groups of users with different needs. They are:
  • Amazon E-Commerce Service
  • Amazon Historical Pricing
  • Amazon Mechanical Turk (Beta)
  • Amazon S3™
  • Amazon Simple Queue Service (Beta)
  • Alexa Top Sites
  • Alexa Web Information Service
  • Alexa Web Search Platform (Beta)
  • The detailed description of each service offered by Amazon can be found at http://www.amazon.com/gp/browse.html/ref=sc_fe_l_2/102-1695756-7301743?%5Fencoding=UTF8&node=15763381&no=3435361&me=A36L942TSJ2AJA.

    For this article, I will concentrate on the Amazon E-Commerce Service (ECS) Web service, which is the flagship of Amazon's many Web service offerings. Using the ECS, you can query Amazon.com for its products information, such as prices, product images, customers’ reviews, and more.

    To illustrate how to use the Amazon.com ECS web service, I will build a Windows application using Visual Studio 2005. Figure 1 shows what the completed application will look like. The application allows the user to search for products in each of several different categories. You can then drill down to the product specifics, such as ASIN (Amazon Standard Identification Number), price, publisher, authors, reviews, etc. This is a useful application that allows you to quickly search for items from Amazon.com, without needing to use your Web browser to navigate to the Web site.

    Figure 1. The completed application.
    Creating the Application
    Before you can use the ECS web service, you need to register for a free account. You can register for a new account at https://aws-portal.amazon.com/gp/aws/developer/registration/index.html/102-1695756-7301743.

    To build the sample application in this article, you need Microsoft Visual Studio 2005. Figure 2 shows the controls that I have added in the default Form1. For simplicity, I have omitted some of the detailed settings of each control on the form. For the detailed version, I strongly encourage you to download the source code that accompanies this article.

    Populate your form as shown in Figure 2. Once the form is populated, add a Web Reference to the Amazon.com ECS web service. Right-click on the project name in Solution Explorer and select Add Web Reference…. Enter the following URL: http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl . Click Go and then name the Web Reference AmazonWS. Click Add Reference to add the Web reference to the project.

    Coding the Application
    Switch to the code-behind of Form1 and declare the following member variables (within Form1):

    
        Private amazonResponse As AmazonWS.ItemSearchResponse = Nothing
        Private amazonItems As AmazonWS.Item() = Nothing
    
    The amazonResponse variable will be used to store the result returned from ECS. The amazonItems variable will store the product items returned in the result.

    Figure 1. Populating the form with the various controls.
    Next, define the GetProdInformation() subroutine. This will be the main subroutine that communicates with the ECS. Here, you specify the keyword to search for, the type of response (indicates how detailed the response should be), product category, as well as the particular page to return. Eeach response from ECS will return 10 products; to retrieve the next 10 products, you would set the ItemPage property. Also, remember to set the subscription ID that was assigned to you during the registration process; failure to do so will cause the request to ECS to fail.

    
        Public Sub GetProdInformation( _
           ByVal keyword As String, _
           ByVal Category As String, _
           ByVal Page As Integer)
    
            Dim itemSearchRequest As New AmazonWS.ItemSearchRequest
            Dim itemSearch As New AmazonWS.ItemSearch
    
            '---initialize objects---
            With itemSearchRequest
                '---set the search keyword(s)---
                .Keywords = keyword
                '---set the size of the response---
                .ResponseGroup = New String() {"Large"}
                '---set the SearchIndex or search mode---
                .SearchIndex = Category
                '---set the response page---
                .ItemPage = Page
            End With
    
            With itemSearch
                '---set the Amazon.com SubscriptionId---
                .SubscriptionId = "your_subscription_id"
                .Request = New AmazonWS.ItemSearchRequest() _
                   {itemSearchRequest}
            End With
    
            Try
                '---invoke the Amazon.com web service
                amazonResponse = _
                   My.WebServices.AWSECommerceService. _
                   ItemSearch(itemSearch)
                If amazonResponse IsNot Nothing Then
                    amazonItems = amazonResponse.Items(0).Item
                End If
            Catch ex As Exception
                Console.WriteLine("No information returned by Amazon.com")
            End Try
        End Sub
    
    The SearchForProducts() subroutine will call the GetProdInformation() subroutine defined previously. It will also perform some housekeeping tasks such as changing the default cursor to an hourglass and then displaying the results returned from the ECS in the ListBox control (lstProducts). In addition, it populates the ComboBox control (cbbPage) with page numbers if multiple pages are needed to display the results.
    
        Public Sub SearchForProducts( _
           ByVal keyword As String, _
           ByVal Category As String, _
           ByVal Page As Integer)
    
            '---clears the controls---
            lstProducts.Items.Clear()
            ImageList1.Images.Clear()
            txtProductDetails.Text = String.Empty
            txtURL.Text = String.Empty
    
            '---shows the Hourglass cursor---
            Windows.Forms.Cursor.Current = Cursors.WaitCursor
    
            '---communicates with ECS---
            GetProdInformation(keyword, Category, cbbPage.Text)
    
            If amazonItems Is Nothing Then Exit Sub
            Try
                For i As Integer = 0 To amazonItems.Length - 1
                    With amazonItems(i)
                        lstProducts.Items.Add(.ItemAttributes.Title)
                    End With
                Next
    
                '---shows the number of pages available---
                cbbPage.Items.Clear()
                For i As Integer = 1 To amazonResponse.Items(0).TotalPages
                    cbbPage.Items.Add(i)
                Next
            Catch ex As Exception
                MsgBox(ex.ToString)
            Finally
                Windows.Forms.Cursor.Current = Cursors.Default
            End Try
    
        End Sub
    
    Double-click the Search button to reveal its Click event handler. Code the event as follows:
    
        Private Sub btnSearch_Click( _
           ByVal sender As System.Object, _
           ByVal e As System.EventArgs) _
           Handles btnSearch.Click
    
            SearchForProducts(txtSearchKeyword.Text, cbbCategory.Text, 1)
    
        End Sub
    
    When a user selects an item in the ListBox control (lstProducts), you will display the detailed information of the selected item in the TextBox control (txtProductsDetails). You will also download the product image from Amazon.com and display it in the PictureBox control:
    
        Private Sub lstProducts_SelectedIndexChanged( _
           ByVal sender As System.Object, _
           ByVal e As System.EventArgs) _
           Handles lstProducts.SelectedIndexChanged
    
            If lstProducts.SelectedIndex < 0 Then Exit Sub
    
            Dim img As Image = Nothing
            Try
                txtProductDetails.Text = String.Empty
    
                '---display detailed book information
                With amazonItems(lstProducts.SelectedIndex)
    
                    '---displays the product URL---
                    txtURL.Text = .DetailPageURL
    
                    '---displays the ASIN number---
                    txtProductDetails.Text &= "ASIN: " & _
                       .ASIN & vbCrLf
    
                    '---displays the product title---
                    txtProductDetails.Text &= "Title: " & _
                       .ItemAttributes.Title & vbCrLf
    
                    '---displays the producer---
                    txtProductDetails.Text &= "By: " & _
                       Join(.ItemAttributes.Author, ",") & vbCrLf
    
                    '---displays the publisher/manufacturer---
                    txtProductDetails.Text &= _
                       "Publisher/Manufacturer: " & _
                       .ItemAttributes.Publisher & vbCrLf
    
                    '---displays the price---
                    txtProductDetails.Text &= "Price: " & _
                       .ItemAttributes.ListPrice.FormattedPrice. _
                       ToString() & vbCrLf
    
                    '---displays the average ratings---
                    txtProductDetails.Text &= "Ratings: " & _
                       .CustomerReviews.AverageRating.ToString & vbCrLf
    
                    '---displays total reviews---
                    txtProductDetails.Text &= "Total Reviews: " & _
                       .CustomerReviews.TotalReviews.ToString & vbCrLf
    
                    '---displays customers' reviews---
                    Dim reviews As String = String.Empty
                    For i As Integer = 0 To .CustomerReviews.Review. _
                       Length - 1
                       reviews &= vbCrLf & """" & _
                       .CustomerReviews.Review(0).Content & _
                       """" & vbCrLf & vbCrLf
                    Next
                    txtProductDetails.Text &= "Customers Review: " & _
                       reviews
    
                    '---download the product image---
                    Dim webReq As Net.HttpWebRequest = _
                       Net.HttpWebRequest.Create(.MediumImage.URL.ToString)
                    Dim webResp As Net.HttpWebResponse = _
                       webReq.GetResponse()
    
                    '---displays the image---
                    img = Image.FromStream(webResp.GetResponseStream())
                    PictureBox1.Visible = True
                    PictureBox1.Image = img
                End With
            Catch ex As Exception
                If img Is Nothing Then
                    PictureBox1.Visible = False
                End If
            End Try
        End Sub
    
    Finally, the user can select to view the results of a particular page by selecting the page number in the ComboBox control (cbbPage) and clicking on the Go button:
    
        Private Sub btnGo_Click( _
           ByVal sender As System.Object, _
           ByVal e As System.EventArgs) _
           Handles btnGo.Click
            SearchForProducts( _
               txtSearchKeyword.Text, _
               cbbCategory.Text, _
               CInt(cbbPage.Text))
        End Sub
    

    Summary
    In this article, you have seen how you can easily retrieve products information from Amazon.com’s ECS web service. The sample application shown in this article can be adapted for your own use and you can also easily convert it to a Web application. For more ideas on how to incorporate ECS into your own application, check out the reference application at the following site: http://www.amazon.com/gp/browse.html/ref=sc_fe_l_1/102-1695756-7301743?%5Fencoding=UTF8&node=3434671&no=3435361&me=A36L942TSJ2AJA.

Wei-Meng Lee(http://weimenglee.blogspot.com) is a Microsoft MVP and founder of Developer Learning Solutions (http://www.developerlearningsolutions.com), a technology company specializing in hands-on training on the latest Microsoft technologies. He is an established developer and trainer specializing in .NET and wireless technologies.

Wei-Meng speaks regularly at international conferences and has authored and co-authored numerous books on .NET, XML, and wireless technologies. He writes extensively on topics ranging from .NET to Mac OS X. He is also the author of the .NET Compact Framework Pocket Guide, ASP.NET 2.0: A Developer's Notebook (both from O'Reilly Media, Inc), and Programming Sudoku (Apress).


Amazon E-commerce Service
This SDK offers you a nearly infinite number of ways to include product information in your web site or application. Search by product keyword, company or artist keyword, display images, prices, etc. The Amazon E-commerce Web service is also a way to earn money by becoming an Amazon affiliate seller. You get a small cut of the profits from every sale generated by your site visitors.
Provider: Amazon   Cost: 0