Design Studio

Design Studio

Web Services
Table of Contents
Module Overview 3
Introduction 4
Program to Program Communications 5
RESTfull Services 10
Consumption of an Existing SOAP Web Service 15
Creating Web Services 20
Lab 12 26
Module Overview
In this module, you will learn how information exchange problem can be solved by using web services. E-Commerce that provides business-to-customer communication was the first step. The next step is business-to-business communications.
Objectives
After completing this module, you will be able to:
• create custom web services
• consume web services using php
Assigned Reading
• SOAP vs REST http://www.ajaxonomy.com/2008/xml/web-services-part-1-soap-vs-rest
• Understanding web services specifications, Part 1: SOAP http://www.ibm.com/developerworks/webservices/tutorials/ws-understand-web-services1/ws-understand-web-services1.html
• RESTful Web Services http://www.oracle.com/technetwork/articles/javase/index-137171.html
Additional Reading
• 10 top IT skills in demand: a one-day snapshot http://www.zdnet.com/10-top-it-skills-in-demand-a-one-day-snapshot-7000005443/
Time to Complete
• 1-2 hours
Assessments and Assignments
• Lab

Introduction
What is a web service?
The W3C defines a Web service as a software system designed to support interoperable machine-to-machine interaction over a network. Web services are frequently just application programming interfaces (API) that can be accessed over a network, such as the Internet, and executed on a remote system hosting the requested services.
SOAP (Simple Object Access Protocol) is a protocol for exchanging XML-based messages over computer network.
WSDL (Web Services Description Language) is an XML format published for describing Web services.
UDDI is a protocol for publishing and discovering metadata about Web services, to enable applications to find Web services, either at design time or runtime.
WS-Security defines how to use XML Encryption and XML Signature in SOAP to secure message exchanges.
It uses XML documents through communication over TCP/IP. It can be used with any programming languages. It is also hardware and Operating System independent.

Why do we need web services?
If we are looking for telephone numbers, we can check Yellow Pages. If we look for software applications, we search Internet. But HTML and browsers are created for humans. SOAP and XML-based web services make program to program communications possible.
An application might need:
• Credit card verification
• Package shipping
• Currency conversion
• Stock quotes
These services have been implemented already, so you do not need to start from scratch. There are many sites that list available services, for example http://www.webservicex.net
Program to Program Communications
Ideal scenario for inventory management:
Inventory management software is aware of quantities of each product that have to be stored in the warehouse. It is predicted by using data mining techniques. When quantity reaches reorder point, inventory management software locates web services of all vendors of that particular product, finds the best price and orders necessary quantity (without human participation).

Web Service:
• exposes functionality through standard protocol (e.g. SOAP)
• describes it interfaces using Web Services Description Language (WSDL)
• registered using Universal Discovery Description and Integration (UDDI) so it can be consumed
Simple Object Access Protocol
• application2application
• over SMTP or HTTP
• must use SOAP envelope
• relies on Web Services Description Language
• runs in request/response fashion
• defines a structure to call method and pass method parameters
• defines a structure for return values and errors (faults)

SOAP message example
<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>
<addTwoNumbers>
<number1>3</number1>
<number2>5</number2>
</addTwoNumbers>
<soap:Fault>
. . .
</soap:Fault>
</soap:Body>
</soap:Envelope>

