Week 18 - Creating and Consuming A Web Service PDF

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

Lecture 17: Creating and

Consuming a Web Service


Internet Technologies and Web
Services – CSE2034Y
2

SOAP
SOAP used to be an acronym which stood
for Simple Object Access Protocol in
version 1.1, but as of version 1.2 the
protocol goes simply by the name SOAP.

20
SOAP
• SOAP allows you to build interoperable software and
allows others to take advantage of your software
over a network.
• It defines rules for sending and receiving Remote
Procedure Calls (RPC) such as the structure of the
request and responses.
• SOAP is not tied to any specific operating system or
programming language.
• SOAP is based on XML so it is human-readable, but
there is a specific schema that must be adhered to.
4

Wendy Liu, http://www.cs.toronto.edu/~wl/csc309/handouts/webservice.pdf


SOAP Structure
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Header>
...
</soap:Header>
<soap:Body>
...
<soap:Fault>
...
</soap:Fault>
</soap:Body>
</soap:Envelope>
SOAP Structure
• It is similar to an ordinary XML file, but what
makes it a SOAP message is the root element
Envelope with the namespace soap as
http://www.w3.org/2001/12/soap-envelope.
• The soap:encodingStyle attribute determines the
data types used in the file, but SOAP itself does
not have a default encoding.
SOAP Structure(2)
• soap:Envelope is mandatory
• The next element, soap:Header, is optional and
usually contains information relevant to
authentication and session handling. The SOAP
protocol doesn’t offer any built-in
authentication, but allows developers to include
it in this header tag.
SOAP Structure(3)
• The soap:Body element is required.
• It contains the actual RPC message, including
method names and, in the case of a response, the
return values of the method.
• The soap:Fault element is optional; if present, it
holds any error messages or status information
for the SOAP message and must be a child
element of soap:Body.
SOAP Request
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-
envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-
encoding">
<soap:Body
xmlns:m="http://www.yourwebroot.com/stock">
<m:GetStockPrice>
<m:StockName>IBM</m:StockName>
</m:GetStockPrice>
</soap:Body>
</soap:Envelope>
SOAP Request(2)
• The above is an example of a SOAP request
message to obtain the stock price of a particular
company.
• Inside soap:Body, the GetStockPrice element is
specific to the application.
• It’s not a SOAP element, and it takes its name
from the function on the server that will be
called for this request. StockName is also
specific to the application and is an argument for
the function.
SOAP Response
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-
envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-
encoding">
<soap:Body
xmlns:m="http://www.yourwebroot.com/stock">
<m:GetStockPriceResponse>
<m:Price>183.08</m:Price>
</m:GetStockPriceResponse>
</soap:Body>
</soap:Envelope>
SOAP Response(2)
• Inside the soap:Body element there is a
GetStockPriceResponse element with a Price
child that contains the return data.
• Both GetStockPriceResponse and Price are
specific to this application.
NuSoap Library
• nusoap.php is an open library that provides support for
SOAP functions within your PHP scripts.
• nusoap.php library is available from
http://sourceforge.net/projects/nusoap/
• Download NuSoap and unzip the package in your web
root directry. To use the library just include the
nusoap.php file in your code.
• The result produced is in the format of an array whereas
when using normal PHP an object is obtained as result
and needs to be converted into an array.
• There is no need to write the WSDL file when using
NuSoap
Building a SOAP Server
• For the server, let’s say we’ve been given the task
of building a service to provide a listing of
products given a product category.
• The server should read in the category from a
request, look up any products that match the
category, and return the list to the user in a CSV
format.
• Create a file in your web root named
productlist.php with the following code:
ProductList.php
<?php
require_once "nusoap.php";

function getProd($category) {
if ($category == "books") {
return join(",", array(
"The WordPress Anthology",
"PHP Master: Write Cutting Edge Code",
"Build Your Own Website the Right Way"));
}
else {
return "No products listed under that category";
}
}

$server = new soap_server();


$server->register("getProd");
$server->service($HTTP_RAW_POST_DATA);
ProductList.php - explanations
• First, the nusoap.php file is included to take advantage of
the NuSOAP library.
• Then, the getProd() function is defined. Afterward, a new
instance of the soap_server class is instantiated, the
getProd() function is registered with its register()
method.
• In a real-world scenario you would probably look up the
list of books from a database, but here getProd() is
returns a hard-coded list of titles.
• If you want to include more functionality in the server
you only need to define the additional functions (or even
methods in classes) and register each one as you did
above.
Building a SOAP Client
• Now that we have a working server, let’s build a
client to take advantage of it.
• We will create a file named productlistclient.php
and use the code that follows.
productlistclient.php
<?php
require_once "nusoap.php";
$client = new nusoap_client("http://localhost/nusoap/productlist.php");

