In the most generic sense, a Web service

As you can see from the previous code example, this is a contact record with two contacts, John Doe Doe. For each contact, a contact type and a first and last name are specified. This XMLdocumentcan be sent to a mainframe, a Windows computer, a UNIX computer, and a Linux computer. All thesecomputers can read it because it is a text file. Invoking an XML Web ServiceAvery important aspect of communicating with a Web service is how you can physically execute a ified function. XMLWeb services are based on standard Internet protocols and allow you to invoke through communication mechanisms such as HTTP-GET, HTTP-POST, or SOAP over HTTP, in more detail in the following sections. Some Web APIs covered in this book, such as Amazon sWeb API, support both the HTTP-GET and SOAPoptions, although others support only one method. Web service providers can enable all three methods, but they typically disable one or more that theydecide are not appropriate or desirable for various reasons. The fact that vendors support differentmethods is the subject of much debate. You should, however, understand how to use each method can work with the various Web APIs that are available. The methods are introduced here, but I them in greater detail in the chapters that follow. Invoking a Web Service Using REST (HTTP-GET) RESTstands for Representational State Transfer.It refers to invoking a Web service using parametersincluded in a URL. REST uses HTTP-GET to retrieve data and is not typically used for data updates. After a request is processed, REST returns an XMLdocument. Let s look at an example of calling an Amazon Web service using REST. Suppose you have thefollowingURL: http://aws- beta.amazon.com/onca/xml?Service=AWSProductData&SubscriptionId=YOUR_ID_GOES_HERE&ItemSearch&SearchIndex=Books&Keywords=Denise%20GosnellNotice how the first part of the URLcontains the traditional domain information. Next, you see the ous parameters being passed. These parameters are being passed to an Amazon API (currently version4.0 beta). The URLincludes a parameter for the service being called (AWSProductData), the subscriptionID (your developer token), the operation to perform (a search), the search index to use (books), and to search on (Denise Gosnell). Parameters are separated by ampersands (&), and spaces areindicated by %20. As you can see, it is really quite easy to call a Web service using REST, if the Web service supports REST. You can then use your programming language of choice to execute the HTTP-GET command containingthe URLand process the XMLfile that is returned. You will see examples of this in action throughoutthebook. It is very easy to test a REST Web service from your Web browser. Pasting the URLlisted previously Web browser returns results similar to those shown in Figure 1-1.3Anatomy

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Clan Web Hosting services

In the most generic sense, a Web service

In the most generic sense, a Web service is merely a function or procedure that can be called over theInternet. This generic definition includes Web services that can be called only from specific platforms, such as Windows, and only after installation of certain software on the client. However, in the context ofthis book, the term Web servicerefers to services that are platform-neutral and so can be called from anyplatform capable of communicating using standard Internet protocols. These platform-neutral Web serv- ices are sometimes referred to as XMLWeb servicesbecause XMLis typically the data transfer formatused for them. XMLis a text-based syntax that can be understood by various platforms, as I discuss in alater section. Despite common misconceptions, XMLWeb services can be called from applications thatare not browser-based, such as traditional Windows applications. As long as the application can commu- nicate using Internet protocols, non-Web based applications can make use of the same functionality. Despite the great value of Web services, their adoption industry-wide has been slow in coming. Thegreat news is that, as of this writing, Web APIs and Web services have finally been adopted by big play- ers in the industry. Industry leaders such as Google, Amazon, and eBay have embraced the Web servicesconcept and have created Web APIs that enable you to implement their core features in your own appli- cations. This recent movement toward Web APIs is my primary reason for writing this book. In it, youwill, of course, explore several leading Web APIs to learn how you can use them in your applications. As you will see in the following chapters, most of these leading Web APIs require you to obtain a devel- oper token that must be included in each request. Vendors require a developer token in order to controlhow much you use (and thus not abuse) the service and/or how much they should charge you. MostWeb APIs have a free limited-use license or trial period, and some of them require payment for the service. Web APIs as XML Web ServicesAs I mentioned previously, Web APIs are typically a related collection of Web services. Most of the Webservices available today are based on XMLand can, therefore, be called from various platforms. Thefocus of this book is primarily on XMLWeb services. Therefore, a brief explanation on XMLis appropri- ate before you learn the basics of calling XMLWeb services in your programs. What Is XML? XMLstands for eXtensible Markup Language, which is a text-based markup language. XMLis similar toHTMLin many ways, such as how it describes data by using tags. Avery simple example of an XMLdocument is shown here. < ?xml version= 1.0 encoding= UTF-8 ?> John Doe Jane Doe 2Chapter

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Clan Web Hosting services

Figure 12-13SummaryIn this chapter, you created a simple

