What is a Web Service? (click any heading below to return here)
"self-contained, self-describing,
modular applications that can be published, located, and invoked across the Web.
Once a Web service is deployed, other applications (and other Web Services) can discover and invoke
the deployed service."
Web services make software functionality available over the Internet. In other words, let someone at another
computer run a program you have on your computer. That way Web applications written in PHP and ASP.Net, can make a
request to a program running on another server (the Web service) and use that program's response in a Web site or other application.
Web Services perform functions, which can be anything from simple requests to complicated business processes.
Thanks to Phil Namoc, Jason Lien and Brian Ellison for this page.
Documenting Web Services: WSDL
The Web Services Description Language (WSDL) grammar is expressed in XML. WSDL describes Web services, including: interface
and end points (or ports), what a service can do, where it resides and how to invoke it via machine-understandable terms targeted
for automated distributed communications between Web applications. Simply, a WSDL definition describes how to access a Web service
and what operations it will perform.
Examples of Web services
Web Services can vary in function from simple operations like the retrieval of a stock quote,
to complex business systems, which access and combine information from multiple sources. Other
examples of web services are:
validating a credit card
retrieving a shipping cost
getting a weather forecast
translating foreign languages
Web services work with standard Web protocols - XML, HTTP and TCP/IP. A simple Web service process can be described by the following.
the Web service provider defines a format for requests for its service and the response
the service will generate
your computer makes a request for the Web services across the network
the Web service performs some action and sends back a response
In the following three examples below, we will be looking at:
a weather service that returns temperatures*
a simple UPS web service to determine shipping rates
a credit card validation web service
The weather example is interesting because your page that shows the temperature does not have to have any JavaScript, or server scripting; simple HTML does the whole job. If you can show an image then you can get the weather. The image attribute src carries the location parameter (temp.php?zip=32507) to the Web service so it will know what region you want the temperature for.
Weather Service
The temperature below is not data in the usual sense. It is an image. The HTML image tag is capable of remote calls to servers to request images, of course, and it can conveniently call for a Web service as well. The service just has to return its information in the form of an image, not text.
If you want to create a Web Service written in PHP that returns images you should start learning about GD which was used to create the example above. The source code for the temperature example is below.
This web service allows users to enter in the weight of their package in pounds and select a shipping
method.
By clicking OK, the data request is sent to a server script (receiveUPS.php). This script
looks up the corresponding shipping rate in a text file database (receiveUPS.txt). The first field is
the method type (UPSGround, Next Day Air, etc.). The second field is the shipping destination country
(1 for USA, 2 for Canada, and 3 for World Wide). The third field is shipping rate in dollars.
And the fourth field is the package weight in pounds.
Once the match is found in the text file, the shipping rate is then sent as a variable in the HTML URL.
print "<script type = 'text/javascript'> location.href=\"receiveUPS.html?charge=$price\"</script>
The variable charge is then read by receiveUPS.html which calculates the total
invoice cost with the new shipping rate included. In this example, the shipping rate of
a 10 lbs package using UPS Ground is $11.
Working Example
The following is a working example of the UPS web service:
Credit Card Validation
The following example is only a demo of a true credit card validation web service. This sample web
service checks to make sure that the credit card number is 16 digits in length and also verifies that
all Visa credit cards begin with with the number 4 (like in the real world).
Web Service Methods
There are two main methodologies of accessing Web services: one is URI-based and the other uses Remote Procedure Calls (RPC). We will examine the URI-centric REST and then the SOAP-RPC methods. Uniform resource information (URI's) may be the familiar URL but could also be simply an abstract reference to resource information.
REST is a standard and an architectural style that uses URI's to access data resources. SOAP is a communication protocol, not a standard or style, that relays resource data requests and responses. Further information on REST and SOAP.
REST
REST stands for REpresentational State Transfer. REST is an architectural style
for network-based systems, as described by Dr. Roy Fielding in his disseration.
He explains that REST "is intended to evoke an image of how a well-designed Web
application behaves: a network of Web pages (a virtual state-machine), where
the user progresses through an application by selecting links (state transitions),
resulting in the next page (representing the next state of the application) being
transferred to the user and rendered for their use."
REST Web services provides URIs to access resource data, commonly in the form of XML.
Making use of HTTP as its communication protocol and XML resource data allows businesses
to communicate the data on any given platform.
REST Example:
Acme, a ficticious shirt supplier, has some Web services that allows its clients to:
get a list of shirt syles
get detailed information about a particular shirt
submit a Purchase Order (PO)
Acme's Web service has a URL that will retrieve a list of shirt styles in XML format:
http://www.acme-shirts.com/shirts/styles
The URL request returns the following data:
A link to the Web service URL makes available a shirt styles list resource. Note that how the Web
service generates the parts list is completely transparent to the client. This XML data would then
be displayed to the client user. The shirt styles resource also provides a URL that would retrieve
further data on a particular style of shirt.This is a key feature of REST. The client transfers from
one state to the next by examining and choosing from among the alternative URLs in the response
document.
Logical vs. Physical URLs
A logical URL:
http://www.acme-shirts.com/shirts/styles/003
A physicalURL:
http://www.acme-shirts.com/shirts/styles/003.html
Using logical URLs saves the Web service developer from having to make several
static pages. With a logical URL, the Web service would take the URL request, parse it
to determine what is being requested, query the database,and generate the
response document which is returned to the client. This would be much more efficient than,
say, writing a HTML page for each shirt style.
Acme example continued ...
Acme also provides a Web service that allows clients to submit Purchase Orders (PO).
The Web service makes available a URL to submit a PO. The client creates a PO instance document
which conforms to the PO schema that Parts Depot has designed (and publicized in a WSDL document).
The client submits PO.xml as the payload of an HTTP POST. The PO service responds to the HTTP
POST with a URL to the submitted PO. Thus, the client can retrieve the PO any time thereafter.
The PO has become a piece of information which is shared between the client and the server. The
shared information (PO) is given an address (URL) by the server and is exposed as a Web service.
Using REST with PHP
To retrieve the XML data via REST (URL) in PHP, you will need to call built-in PHP functions that opens a file and
stores XML into a variable. Look at the following code:
$xurl=fopen($URL,"r");
while (!feof ($xurl))
$xml .= fgets($xurl, 4096);
fclose ($xurl);
fopen(*URL*, *read/write*) retrieves the file from the URL, the first argument of the function.
The second argument refers to whether the file is read-only or not. "r" means the file
will be read-only.
fgets(*resource handler*, *buffer size*) points at a line in the file. The first argument is the
resource to be looked at, in this case it is the opened file. The second argument is a buffer size, and 4096 is
large enough to work with.
fclose(*resource handler*) closes the opened file.
Once the XML stored in a variable, you will need to parse the XML into an array. PHP has built-in functions to
do this. Look at the following code:
// Start the built-in XML parser
$parser = xml_parser_create( );
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
// Set tag names and values
xml_parse_into_struct($parser,$xml,$values,$index);
// Close down XML parser
xml_parser_free($parser);
xml_parser_create() creates a new XML parser.
xml_parser_set_option() sets the options of the parser. XML_OPTION_CASE_FOLDING uppercases elements.
xml_parse_into_struct ( resource parser, data, array &values [, array &index]) actually parses
the XML into an array.
xml_parser_free( closes the parser.
Now, the data for each element is stored into an array by it's element name. Refer to the
PHP manual for more information on these functions.
SOAP
SOAP stands for Simple Object Access Protocol. In Web applications, a
request for an application comes from the client computer and is transmitted over the Internet
to the server computer. There are many ways of doing this, but SOAP makes it easy by
using XML and HTTP - which are already standard Web formats.
SOAP is a simple XML based protocol to let applications exchange information over HTTP.
Simply stated, SOAP provides a way to access services, objects, and servers in a completely
platform-independent manner. Using SOAP you can query, invoke, communicate with, and
otherwise touch services provided on remote systems without regard to the remote system's
location, operating system, or platform.
A SOAP transaction begins with an application making a call to a remote
procedure. The SOAP client script then encodes the procedure request in
XML and sends it over HTTP to a server script. The server parses the
request and passes it to a local method, which returns a response. The
response is encoded into XML by the server and returned as a response to
the client, which parses the response and passes the result to the
original function.
There are two main ways to create and send a soap request to a server:
NuSoap (PHP based)
XML Spy (graphical user interface)
NuSOAP
There are several implementations of SOAP under PHP. The most popular used implementation is NuSOAP,
an external PHP library downloadable at Consuming Web Services with PHP.
Example
Let's take a Barnes & Noble Price Quote server. One of BN's SOAP server methods is getPrice. The method takes an ISBN as input and returns price data from Barnes & Noble. Here is the client script that calls the getPrice:
<?php
// include the SOAP classes
require_once('nusoap.php');
// define parameter array (ISBN number)
$param = array('isbn'=>'0385503954');
// define path to server application
$serverpath ='http://services.xmethods.net:80/soap/servlet/rpcrouter';
//define method namespace
$namespace="urn:xmethods-BNPriceCheck";
// create client object
$client = new soapclient($serverpath);
// make the call
$price = $client->call('getPrice',$param,$namespace);
// otherwise output the result
print "The price of book number ". $param['isbn'] ." is $". $price;
// kill object
unset($client);
?>
In the example, the PHP script first includes the NuSOAP class with the methods needed to access SOAP
services. An array $params is created to store the input parameters for the BN's price method.
Next, the URL of the server application is stored in the variable $serverpath and the namespace
of the method is stored into the variable $namespace. It then creates an instance of a SOAP client called
$client. The script then makes a call to BN's SOAP server via the call() method, passing the method
name, parameters, and the namespace of the method as its arguments. NuSOAP
parses the results in the SOAP response envelope into an array stores
it into $price. The result is printed out and the client object is killed.
A Closer Look at the Transaction
An envelope defines the XML to be a SOAP message. In the body of a request envelope, the client makes a call to procedures and passes its arguments. Here is the example's SOAP request:
The SOAP request is calling a procedure getPrice and with the ISBN argument,
0385503954. The SOAP server receives the request, decodes the procedure calls and invokes the procedure.
The server then packages the response into a SOAP envelope and sends it back to the client.
This SOAP envelope sends the client the getPriceResponse called return with the value of 26.
Applications written for different platforms can "speak" SOAP using HTTP, so they can communicate with each other using data. Platform differneces in native languages are ignored because of SOAP.
XML Spy
Similar to NuSoap, XML Spy also involves manipulating soap envelopes.
However, XML Spy is a smart editing-tool that includes a graphical user interface
for making eXtensible Markup Language (XML) solutions easier.
It claims to be an XML development environment to support the designing and editing of
XML technologies; including XML editing and validation, Schema and Dtd design, and XSL
transformation. XML Spy is the industry standard XML Development Environment for building
software applications based on XML technologies.
This web service will return the price of a book given the ISBN at Barnes and Noble.
Creating a new SOAP request:
1. Open XML Spy 2004 (Enterprise Edition)
2. Select the menu option Soap | Create new SOAP request.
This opens a dialog box where you have to enter the local path or URL of a WSDL file describing
the web service.
3. Click OK to confirm the selection and connect to the server.
This opens a dialog box from which you select a specific SOAP operation.
4. Click the getPrice (string isbn) entry, and confirm with OK.
This creates an Untitled.xml document in XMLSPY 2004 containing the SOAP request data.
One of the features of XML Spy is the ability to view the Soap Document in "Grid" view which
separates each tag into its own grid. Try switching over to "Text" view to see the tags.
By comparison, entering in data for this soap request is more user-friendly in "Grid" view.
5. Click one of the fields to deselect the table highlighting.
Before the request can be sent, we have to specify the ISBN to return its book price.
6. Click the text field, and enter 0439139597.
Now that we have defined the Soap request document, the data needs to be returned back to
the server.
Sending a Soap Request:
1. While the SOAP request document is active, select the menu option
Soap | Send request to server.
After a few seconds, a new XML document is automatically created, containing the SOAP
Response from the respective server. In this example, the price of the ISBN we entered earlier is
displayed in the new document.
In this example, the price of a book with an ISBN of 0439139597 is $18.16.
Question 1: Now that you are familiar with soap requests and how it
works with XML Spy, what is the price of the XML Spy Reference Manual at Barnes and
Noble -- with ISBN of 0595219020?.
Exercise 2: Easter Date Calculator
This web service calculates the date of Easter when given a year.
The URL for this web service is: http://www.stgregorioschurchdc.org/wsdl/Calendar.wsdl
Question 3: What date does Easter fall on in the year 2010?
While NuSoap and XML Spy both use SOAP to transport data, XML data can be sent through
HTTP using XML parsing as well.
XML allows document authors to create their own tags, immediately making it more
powerful and flexible than HTML. Once a file has been created, it needs to be converted
from pure data into something more readable.
However, most browsers do not come with an XML parser or an XSL processor.
The latest versions of Internet Explorer and Netscape Gecko do support XML, but older
versions do not. Using PHP is one way to read XML data source to generate HTML for these
older browsers.
The following script by Brian Ellison shows how to use PHP to read an XML data
file and create an HTML table with the XML data. His method is general, so
it will probably work for most XML files.
Reading XML with PHP scripts
PHP uses native XML parsing functions for getting data from XML documents. An XML document is read in from beginning to end, setting off an event whenever a start tag, end tag, or block of character data is encountered. The data contained in the tags is parsed then stored in an array which may be used by your PHP script for output.
The Code to Parse XML Using PHP
This example (with explanations of the code in red) demonstrates how to get the XML data from the following page : http://www.classanytime.com/mis373/db/inventory.xml. The code can be modified to get data from most XML pages.
<?php
// The variables in xItem are the data you want to extract from the XML page.
In this case we are parsing the ID, ItemName, Description, Price, and Quantity
class xItem {
var $xID;
var $xItemName;
var $xDescription;
var $xPrice;
var $xQuantity;
}
// Declare variables to hold XML data
$arItems = array();
$itemCount = 0;
// URL of XML page to find data
$uFile = "http://www.classanytime.com/mis373/db/inventory.xml";
// startELement function gets the first tag
function startElement($parser, $name, $attrs) {
global $curTag;
$curTag .= "^$name";
}
// endElement gets the closing tag
function endElement($parser, $name) {
global $curTag;
$caret_pos = strrpos($curTag,'^');
$curTag = substr($curTag,0,$caret_pos);
}
// get the data in between the open and closing XML tags
function characterData($parser, $data) {
global $curTag;
// Reference the data in the XML document to extract.
global $arItems, $itemCount;
$itemTitleKey = "^INVENTORY^ITEM^ID";
$itemLinkKey = "^INVENTORY^ITEM^ITEMNAME";
$itemDescKey = "^INVENTORY^ITEM^DESCRIPTION";
$itemMainPriceKey = "^INVENTORY^ITEM^PRICE";
$itemMainQuantityKey = "^INVENTORY^ITEM^QUANTITY";
$itemSupplier = "^INVENTORY^ITEM^SUPPLIER";
// When going through all the items, be sure to go in the order
// that the data comes in the XML document. For example, in our
// XML document the ID comes, first, then the Itemname, then the
// description, and so on. It is important to go in order because
// the parser goes from top to bottom.
if ($curTag == $itemTitleKey) {
// make new xItem
$arItems[$itemCount] = new xItem();
// set new item object's properties
$arItems[$itemCount]->xID = $data;
}
elseif ($curTag == $itemLinkKey) {
$arItems[$itemCount]->xItemName = $data;
}
elseif ($curTag == $itemDescKey) {
$arItems[$itemCount]->xDescription = $data;
}
elseif ($curTag == $itemMainPriceKey) {
$arItems[$itemCount]->xPrice = $data;
}
elseif ($curTag == $itemMainQuantityKey) {
$arItems[$itemCount]->xQuantity = $data;
}
elseif ($curTag == $itemSupplier) {
$arItems[$itemCount]->xSupplier = $data;
// increment item counter
$itemCount++;
}
}
// This PHP parser code is uses the functions above
and stores the XML data into arrays created earlier.
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
if (!($fp = fopen($uFile,"r"))) {
die ("could not open RSS for input");
}
while ($data = fread($fp, 4096)) {
if (!xml_parse($xml_parser, $data, feof($fp))) {
die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
}
}
xml_parser_free($xml_parser);
// Output the data
?>
<html>
<head>
<title>XML report of inventory data</title>
</head>
<body>
<table cellpadding="3" cellspacing="0"
border="1" style="border:1px solid silver;">
<tr>
<th scope="col">Number</th>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Description</th>
<th scope="col">Price</th>
<th scope="col">Quantity</th>
<th scope="col">Supplier</th>
</tr>
<?php
// Loop through the array to extract the parsed data
for ($i=0;$i<count($arItems);$i++) {
$txItem = $arItems[$i];
?>
<tr>
<td scope="row"<?php echo $i; ?></td>
<td<?php echo($txItem->xID); ?></td>
<td<?php echo($txItem->xItemName); ?></td>
<td<?php echo($txItem->xDescription); ?></td>
<td<?php echo($txItem->xPrice); ?></td>
<td<?php echo($txItem->xQuantity); ?></td>
<td<?php echo($txItem->xSupplier); ?></td>
</tr>
<?php
}
?>
</table>
</body>
</html>
The exercise deal with making calls to a web service and presenting the retrieved
data on a page. You will be using PHP to manage the web service calls. Create a page that includes an Amazon Top 10 Bestsellers sidebar and a Web search form as described below.
Exercise 1: Amazon Bestsellers (REST)
This first component will take advantage of Amazon's Web Services. Using Amazon's
extensive API, you will use REST calls to retrieve XML data to be used on your page.
Somewhere on the front page of your site, create a sidebar that displays Amazon.com's top 10 bestsellers for a subject of your interest. Here is a list of possible searches that Amazon makes available:
Querying Amazon Web Service will return the results in XML, which will need to be parsed into a list.
Relevant element names to be used are: 'Asin', 'ProductName', 'Artist' or 'Authors', and 'OurPrice'
Your PHP script will build a list to display the results
Place list somewhere right or left of your page
Each item listed should be linked to Amazon page via the returned 'Asin' in the form of http://www.amazon.com/o/ASIN/[Asin]
To access Amazon's Web Services, you must use a security token. You may use this token:
D3JONB1AX0R25J. Tokens are free and available from Amazon.
Exercise 2: Google Search (SOAP)
Here, you will be taking advantage of Google's web search API. On your page, you will have
a search box that will make SOAP calls to Google's web services. To handle the SOAP calls using PHP, you will need to use the NuSOAP library.
The SOAP search request parameters can be found here.
Google's web service search operation is named doGoogleSearch.
The namespace for Google's doGoogleSearch is called urn:GoogleSearch.
Google also requires a security token. You may use
nU6hkPZQFHJTNzfhCkYADo9JfcY0i2sE. They are free and available
here.
Relevant element names to be used are:
'resultElements' - array of results
'title' - title of result
'URL' - the URL of the site
'snippet' - a small description of the result
Print out just the top 10 results into a list with snippet on a separate page titled eprojectx-google.php
Each result should be linked to the respective sites
Search box must be able to accept multiple terms and specific phrases
Johnny CashCareer ... and
Johnny CashSings Ballads Of The True West (1965). People forget just how hot Johnny Cash
was, when his sales career was at its zenith. ...
johnnycash.com ... painting.
Johnny Cash has been a household name for more than most people can remember, and his
career spanned nearly five decades. ...
Johnny Cash/ Man In Black ...
someone -. 1932-2003. Established February 24, 1998. ash Johnny Cash Johnny
Cash Johnny Cash Johnny Best viewed in 1024x768. The above ...
Johnny Cash - The Man in Black Johnny Cash lyrics, pictures, mp3, audio files, sound samples, biography, facts, address,
and concert informatio. I'll fly a starship ...
Johnny Cash Lyrics Johnny
Cash Classic Lyrics. I plan on adding more lyrics here. Please stop back. If you are looking for
chords, TRY HERE. Written by JR Cash. Big River. ...
Johnny Cash/ Man In Black ... someone -.
1932-2003. Established February 24, 1998. ash Johnny Cash Johnny Cash Johnny
Cash Johnny Best viewed in 1024x768. The above ...