Web services
Last updated
Last updated
“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.
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.
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.
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:
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:
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:
The web service returned the price of $14.50 for the stock MOT. The application can now use the value.
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.
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.
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 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
otteniamo dal web service la risposta con il valore della temperatura convertita da celsius in fahrenheit:
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.
Confronto tra tecnologie
SOAP
REST
Meaning
Simple Object Access Protocol
Representational State Transfer
Design
Standardized protocol with pre-defined rules to follow.
Architectural style with loose guidelines and recommendations.
Approach
Function-driven (data available as services, e.g.: “getUser”)
Data-driven (data available as resources, e.g. “user”).
Statefulness
Stateless by default, but it’s possible to make a SOAP API stateful.
Stateless (no server-side sessions).
Caching
API calls cannot be cached.
API calls can be cached.
Security
WS-Security with SSL support. Built-in ACID compliance.
Supports HTTPS and SSL.
Performance
Requires more bandwidth and computing power.
Requires fewer resources.
Message format
Only XML.
Plain text, HTML, XML, JSON, YAML, and others.
Transfer protocol(s)
HTTP, SMTP, UDP, and others.
Only HTTP
Recommended for
Enterprise apps, high-security apps, distributed environment, financial services, payment gateways, telecommunication services.
Public APIs for web services, mobile services, social networks.
Advantages
High security, standardized, extensibility.
Scalability, better performance, browser-friendliness, flexibility.
Disadvantages
Poorer performance, more complexity, less flexibility.
Less security, not suitable for distributed environments.