Anatomy of a Web APIIn this chapter, you will learn the basic concepts of Web APIs that I use throughout the rest of thebook. Web APIs are application programming interfaces that can be called over standard Internetprotocols. Many companies are using Web APIs to expose functionality in their existing systemsina platform-neutral manner. Other companies are building applications from the ground up asWeb APIs. Web APIs generally allow remote computers on different platforms to talk to eachotherusing methods that were previously very difficult. This chapter will specifically cover thefollowing: .What a Web API is and how it differs from a Web service .The current status of Web APIs in the industry .Calling a Web API using REST (HTTP-GET) .Calling a Web API using HTTP-POST .Calling a Web API using HTTPand SOAPWeb APIs versus Web ServicesWeb APIs are application programming interfaces that are available over the Internet. They arealso sometimes referred to as Web services. It is helpful to think of a Web API as a series of Webservices, each of which has one or more procedures that can be called using the Internet. An exam- ple of a Web API includes the Google API, which makes various search functions available overthe Internet for use in third-party applications. Although Web APIs and Web services are separateconcepts, it is common and acceptable to refer to the two concepts interchangeably because theyare so closely related.

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Inexpensive Web Hosting services

Figure 12-13SummaryIn this chapter, you created a simple

Figure 12-13SummaryIn this chapter, you created a simple dashboard application that uses the Google, Amazon.com, and to retrieve data that is used in interesting ways in the browser. You have successfully completed chapters in this book. You should now have a basic ability to interact with the Web APIs coveredherein and also feel comfortable learning about new APIs on your own. This book just scratches the face on the wonderful opportunities that are available to you today with some existing Web APIs and bit of your imagination.

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Inexpensive Web Hosting services

Figure 12-10Figure 12-11277Case

On first glance, this screen looks like nothing more than the Amazon.com page that corresponds to theiPod device. However, if you scroll down in the browser window, you also see information displayedfrom the Epinions.com Web site that contains reviews of the iPod. An example of this is illustrated inFigure 12-12. Figure 12-12If you think about what was done here, it is really pretty cool. You used Google to retrieve a link to anEpinions Web page containing a review of the product specified in the search. You then retrieved theactual page from the Epinions Web page and programmatically displayed it in the same browser win- dow with the rest of the results. Scrolling down even farther leads you to a section of the browser page where the eBay search results areshown. Figure 12-13 provides an example of what this screen might look like. In the eBay section, some basic information is provided about the item along with a hyperlink to the auc- tion listing. The calls to Amazon.com and Google are hitting the live sites, whereas the call to eBay is hitting theSandbox test environment. The same code would also work against the live eBay site. That s it. See, it really is simple to integrate data from multiple APIs into your programs. 278Chapter

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Adult Web Hosting services

Figure 12-10Figure 12-11277Case

Figure 12-10Figure 12-11277Case

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Adult Web Hosting services

Sub SearchEbay() This procedure searches eBay for the

items.Item.ListingDetails.ViewItemURL &
strOutput = strOutput & Listing Duration: & _ items.Item.ListingDuration & vbCrLfstrOutput = strOutput & Time Left: & items.Item.TimeLeft & _

NextResponse.Write(strOutput) End Sub6.Add the WritePageContentsToBrowserprocedure to the code section: Sub WritePageContentsToBrowser(ByVal strURL As String) retrieve the page at the specified URL into a response streamDim wrq As WebRequest = WebRequest.Create(strURL) Dim wrp As WebResponse = wrq.GetResponse() Dim sr As StreamReader = New StreamReader(wrp.GetResponseStream()) read the entire stream containing the specified page and display it in the browserResponse.Write(sr.ReadToEnd) write some blank lines to the browserResponse.Write(

) End SubNice work you are now finished writing the code for the dashboard application. Make sure to saveyour changes to the project and to compile and resolve any compiler errors. At the time of this book s writing, there is a problem with the Amazon.com WSDLfile that requiresmanual correction. If you receive an error message stating that CustomerReviews1 cannot be reflectedor a similar error regarding CustomerReviews1, then please consult Chapter 4 for a detailed descriptionof how to resolve the error. Touring the Completed ApplicationAs you tour the dashboard application, you can see for yourself that it really is a simple example thatcould be enhanced in many ways. I purposely kept the example simple to illustrate how much you cando with third-party APIs and just a little code. Go ahead and run the program by pressing F5. Youshould see an opening screen similar to the one shown in Figure 12-10. Enter some search criteria for some electronic equipment of interest and click the Search button. Thecode currently filters the Amazon.com results by the electronic category, but you can revise the categoryto books or something else by changing the property in the code section. Suppose that you specified criteria for ipod, to search for reviews and availability of Apple iPod devices. When you click the Search button, you should see a screen similar to the one shown in Figure 12-11.276Chapter

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Adult Web Hosting services

Sub SearchEbay() This procedure searches eBay for the