<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>
<addTwoNumbersResponse>
<additionResult>8</additionResult>
</addTwoNumbersResponse>
<soap:Fault>
. . .
</soap:Fault>
</soap:Body>
</soap:Envelope>
Service has one operation addTwoNumbers that takes two parameters number1 and number2. The result is additionResult.
Web Services Description Language
• XML based
• describes web services
• list of methods available
WSDL example: http://www.w3.org/TR/wsdl#_wsdl
WSDL Components
• <types> a container for data type definitions
• <message> an abstract, typed definition of the data being communicated.
• <operation> an abstract description of an action supported by the service.
• <portType> an abstract set of operations supported by one or more endpoints.
• <binding> a concrete protocol and data format specification for a particular port type
• <port> a single endpoint defined as a combination of a binding and a network address.
• <service> a collection of related endpoints.
WSDL Binding
• maps the abstract service functionality to a specific network protocol and message format
• defines:
– the communication protocol to use
– how service interactions are accomplished using this protocol
– the address to communicate with
• Three bindings are defined in the WSDL spec:
– SOAP binding
– HTTP binding
– SMTP binding
Universal Description, Discovery, and Integration UDDI
• XML based
• open industry initiative
• service providers
• Bindings (locations) of those services
• Interfaces supported by those services
• White Pages (by business)
• Yellow Pages (by category)
• Green Pages (how to invoke)
UDDI Entries
• businessEntity – provider of service
• businessService – collection of related services
• bindingTemplate – information necessary to use
• tModel – “reusable concept” such as
o Interface
o Protocol used by web services
o Category
• publisherAssertion – relationship that business entity has with another businessEntity
• Subscription – request to be informed of particular changes
UDDI Related Standards
• WS- Addressing (endpoint references)
• WS-Routing (in what order)
• WS-Security
• WS-Policy
Web Services Inspection Language (WSIL or WS-Inspection )
• XML based
• web services and their endpoints
• joint Microsoft & IBM project
• replaces DISCO (Discovery of Web Services) and ADS (Advertisement and Discovery of Services)
WSIL example: http://msdn2.microsoft.com/en-us/library/ms951265.aspx
<?xml version=”1.0″?>
<inspection xmlns=”http://schemas.xmlsoap.org/wsil/”
xmlns:wsiluddi=”http://schemas.xmlsoap.org/wsil/uddi/”>
<service>
<abstract>A stock quote service with two descriptions</abstract>
<description referencedNamespace=”http://schemas.xmlsoap.org/wsdl/”
location=”http://example.com/stockquote.wsdl”/>
<description referencedNamespace=”urn:uddi-org:api”>
<wsiluddi:serviceDescription
location=”http://www.example.com/uddi/inquiryapi”>
<wsiluddi:serviceKey>
4FA28580-5C39-11D5-9FCF-BB3200333F79
</wsiluddi:serviceKey>
</wsiluddi:serviceDescription>
</description>
</service>
<service>
<description referencedNamespace=”http://schemas.xmlsoap.org/wsdl/”
location=”ftp://anotherexample.com/tools/calculator.wsdl”/>
</service>
<link referencedNamespace=”http://schemas.xmlsoap.org/wsil/”
location=”http://example.com/moreservices.wsil”/>
</inspection>
RESTfull Services
REpresentational State Transfer (REST) is a stateless client-server architecture in which the web services are viewed as resources and can be identified by their URLs.
When to use RESTfull service? When you need to expose a public API over the Internet to perform CRUD (create, read, update and delete) operations on data.
Making calls to an HTTP API is significantly easier, so it is a “thinner client”. SOAP based services provide more functionality.
Example:
The request:

GET /StockPrice/IBM HTTP/1.1
Host: example.org
Accept: text/xml
Accept-Charset: utf-8

The response:
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: nnn

<?xml version=”1.0″?>
<s:Quote xmlns:s=”http://example.org/stock-service”>
<s:TickerSymbol>IBM</s:TickerSymbol>
<s:StockPrice>45.25</s:StockPrice>
</s:Quote>
SOAP
Pros:
• Language, platform, and transport independent
• Designed to handle distributed computing environments
• Is the prevailing standard for web services, and hence has better support from other standards (WSDL, WS-*) and tooling from vendors
• Built-in error handling (faults)
• Extensibility
Cons:
• Conceptually more difficult, more “heavy-weight” than REST
• Harder to develop, requires tools
REST
Pros:
• Language and platform independent
• Much simpler to develop than SOAP
• Small learning curve, less reliance on tools
• Concise, no need for additional messaging layer
• Closer in design and philosophy to the Web

Cons:
• Assumes a point-to-point communication model–not usable for distributed computing environment
• Lack of standards support for security, policy, reliable messaging, etc., so makes it harder to develop
• Tied to the HTTP transport model
Restful Services Implementation
We will use a Slim framework for PHP 5 to quickly write a simple web application http://www.slimframework.com/
1. Create a new directory under htdocs and name it m12.
2. To install SLIM, download the ZIP file from GitHub https://github.com/slimphp/Slim/archive/2.6.2.zip and unzip it to the m12 directory on your USD drive. Name the directory slim. Your directory structure should look similar to:

3. Once it has been extracted to the m12 directory, visit the index.php page http://localhost/m12/slim to receive a welcome message. If there is no error, then the installation was successful.

4. Next, will create a “Hello, World” program for SLIM. You can do this by modifying index.php in m12/slim directory
<?php

//Include Slim Framework
require ‘Slim/Slim.php’;
use SlimSlim;
Slim::registerAutoloader();

// Instantiate a Slim application
$app = new Slim();

// add new Route
// when user requests root of your web application (in our case
// http://localhost/m13/slim) the welcome message is displayed
$app->get(“/”, function () {
echo “<h1>Hello, World</h1>”;
});

// Run the Slim application
$app->run();
?>

