Web Services Workshop

Chris Williamson

Wolfram Research

What are Web Services?

Programmatic interfaces made available on the network which are used for application to application communication.

What are Web Services?

Programmatic interfaces made available on the network which are used for application to application communication.

Language and Platform independent

What are Web Services?

Programmatic interfaces made available on the network which are used for application to application communication.

Language and Platform independent

Generally invoked similar to how any other Mathematica functions.

What are Web Services?

Programmatic interfaces made available on the network which are used for application to application communication.

Language and Platform independent

Generally invoked similar to how any other Mathematica functions.

Useful for calling remote functionality.

What are web services?

Programmatic interfaces made available on the network which are used for application to application communication.

Language and Platform independent

Generally invoked similar to how any other Mathematica functions.

Useful for calling remote functionality.

Useful for querying data from a remote machine.

How do web services work?

Send XML messages over HTTP to the server.

How do web services work?

Send XML messages over HTTP to the server.

Use SOAP to encode and process the messages.

How do web services work?

Send XML messages over HTTP to the server.

Use SOAP to encode and process the messages.

Use WSDL to discover and bind to the interface for the web service.

Load the Package

The package needs to be loaded before we can use WebServices.

<< WebServices`

Install a web service

A web service can be installed by pointing InstallService to a WSDL file.  This function returns a list of functions.

InstallService["http://www.xmethods.net/sd/2001/TemperatureService.\
wsdl"]

Simple Example

If content is provided by the web service, the usage message for a function describes the purpose of the web service.  It also provides a link to the OperationPalette.  The OperationPalette can be used to inspect the function.  It can retrieve parameters and datatypes used with the function.

?getTemp

Simple Example (con't)

The function may be invoked using the parameters described by the OperationPalette.  Online documentation may also be very useful for determining how a web service works.

getTemp["61821"]

Working with compound types

Compound data types are structures of data that make up combinations of simple data types (strings, integers, reals, etc.)

Working with compound types

Compound data types are structures of data that make up combinations of simple data types (strings, integers, reals, etc.)

Most useful web services use compound data types.

Working with compound types

Compound data types are structures of data that make up combinations of simple data types (strings, integers, reals, etc.)

Most useful web services use compound data types.

Compound data types use a rule syntax.

Compound Example

InstallService can be used to install the service.  Once it is installed we can look at the usage message and OperationPalette.  The OperationPalette lets you explore the compound types and paste a template of compound types into a notebook.

InstallService["http://soap.amazon.com/schemas3/AmazonWebServices.\
wsdl"]

?AuthorSearchRequest

Compound Example (con't)

The values of the compound datatypes can be input using a rule form.  One compound datatype in rule form is essentially a list of rules specifying names and values.  Values may consist of simple datatypes or compound datatypes.  One thing to note is the more complex a web service, the more online documentation will help you.  Most of these values were helped along using online documentation.

\(results\  = \ 
      AuthorSearchRequest[{
"author" -> "Stephen Wolfram", 
"page" -> 
            1, 
"mode" -> "books", 
"tag" -> "webservices-20", 
"type" -> "lite", 
"devtag" -> "D3VZJS46JD5U9D", 
"version" -> "1.0"
}]\)

Compound Example (con't)

Of course once data is in Mathematica, Mathematica functions can be used to transform and display the data.

ListPlot[
      Sort[ToExpression[StringDrop[#,  1]]  &  /@  
          Cases[results,  
            Rule["ListPrice", listPrice_String] :> 
              listPrice,  Infinity]],  PlotJoined -> True]

Compound Example (con't)

Even with web service functions being easy to use, it is normally best to build an interface to the web service.  This can simplify the interface and make it more intuitive to the user.  It also allows the developer of the interface to make the functionality more complete and nicer to look at.  The Amazon example demonstrates this possibility.

Message Example

Web services come in many flavors.  Efforts are being made to standardize web services across all platforms.  However, it is not the case that all the flavors of the XML messages sent and received while using SOAP are as expected.  To help with this there is a message interface to the Web Services Package.  ToServiceRequest can be used to build a request message in symbolic XML using the functions and parameters installed with a InstallService call.

\(\(InstallService["http://www.xignite.com/xHistorical.asmx?WSDL"];\)\)
\(msg\  = \ 
      ToServiceRequest[
        GetHistoricalQuotesRange, "MSFT", \ "Symbol", \ \ "01/01/2004", \ "10/19/2004", {"Username" -> "chrisw@wolfram.com"}]\)

Message Example (con't)

This message can be used as a starting point for customizing the request.  The request can also be built from scratch.  However, once the message is customized, it may be sent to the server using InvokeServiceOperation.  The response message will be returned as symbolic XML.

response  = 
      InvokeServiceOperation[GetHistoricalQuotesRange, msg]

Message Example (con't)

FromServiceResponse can be used to process the response message and convert it into Mathematica expressions.  However, this example demonstrates why we need this message interface and hence does not work with FromServiceResponse.  If it did work with FromServiceResponse, a user could just call the function without needing to interface with the messages.

FromServiceResponse[response]

Message Example (con't)

Mathematica contains powerful XML tools that can be used to process the response message.

\(ListPlot[
Cases[response, \ 
        XMLElement[{_String, \ "LastClose"}, \ {}, \ {val_String}] :> ToExpression[val], \ Infinity], \ 
      PlotJoined -> True]\)

Working with binary data

Web Services Package supports binary data, so users can use binary data such as imagery as well as textual data.

\(\(InstallService["http://terraservice.net/TerraService.asmx?WSDL"];\)\)
place  =  
        GetPlaceList["Washington Monument",  1,  
          True];
tileMeta  =  
        GetTileMetaFromLonLatPt[
          Flatten["Center" /.  
              place],  "Photo",  "Scale1m"];
tile  =  
        GetTile["Id"  /. tileMeta];
Show[ImportString[tile, "JPEG"]]

Working with Mathematica expressions

Web Services Package supports Mathematica expressions, so users can use web services that support expressions.

InstallService["http://webservices.wolfram.com/services/Integrator/\
Integrate.m?wsdl"];
IntegrateExpression[Sin[x^2]]

Working with MathML

Web Services Package supports MathML, so users can use web services that support MathML.

InstallService["http://webservices.wolfram.com/services/\
Integrator/Integrate.m?wsdl"];
mathml = IntegrateMathML[XML`MathML`ExpressionToSymbolicMathML[Sin[x]]]

XML`MathML`SymbolicMathMLToExpression[mathml]

Web Services Package examples

There are many web services out there for users to choose from.  Here are a few of the larger companies that produce useful web services.  Xmethods.com has a very nice list of the web services published by various organizations.

Google

Amazon

Ebay

Terra Service

Providing a web service using webMathematica

webMathematica traditionally is a great way to provide mathematical content to a web browser, but with web services you can provide content to many more clients.

Providing a web service using webMathematica

A webMathematica web service is basically a Mathematica package containing a bit of extra meta-data.

BeginPackage["Test`", {"MSPWebServices`"}];

AddNumbers::usage = "Adds two numbers together.";
ServiceReturn[AddNumbers] = _Real;

PointsPlot::usage = "Plots some points and returns the graph.";
ServiceReturn[PointsPlot] = _base64Binary;

Pt::usage = "Defines a point.";
ServiceTypeDefinition[Pt] = {lat_Real, lon_Real};

Begin["`Private`"];

AddNumbers[p_Real, p2_Integer] := p + p2;

PointsPlot[ points : {___Pt}] :=
    Module[{p},
      p = {#[[1]], #[[2]]} & /@ points;
      image = ListPlot[p, PlotJoined->True];
      base64Binary[ExportString[image, "GIF"]]
      ];

End[];
EndPackage[];

"Test`"