Sub SearchEbay() This procedure searches eBay for the specified criteria and then displays a list of auctions that contain the criteriaDim strToken As StringDim strDevId As StringDim strAppId As StringDim strCertId As StringResponse.Write( ————————————————
) Response.Write _ ( Results From eBay (Sandbox test environment):

) specify credentials required to access APIstrToken = YOUR EBAY TOKEN strDevId = YOUR EBAY DEV ID strAppId = YOUR EBAY APP ID strCertId = YOUR EBAY CERT ID Dim SOAPService As New eBay.eBayAPIInterfaceServiceSOAPService.Url = https://api.sandbox.ebay.com/wsapi & _ ?callname=GetSearchResults&siteid=0&appid= & _ strAppId & version=383 SOAPService.RequesterCredentials = New eBay.CustomSecurityHeaderTypeSOAPService.RequesterCredentials.eBayAuthToken = strTokenSOAPService.RequesterCredentials.Credentials = New eBay.UserIdPasswordTypeSOAPService.RequesterCredentials.Credentials.AppId = strAppIdSOAPService.RequesterCredentials.Credentials.DevId = strDevIdSOAPService.RequesterCredentials.Credentials.AuthCert = strCertIdDim Request As New eBay.GetSearchResultsRequestTypeDim Resp As New eBay.GetSearchResultsResponseType specify the search criteria and versionRequest.Query = txtSearch.TextRequest.Version = 383 call the GetSearchResults method to run the searchResp = SOAPService.GetSearchResults(Request) Dim items As eBay.SearchResultItemTypeDim strOutput As StringIf Resp.SearchResultItemArray Is Nothing Then Exit Sub loop through the results and display the resultsFor Each items In Resp.SearchResultItemArraystrOutput = strOutput & Title: & items.Item.Title &
strOutput = strOutput & Item Id: & items.Item.ItemID &
strOutput = strOutput & Item URL: & _

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Adult Web Hosting services

Response.Write( ) SearchAmazon() SearchGoogle() SearchEbay() End Sub3.Add the SearchAmazonprocedure

4.Add the SearchGoogleprocedure to the code section: Sub SearchGoogle() This procedure will retrieve and display the first page from google that is contained on epinions.com with the specified search criteria. Epinions.com is a consumer review web site. Response.Write( ————————————————
) Response.Write( Epinions Page Found Using Google:

) Create a Google Search objectDim Search As New Google.GoogleSearchServiceDim strLicense As StringDim strSearchText As StringDim intStart As IntegerDim intMaxResults As Integer set the values to pass to the Google web service set your developer license keystrLicense = YOUR GOOGLE LICENSE KEY Set the search criteria to search the epinions site for the value the user entered in the search text box. strSearchText = site:www.epinions.com & txtSearch.TextintStart = 0intMaxResults = 1 execute the doGoogleSearch method to retrieve the epinions page for the particular product matching the search criteriaDim SearchResult As Google.GoogleSearchResult = _ Search.doGoogleSearch(strLicense, strSearchText, _ intStart, intMaxResults, False, , False, , , ) if no results were returned then exitIf SearchResult.resultElements Is Nothing Then Exit Sub work with the results to retrieve the URL of the epinions page that was returned in the searchDim result As Google.ResultElementDim strURL As StringFor Each result In SearchResult.resultElements write the page to the browserWritePageContentsToBrowser(result.URL) Exit ForNextEnd Sub5.Add the SearchEbayprocedure to the code section: 274Chapter

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Adult Web Hosting services

Response.Write( ) SearchAmazon() SearchGoogle() SearchEbay() End Sub3.Add the SearchAmazonprocedure

Response.Write(

) SearchAmazon() SearchGoogle() SearchEbay() End Sub3.Add the SearchAmazonprocedure to the code section: Sub SearchAmazon() This procedure searches Amazon.com for the specified criteria and then displays the first Amazon.com page that corresponds to the particular item. Response.Write(

Results From Amazon.Com:

) Dim AmazonProductData As New AWSECommerceServiceDim AmazonSearch As New ItemSearchDim AmazonResponse As New ItemSearchResponseDim AmazonRequest(1) As ItemSearchRequest Developer/Subscription CodeAmazonSearch.SubscriptionId = YOUR AMAZON SUBSCRIPTION ID HERE We are only making one request, not batching multiple requests Thus element 0 of the array is all we need to assign and work withAmazonRequest(0) = New ItemSearchRequestAmazonRequest(0).SearchIndex = Electronics AmazonRequest(0).Keywords = txtSearch.Text assign the search object to the request object with the assigned parametersAmazonSearch.Request = AmazonRequest run the search and populate the responseAmazonResponse = AmazonProductData.ItemSearch(AmazonSearch) If AmazonResponse.Items(0).Item Is Nothing Then Exit SubDim item As New Item loop through the resultsFor Each item In AmazonResponse.Items(0).Item display the amazon.com page in the browserWritePageContentsToBrowser(item.DetailPageURL) Exit ForNextEnd Sub273Case

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Adult Web Hosting services