5. Visit the url http://localhost/m12/slim
You should see a page that is similar to this screen
6. Now we will add another route that will request your name as a parameter and will display customized greeting.
// add one more Route
// read what is supplied after /m13/slim/ and read it in a variable $name
$app->get(“/:name”, function ($name) {
echo “<h1>Hello, $name</h1>”;
});

7. We can also add a route to find sum of two numbers via HTTP request.
// add one more Route
// read what is supplied after /m13/slim/add and read numbers into variables
// $number1 and $number2
$app->get(“/add/:number1/:number2”, function ($number1, $number2) {
echo “$number1 + $number2 = ” . ($number1 + $number2);
});
8. You will get a screen similar to this:

Please note that it is case sensitive http://localhost/m12/slim/add/3/4 is not the same as http://localhost/m12/slim/Add/3/4 .
We did not add any error handling and if user types string instead of a number, the result will be

Consumption of an Existing SOAP Web Service
First, we will write a client to consume an existing web service.
We will use Weather service available at http://graphical.weather.gov/xml/SOAP_server/ndfdXMLserver.php#
Description is available at http://graphical.weather.gov/xml/DWMLgen/wsdl/ndfdXML.wsdl
We will use one method called NDFDgen. The wsdl file lists all parameters this method uses and name of the returned result.

<message name=”NDFDgenRequest”>
<part name=”latitude” type=”xsd:decimal” />
<part name=”longitude” type=”xsd:decimal” />
<part name=”product” type=”typens:productType” />
<part name=”startTime” type=”xsd:dateTime” />
<part name=”endTime” type=”xsd:dateTime” />
<part name=”Unit” type=”typens:unitType” />
<part name=”weatherParameters” type=”typens:weatherParametersType” />
</message>

<message name=”NDFDgenResponse”>
<part name=”dwmlOut” type=”xsd:string” />
</message>
First, we will evoke this service from the demonstration page http://graphical.weather.gov/xml/SOAP_server/ndfdXML.htm using KSU Marietta Campus’ LatLng(33.939248,-84.519796) and weather at a Glance.

The resulting xml file will contain a seven-day forecast.

Now we will write our own SOAP client. Create weather_client.php file in m12 directory
<?php
//assign values to parameters in order
//to find weather on SPSU campus
$latitude = ‘33.939248’;
$longitude = ‘-84.519796’;
$product = ‘glance’;
$startTime = ”;
$endTime = ”;
$weatherParameters = NULL;

