Web services

“A web service is a software system designed to support interoperable machine-to-machine interaction over a network. It has an interface described in a machine-processable format “ (W3C, Web Services Glossary )

Web services are modular components that are made for various applications to interact with each other. They are typically made for reusability because many applications will connect to them. Typically web service messages are transferred in XML and the results are translated at the requesting application.

It is easier to understand the process of web services in diagrams.

Components of web services

La descrizione sotto è più legata a SOAP (la prima implementazione dei web service)

There are many different types of web services, but this course will focus on the components of SOAP messaging.

WSDL

Before an application can utilize a web service it must know a little bit about the web service. This is where the WSDL (Web Service Description Language) comes in. The WSDL lets the application know how to interface with the web service. The WSDL is written in XML and uses the following elements.

  • Types -- a container for data type definitions using some type system (such as XSD).

  • Message -- an abstract, typed definition of the data being communicated.

  • Operation -- an abstract description of an action supported by the service.

  • Port Type -- 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.

Here is an example of a WSDL for a stock quote web service. The following example shows the WSDL definition of a simple service providing stock quotes. The service supports a single operation called GetLastTradePrice, which is deployed using the SOAP protocol over HTTP. The request takes a ticker symbol of type string, and returns the price as a float.

<?xml version="1.0"?>
<definitions name="StockQuote"
	targetNamespace="http://example.com/stockquote.wsdl"
          xmlns:tns="http://example.com/stockquote.wsdl"
          xmlns:xsd1="http://example.com/stockquote.xsd"
          xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
          xmlns="http://schemas.xmlsoap.org/wsdl/">

    <types>
       <schema targetNamespace="http://example.com/stockquote.xsd"
              xmlns="http://www.w3.org/2000/10/XMLSchema">
           <element name="TradePriceRequest">
              <complexType>
                  <all>
                      <element name="tickerSymbol" type="string"/>
                  </all>
              </complexType>
           </element>
           <element name="TradePrice">
              <complexType>
                  <all>
                      <element name="price" type="float"/>
                  </all>
              </complexType>
           </element>
       </schema>
    </types>

    <message name="GetLastTradePriceInput">
        <part name="body" element="xsd1:TradePriceRequest"/>
    </message>

    <message name="GetLastTradePriceOutput">
        <part name="body" element="xsd1:TradePrice"/>
    </message>

    <portType name="StockQuotePortType">
        <operation name="GetLastTradePrice">
           <input message="tns:GetLastTradePriceInput"/>
           <output message="tns:GetLastTradePriceOutput"/>
        </operation>
    </portType>

    <binding name="StockQuoteSoapBinding" type="tns:StockQuotePortType">
        <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
        <operation name="GetLastTradePrice">
           <soap:operation soapAction="http://example.com/GetLastTradePrice"/>
           <input>
               <soap:body use="literal"/>
           </input>
           <output>
               <soap:body use="literal"/>
           </output>
        </operation>
    </binding>

    <service name="StockQuoteService">
        <documentation>My first service</documentation>
        <port name="StockQuotePort" binding="tns:StockQuoteBinding">
           <soap:address location="http://example.com/stockquote"/>
        </port>
    </service>

</definitions>

Il WSDL, un documento in formato XML, descrive i metodi con i parametri di chiamata e l'oggetto di ritorno, che il web service espone.

Per avere un'idea il link alle specifiche su WSDL:

SOAP Message

Once an application knows how to utilize a web service, it can use SOAP to actually interact with the web service. SOAP, Simple Object Access Protocol, is a messaging protocol used to invoke remote web services. SOAP is normally sent through the HTTP protocol using a SOAP envelope, which contains a SOAP header and a SOAP message.

When the SOAP message is recieved by the web service, the web service is run and the response is sent back to the requesting application via a SOAP message. Again, these messages are sent using the HTTP protocol, so they are similiar to web requests.

Sotto l'esempio di messaggi SOAP per il servizio Stock Quote il cui WSDL è stato visto sopra.

La request, con header HTTP e SOAP Message nel body:

POST /StockQuote HTTP/1.1
Host: www.stockquoteserver.com
Content-Type: text/xml;
charset="utf-8"
Content-Length: nnnn
SOAPAction: "Some-URI"

<SOAP-ENV:Envelope
 xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" 
 SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> 
   <SOAP-ENV:Body>
    <m:GetLastTradePrice
     xmlns:m="Some-URI">
      <symbol>MOT</symbol>
    </m:GetLastTradePrice>     
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

This request is asking the web service for the last trading price of the stock MOT.

La response del web server, con header HTTP e SOAP Message nel body:

HTTP/1.1 200 OK Content-Type: text/xml; charset="utf-8"
Content-Length: nnnn

<SOAP-ENV:Envelope
 xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
 SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>   
 <SOAP-ENV:Body>
  <m:GetLastTradePriceResponse
   xmlns:m="Some-URI">
   <Price>14.5</Price>
  </m:GetLastTradePriceResponse>
 </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

The web service returned the price of $14.50 for the stock MOT. The application can now use the value.

Why use web services?

There are many benefits to using web services for serving business logic to many applications at the same time.

  • Promotes interoperability by minimizing the requirements for shared understanding

    • There is a standard way of utilizing web services.

  • Enables just-in-time integration

    • Web services do not need to be known until they are required by the application. All of the information is received in the WSDL.

  • Reduces complexity by encapsulation

    • All of the business logic is encapsulated by the XML through the WSDL and SOAP messages.

  • Enables interoperability of legacy applications

    • Applications can utilize the business logic through just a simple HTTP request. New applications can be created through the legacy business logic that can utilize the legacy business logic.

