Chapter 2. Writing Web Service Clients
Web Services Are Web Sites
In Chapter 1 I showed some quick examples of clients for existing, public web services. Some of the services had resource-oriented RESTful architectures, some had RPC-style architectures, and some were hybrids. Most of the time, I accessed these services through wrapper libraries instead of making the HTTP requests myself.
You can’t always rely on the existence of a convenient wrapper library for your favorite web service, especially if you wrote the web service yourself. Fortunately, it’s easy to write programs that work directly with HTTP requests and responses. In this chapter I show how to write clients for RESTful and hybrid architecture services, in a variety of programming languages.
Example 2-1 is a bare HTTP client for a RESTful web service: Yahoo!’s web search. You might compare it to Example 1-8, the client from the previous chapter that runs against the RPC-style SOAP interface to Google’s web search.
#!/usr/bin/ruby # yahoo-web-search.rb require 'open-uri' require 'rexml/document' require 'cgi' BASE_URI = 'http://api.search.yahoo.com/WebSearchService/V1/webSearch' def print_page_titles(term) # Fetch a resource: an XML document full of search results. term = CGI::escape(term) xml = open(BASE_URI + "?appid=restbook&query=#{term}").read # Parse the XML document into a data structure. document = REXML::Document.new(xml) # Use XPath to find the interesting ...