//location of the web service
$client = new SoapClient(“http://graphical.weather.gov/xml/DWMLgen/wsdl/ndfdXML.wsdl#NDFDgen”);
try{
//SOAP call
$result = $client->NDFDgen($latitude, $longitude, $product, $startTime, $endTime, $weatherParameters);
//display results
echo $result;
}
catch (SoapFault $exception) {
echo $exception;
}
?>
The result will be the same xml file as we received before, but it will be displayed as a text.

If we check source code of the page, we will see that it is an XML file

We can replace echo $result with the following two lines
$xml = simplexml_load_string($result);
echo “Todays maximum temperature is :
{$xml->data->parameters->temperature->value}”;

The value for the value XML tag will be displayed.

You can also use xsl transformation (see XML module)
Creating Web Services
Now we will write our own web service. Create file helloService.php
<?php
//define operation name and number of parameters
function hello($name) {
//define response
$result = ‘Hello, ‘.$name;
//return response to a caller
return $result;
}

//assign unique uri to your web service
$server = new SoapServer(null, array(‘uri’ => “http://designstudio1/hello”));

//add defined above operation to your service
$server->addFunction(‘hello’);
$server->handle();
?>

This service has one operation hello that takes one parameter name and returns string “Hello, name”. If you open this file in a browser http://localhost/m12/helloService.php , you will not get any results. We have to write a client to consume this web service.
Create file HelloClient.php
<?php
//specify location and uri of web service
$client = new SoapClient(null, array(‘location’ =>
“http://localhost/m12/helloService.php”,
‘uri’ => “http://designstudio1/hello”));

//make a SOAP call to web service specifying
//operation and name and value for the parameter
$result = $client->__soapCall(‘hello’,
array(‘name’ => ‘Sam’));
echo $result;
?>
Open this file in the browser, the result should be

Sam is displayed because we assigned value Sam to parameter name ‘name’ => ‘Sam’
The call specifies:
• ‘hello’ – name of the function in the web service
• array(‘name’ => ‘Sam’) – array of parameters ‘parameter_name’ => ‘parameter_value’
If web service requires two parameters first_name and last_name, the call will use
array(‘first_name’ => ‘Sam’, ‘last_name’ => ‘Forest’)
It is also very important to specify correct location of your web service. We used http://localhost/m12/helloService.php
NOTE: URI in client and service has to be the same (it is a unique string with no physical meaning. BLANK LINES and SPACES before <?php and after ?> will cause errors.
If you view source of this page, you will find that result is not XML document.
To generate WSDL for your service we will use Services_Webservice that available as part of PEAR – PHP Extension and Application Repository. Check your USB drive (X:xamppphpPEAR) to see all available extensions.
If Services is not listed (no such folder) or if the folder does not have Webservice.php file, then you need to install it. Open Command Prompt (as administrator), switch to you PHP XAMPP folder and type
pear install Services_Webservice-0.5.1
You should see “Install OK”

If you have problems with Services_Webservice installation:
1. Check that you running Command Prompt window as administrator.
2. Try to update PEAR and clear the cache
pear clear-cache
pear update-channels

Now we will modify our helloService.php file
<?php
//include Services_Webservice extension
include_once(‘Services/Webservice.php’);

//define class
class phpService extends Services_Webservice
{
/**
* Returns “Hello, Name”
*
* @param string
* @return string
*/
//declaration of the function. it takes one parameter name
//if more parameters required, comma is used to separate
//them
public function hello($name )
{
//define response
$result = ‘Hello, ‘.$name;
//return response to a caller
return $result; }
}

$helloService = new phpService(
‘helloService’,
‘takes name and returns Hello, Name’,
array(‘uri’ => ‘http://designstudio1/hello’, ‘encoding’ => SOAP_ENCODED,’soap_version’ => SOAP_1_2)
);
$helloService->handle();

?>

Code explanation:
These lines are not comments
/**
* Returns “Hello, Name”
*
* @param string
* @return string
*/
They are very important for your web service.
• * Returns – provides description of the service
• * @param string – tells that there is only one parameter of type string. Other types are int, float, etc. If service has several parameters, they have to be listed on separate lines – one parameter per line.
• * return string – tells that there is one return parameter of type string

Open file in browser, it should look similar to the following screenshot

When you click on Service description link on that page, you will receive WSDL

You can use the same client helloClient.php to consume the modified service.
This is another important feature of web services. If number, type of parameters and type of return value were not modified, then client does not need to know that service was modified.

Now we will modify both client and server to accept first and last name.
Create file helloService2.php file. I highlighted changes
<?php
//include Services_Webservice extension
include_once(‘Services/Webservice.php’);

//define class
class phpService extends Services_Webservice
{
/**
* Returns “Hello, FirstName LastName!”
*
* @param string
* @param string
* @return string
*/
//declaration of the function. it takes one parameter name
//if more parameters required, comma is used to separate
//them
public function hello($fname, $lname )
{
//define response
$result = ‘Hello, ‘ . $fname . ‘ ‘ . $lname . ‘!’;
//return response to a caller
return $result; }
}

$helloService = new phpService(
‘helloService’,
‘takes name and returns Hello, FirstName LastName!’,
array(‘uri’ => ‘http://designstudio1/hello2’, ‘encoding’ => SOAP_ENCODED,’soap_version’ => SOAP_1_2)
);
$helloService->handle();

?>
Create file helloclient2.php file. I highlighted changes
<?php
$fname = $_POST[“fname”];
$lname = $_POST[“lname”];
//specify location and uri of web service
$client = new SoapClient(null, array(‘location’ =>
“http://localhost/m12/helloService2.php”,
‘uri’ => “http://designstudio1/hello2”));

//make a SOAP call to web service specifying
//operation and name and value for parameters
$result = $client->__soapCall(‘hello’,
array(‘fname’ => $fname, ‘lname’=>$lname));
echo $result;
?>
We also have to create a form that will take user’s first and last names. Action of the form should be helloclient2.php.
The result:
Lab 12
Before you start the lab, you have to run and understand all code form this module.
Note: Do not forget to add error handling: aa*3 is not equal to 0.
1. (4 points) Create Restful service that will multiply two numbers.
2. (6 points) Use helloclient2.php and helloService2.php to create multiply_client.php and multiply_service.php to Create SOAP service that will multiply two numbers. You will need to add an html form that will collect user input.
What to submit:
ONE .doc or .docx with
o Source code and screenshots of at least three test cases for #1.
o Source code of the form, client and service files and screenshots of at least three test cases for #2.
ONE .zip file that contains files you created for lab 12.

Place Similar Order Now!

  • Our Support Staff are online 24/7
  • Our Writers are available 24/7
  • Most Urgent order is delivered with 6 Hrs
  • 100% Original Assignment Plagiarism report can be sent to you upon request.
[order_calculator]