In alternativa ai web services ci sono le Remote Procedure Call (chiamate di procedura remote), e abbreviato in RPC, che aumentano però il coupling (accoppiamento) tra client e server e necessitano di aprire porte della rete oltre quelle standard (mentre i web services sono esposti su porta 80 il che generalmente non pone problemi).

E' l'approccio più strutturato alla comunicazione.

Remote procedure calls (RPC) extend the well-known procedure calling mechanism, and allow one process to call a procedure from another process, possibly on a different machine. This idea has become even more popular with the advent of object-oriented programming, and has even been incorporated in programming languages. An example is Java’s remote method invocation (RMI). However, the idea can be implemented even if the program is not written in a language with explicit support.

The implementation is based on stubs — crippled procedures that represent a remote procedure by having the same interface. The calling process is linked with a stub that has the same interface as the called procedure. However, this stub does not implement this procedure. Instead, it sends the arguments over to the stub linked with the other process, and waits for a reply.

The other stub mimics the caller, and calls the desired procedure locally with the specified arguments. When the procedure returns, the return values are shipped back and handed over to the calling process. RPC is a natural extension of the procedure call interface, and has the advantage of allowing the programmer to concentrate on the logical structure of the program, while disregarding communication issues. The stub functions are typically provided by a library, which hides the actual implementation. For example, consider an ATM used to dispense cash at a mall. When a user requests cash, the business logic implies calling a function that verifies that the account balance is sufficient and then updates it according to the withdrawal amount. But such a function can only run on the bank’s central computer, which has direct access to the database that contains the relevant account data. Using RPC, the ATM software can be written as if it also ran directly on the bank’s central computer. The technical issues involved in actually doing the required communication are encapsulated in the stub functions.

TIPI DI WEB SERVICES: SOAP e REST

Ci sono differenti standard e architetture per implementare un'architettura a web service, principalmente Simple Object Access Protocol (SOAP) e Representional State Transfer (REST).

Vediamo le differenze analizzandoli e dicendo subito che SOAP è una vera e propria specifica che descrive come devono essere i messaggi, mentre REST è più uno stile architetturale.

Le specifiche di SOAP (SOAP Specifications) sono mantenute e sviluppate dal World Wide Web Consortion (W3C).

L' architettura REST deve rispondere a delle linee guida se si vuole fornire web services di tipo RESTful, ad esempio che le richieste siano stateless e l'utilizzo dei codici di stato dell' HTTP nelle risposte.

SOAP - Simple Object Access Protocol

Simple Object Access Protocol (SOAP) on the other hand is a protocol for data exchange. It’s strengths lie in that it has a certain set of rules and standards that must be obeyed for successful client / server interactions. SOAP requests are delivered via envelopes that must contain all the required information to process the request.

A SOAP request envelope generally consists of an optional header and a required body attribute. The header attribute is used for information such as security credentials and other metadata while the body attribute is used to handle the actual data and any errors that arise. This is a simplification of how SOAP handles data exchange so for more in-depth information check out the W3C Specification.

Pros:

  • WSDL – the Web Services Description Language (WSDL) describes the web service methods, access and other parameters making it a one-stop shop for learning how to consume the API.

  • Extensibility – WS-* extensions such as WS-Security, WS-Addressing, WS-Federation and others can greatly enhance the capabilities of the application.

  • Protocol Neutral – accessible via HTTP, SMTP, TCP and other application level protocols.

Cons:

  • XML Infoset – SOAP uses XML for transferring payload data which can take significantly longer to serialize which leads to performance issues.

  • Complex Syntax – SOAP works exclusively with XML and reading the data envelopes can be difficult and time-consuming.

ESEMPIO DI SOAP WEB SERVICE

Esempio dato il seguente servizio di conversione delle temperature descritto da seguente WSDL https://apps.learnwebservices.com/services/tempconverter?wsdl

Facendo una request POST HTTP di questo XML al web service: https://apps.learnwebservices.com/services/tempconverter

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://learnwebservices.com/services/tempconverter">
   <soapenv:Header/>
   <soapenv:Body>
      <tem:CelsiusToFahrenheitRequest>
         <tem:TemperatureInCelsius>18</tem:TemperatureInCelsius>
      </tem:CelsiusToFahrenheitRequest>
   </soapenv:Body>
</soapenv:Envelope>

otteniamo dal web service la risposta con il valore della temperatura convertita da celsius in fahrenheit:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <CelsiusToFahrenheitResponse xmlns="http://learnwebservices.com/services/tempconverter">
         <TemperatureInFahrenheit>64.4</TemperatureInFahrenheit>
      </CelsiusToFahrenheitResponse>
   </soap:Body>
</soap:Envelope>

REST - Representional State Transfer

RESTful API’s have gained massive popularity due to their interoperability and flexibility on the web. Web services built with this architecture can evolve independently of the applications that consume them. REST based API’s do not have a well defined security protocol – but JSON Web Tokens (JWTs) are the most common method of authenticating and authorizing requests.

Pros:

  • Stateless – each call to the web service has all the information it needs to process the request and does not rely on storing client-server context.

  • Flexible – RESTful API’s can accept and serve data in many different formats including JSON, XML, Atom and others. JSON is by far the most popular data format used in REST based API’s.

  • Cacheable – responses are cacheable which can greatly improve the performance of the web service by eliminating unnecessary calls to the backend.

Cons:

  • Standards – there is no defined standard for building REST based API’s. There are many great resources and guides such as the White House RESTful API Standards and the REST API Tutorial, but many permutations of REST based API’s exist.

  • HTTP – RESTful applications are confined to the HTTP protocol.

SOAP vs REST

Confronto tra tecnologie

Last updated