$error = $client->getError();
if ($error) {
echo "<h2>Constructor error</h2><pre>" . $error . "</pre>";
}

$result = $client->call("getProd", array("category" => "books"));

if ($client->fault) {
echo "<h2>Fault</h2><pre>";
print_r($result);
echo "</pre>";
}
productlistclient.php(2)
else {
$error = $client->getError();
if ($error) {
echo "<h2>Error</h2><pre>" . $error .
"</pre>";
}
else {
echo "<h2>Books</h2><pre>";
echo $result;
echo "</pre>";
}
}
productlistclient.php – explanations
• Once again we include nusoap.php with require_once and
then create a new instance of nusoap_client.
• The constructor takes the location of the newly created
SOAP server to connect to.
• The getError() method checks to see if the client was created
correctly and the code displays an error message if it wasn’t.
• The call() method generates and sends the SOAP request to
call the method or function defined by the first argument.
The second argument to call() is an associate array of
arguments for the RPC.
• The fault property and getError() method are used to check
for and display any errors. If no there are no errors, then the
result of the function is outputted.
Viewing the page
• Now with both files in your web root directory, launch
the client script in your browser. You should see the
following:
Viewing the request and response
• To inspect the SOAP request and response messages for
debug purposes, these lines can be added at the bottom
of productlistclient.php:
echo "<h2>Request</h2>";
echo "<pre>" . htmlspecialchars($client->request,
ENT_QUOTES) . "</pre>";
echo "<h2>Response</h2>";
echo "<pre>" . htmlspecialchars($client->response,
ENT_QUOTES) . "</pre>";
• The HTTP headers and XML content will now be
appended to the output.
Classwork
• Rewrite the code for productList.php such that now
there is a second function getPublishers which returns a
list of all book publishers. You may use any values that
you wish.
• Rewrite the code for the client such that the method
getPublishers is now called instead of getProd and the
result is displayed on the browser.
WSDL
• Recall: Web Services Description Language (WSDL)
files are XML documents that provide metadata for a
SOAP service.
• They contain information about the functions or
methods the application makes available and what
arguments to use.
• By making WSDL files available to the consumers of
your service, it gives them the definitions they need to
send valid requests precisely how you intend them to be.
Building a WSDL File
• WSDL files can be cumbersome to write by hand as they
must contain specific tags and are usually quite long.
• The nice thing about using NuSOAP is that it can create a
WSDL file for you!
• Let’s modify the SOAP server we made in the first article
to accommodate this.
ProductListAmended.php
<?php
//same as above
$server = new soap_server();
$server->configureWSDL("productlist", "urn:productlist");
$server->register("getProd",
array("category" => "xsd:string"),
array("return" => "xsd:string"),
"urn:productlist",
"urn:productlist#getProd",
"rpc",
"encoded",
"Get a listing of products by category");
$server->service($HTTP_RAW_POST_DATA);
ProductListAmended.php -
explanations
• Basically this is the same code as before but with only a
couple of changes.
• The first change adds a call to configureWSDL(); the
method acts as a flag to tell the server to generate a
WSDL file for our service. The first argument is the name
of the service and the second is the namespace for our
service.
• The second change adds additional arguments to the
register() method.
ProductListAmended.php –
explanations (2)
• getProd is the function name
• array("category" => "xsd:string") defines the input argument to
getProd and its data type
• array("return" => "xsd:string") defines the function’s return value
and its data type
• urn:productlist defines the namespace
• urn:productlist#getProd defines the SOAP action
• rpc defines the type of call (this could be either rpc or document)
• encoded defines the value for the use attribute (encoded or literal
could be used)
• The last parameter is a documentation string that describes what
the getProd function does
Building the WSDL File
• Now if you point your browser to
http://yourwebroot/productlist.php?wsdl and you’ll see
the brand new WSDL file created for you.
• Copy that source and save it as it’s own file called
products.wsdl and place it in you web directory.
Consuming WSDL Files with the Client
• We’ve modified the SOAP server to generate a WSDL
file, so now lets modify the SOAP client to consume it.
• Open up productlistclient.php created in the previous
article and save it as productlistclientAmended.php .
• Change the line that initiates the client from this:
$client = new
nusoap_client("http://localhost/nusoap/productlist.php");
• To:
$client = new
nusoap_client("products.wsdl", true);
Consuming WSDL Files with the
Client(2)
• The second parameter in the nusoap_client()
constructor call tells NuSOAP to build a SOAP client to
accept the WSDL file.
• Now launch productlistclientAmended.php in your
browser and you should see the same result as before,
but now you’re using WSDL power!
References
• Previous Web Lecture Notes
• http://www.sitepoint.com/

You might also like