webMathematica example

This example provides a function that calculates the monthly payment of a loan.

BeginPackage["Loan`", {"MSPWebServices`"}];

CalculateMonthlyPayment::usage = 
"Calculates the monthly payment of a loan given the principal, period in years, 
 and rate as a percent.";
ServiceReturn[CalculateMonthlyPayment] = _Real;

Begin["`Private`"];

CalculateMonthlyPayment[principal_Real, period_Integer, rate_Real] := 
  Module[{funct}, 
    (funct[x_]:=
      (1 + (.01 * rate)/12) * x - payment;
       Flatten[Solve[Nest[funct, principal, Rationalize[(12 * period)]]==0, 
         payment]])[[1,2]]//SetPrecision[#,4]&]

End[];
EndPackage[];

"Loan`"

webMathematica example (con't)

The web service published by webMathematica generates a WSDL file that may be used by clients.

InstallService["http://mathworld-webm:8080/MWS/Loan.m?wsdl"]

webMathematica example (con't)

Just as with previous examples a user can discover how the web service works by looking at the usage message.

?CalculateMonthlyPayment

webMathematica example (con't)

Once a user figures out how the web service works, it may be invoked.

CalculateMonthlyPayment[10000. ,  5,  8. ]

webservices.wolfram.com

Web services provided by Wolfram Research will be located at http://webservices.wolfram.com.  Documentation, clients, and examples will be available for use with the web services.

webservices.wolfram.com

There are currently two web services available and webservices.wolfram.com.

wolfram.com search (Version 2 on the way)

The Integrator

More to come!

webservices.wolfram.com (con't)

These services can be used in many different clients from Mathematica to Java to web pages.

Conclusion

Questions.

My email is chrisw@wolfram.com.