0% found this document useful (0 votes)
22 views19 pages

Chapter Two Architecture of Web Services

Chapter Two discusses the architecture of web services, focusing on two main types: SOAP and RESTful web services. SOAP is a protocol that uses XML for message formatting and requires a strict structure, while REST is an architectural style that allows for more flexibility in data formats and operations. The chapter also outlines the roles, operations, and lifecycle of web services, as well as the components of REST API architecture.

Uploaded by

Teddy yemu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views19 pages

Chapter Two Architecture of Web Services

Chapter Two discusses the architecture of web services, focusing on two main types: SOAP and RESTful web services. SOAP is a protocol that uses XML for message formatting and requires a strict structure, while REST is an architectural style that allows for more flexibility in data formats and operations. The chapter also outlines the roles, operations, and lifecycle of web services, as well as the components of REST API architecture.

Uploaded by

Teddy yemu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Chapter Two: Architecture of Web Services

Types of Web Services


There are two types of web services:

o SOAP Web Services


o RESTful Web Servies

SOAP Web Services

REST defines an architectural approach whereas SOAP poses a restriction on the format of the XML.
XML transfer data between the service provider and service consumer. Remember that SOAP and
REST are not comparable.

SOAP: SOAP acronym for Simple Object Access Protocol. It defines the standard XML format. It
also defines the way of building web services. We use Web Service Definition Language (WSDL) to
define the format of request XML and the response XML.

For example, we have requested to access the Todo application from the Facebook application. The
Facebook application sends an XML request to the Todo application. Todo application processes the
request and generates the XML response and sends back to the Facebook application.

If we are using SOAP web services, we have to use the structure of SOAP.
In the above figure, the SOAP-Envelope contains a SOAP-Header and SOAP-Body. It contains
meta-information needed to identify the request, for example, authentication, authorization, signature,
etc. SOAP-Header is optional. The SOAP-Body contains the real XML content of request or response.
In case of an error, the response server responds back with SOAP-Fault.

Let's understand the SOAP XML request and response structure.

XML Request

<Envelop xmlns=?http://schemas.xmlsoap.org/soap/envelop/?>
<Body>
<getCourseDetailRequest xmlns=?http://udemy.com/course?>
<id>course1</id>
<getCourseDetailRequest>
</Body>
</Envelop>

XML Response

<SOAP-ENV:Envelope xmlns:SOAP-ENV=?http://schemas.xmlsoap.org/soap/envelope/?>
<SOAP-ENV:Header /> <!?empty header-->
<SOAP-ENV:Body> <!?body begin-->
<ns2:getCourseDetailsResponse xmlns:ns2=?http://in28mi> <!--content of the response-->
<ns2:course>
<ns2:id>Course1</ns2:id>
<ns2:name>Spring<ns2:name>
<ns2:description>10 Steps</ns1:description>
</ns2:course>
</ns2:getCourseDetailResponse>
</SOAP-ENV:Body> <!?body end-->
</SOAP-ENV:Envelope>

Points to remember

o SOAP defines the format of request and response.


o SOAP does not pose any restriction on transport. We can either use HTTP or MQ for communication.
o In SOAP, service definition typically done using Web Service Definition Language (WSDL). WSDL
defines Endpoint, All Operations, Request Structure, and Response Structure.

The Endpoint is the connection point where HTML or ASP pages are exposed. It provides the
information needed to address the Web Service endpoint. The operations are the services that are
allowed to access. Request structure defines the structure of the request, and the response structure
defines the structure of the response.

SOAP web service architecture

The Web Services architecture describes how to instantiate the elements and implement the operations
in an interoperable manner.

The architecture of web service interacts among three roles: service provider, service
requester, and service registry. The interaction involves the three operations: publish,
find, and bind. These operations and roles act upon the web services artifacts. The web service
artifacts are the web service software module and its description.

The service provider hosts a network-associable module (web service). It defines a service description
for the web service and publishes it to a service requestor or service registry. These service requestor
uses a find operation to retrieve the service description locally or from the service registry. It uses the
service description to bind with the service provider and invoke with the web service implementation.

The following figure illustrates the operations, roles, and their interaction.
Roles in a Web Service Architecture

There are three roles in web service architecture:

o Service Provider
o Service Requestor
o Service Registry

Service Provider

From an architectural perspective, it is the platform that hosts the services.

Service Requestor

Service requestor is the application that is looking for and invoking or initiating an interaction with a
service. The browser plays the requester role, driven by a consumer or a program without a user
interface.

Service Registry

Service requestors find service and obtain binding information for services during development.

Operations in a Web Service Architecture

Three behaviors that take place in the microservices:

o Publication of service descriptions (Publish)


o Finding of services descriptions (Find)
o Invoking of service based on service descriptions (Bind)

Publish: In the publish operation, a service description must be published so that a service requester
can find the service.

Find: In the find operation, the service requestor retrieves the service description directly. It can be
involved in two different lifecycle phases for the service requestor:

o At design, time to retrieve the service's interface description for program development.
o And, at the runtime to retrieve the service's binding and location description for invocation.

Bind: In the bind operation, the service requestor invokes or initiates an interaction with the service at
runtime using the binding details in the service description to locate, contact, and invoke the service.

Artifacts of the web service

There are two artifacts of web services:

o Service
o Service Registry

Service: A service is an interface described by a service description. The service description is the
implementation of the service. A service is a software module deployed on network-accessible
platforms provided by the service provider. It interacts with a service requestor. Sometimes it also
functions as a requestor, using other Web Services in its implementation.

Service Description: The service description comprises the details of


the interface and implementation of the service. It includes its data types, operations, binding
information, and network location. It can also categorize other metadata to enable discovery and
utilize by service requestors. It can be published to a service requestor or a service registry.

Web Service Implementation Lifecycle

A web service implementation lifecycle refers to the phases for developing web services from the
requirement to development. An Implementation lifecycle includes the following phases:

o Requirements Phase
o Analysis Phase
o Design Phase
o Coding Phase
o Test Phase
o Deployment Phase

Requirements Phase

The objective of the requirements phase is to understand the business requirement and translate them
into the web services requirement. The requirement analyst should do requirement elicitation (it is the
practice of researching and discovering the requirements of the system from the user, customer, and
other stakeholders). The analyst should interpret, consolidate, and communicate these requirements to
the development team. The requirements should be grouped in a centralized repository where they can
be viewed, prioritized, and mined for interactive features.

Analysis Phase

The purpose of the analysis phase is to refine and translate the web service into conceptual models by
which the technical development team can understand. It also defines the high-level structure and
identifies the web service interface contracts.

Design Phase

In this phase, the detailed design of web services is done. The designers define web service interface
contract that has been identified in the analysis phase. The defined web service interface contract
identifies the elements and the corresponding data types as well as mode of interaction between web
services and client.
Coding Phase

Coding and debugging phase is quite similar to other software component-based coding and
debugging phase. The main difference lies in the creation of additional web service interface wrappers,
generation of WSDL, and client stubs.

Test Phase

In this phase, the tester performs interoperability testing between the platform and the client's program.
Testing to be conducted is to ensure that web services can bear the maximum load and stress. Other
tasks like profiling of the web service application and inspection of the SOAP message should also
perform in the test phase.

Deployment Phase

The purpose of the deployment phase is to ensure that the web service is properly deployed in the
distributed system. It executes after the testing phase. The primary task of deployer is to ensure that
the web service has been properly configured and managed. Other optional tasks like specifying and
registering the web service with a UDDI registry also done in this phase.

Web Service Stack or Web Service Protocol Stack

To perform three operations: publish, find, and bind in an interoperable manner, there must be a web
service stack. The web service stack embraces the standard at each level.

In the above figure, the top most layers build upon the capabilities provided by the lower layers. The
three vertical towers represent the requirements that are applied at every level of the stack. The text on
the right represents technologies that apply at that layer of the stack. A web service protocol stack
typically stacks four protocols:

o Transport Protocol
o Messaging Protocol
o Description Protocol
o Discovery Protocol

(Service) Transport Protocol: The network layer is the foundation of the web service stack. It is
responsible for transporting a message between network applications. HTTP is the network protocol
for internet available web services. It also supports other network protocol such as SMTP,
FTP, and BEEP (Block Extensible Exchange Protocol).

(XML) Messaging Protocol: It is responsible for encoding message in a common XML format so that
they can understand at either end of a network connection. SOAP is the chosen XML messaging
protocol because it supports three operations: publish, find, and bind operation.

(Service) Description Protocol: It is used for describing the public interface to a specific web service.
WSDL is the standard for XML-based service description. WSDL describes the interface and
mechanics of service interaction. The description is necessary to specify the business context, quality
of service, and service-to-service relationship.

(Service) Discovery Protocol: It is a centralized service into a common registry so that network Web
services can publish their location and description. It makes it easy to discover which services are
available on the network.

The first three layers of the stack are required to provide or use any web service. The simplest stack
consists of HTTP for the network layer, SOAP protocol for the XML-based messaging, and WSDL for
the service description layer. These three-layer provides interoperability and enables web service to
control the existing internet infrastructure. It creates a low cost of entry to a global environment.

The bottom three layers of the stack identify technologies for compliance and interoperability, the next
two layer- Service Publication and Service Discovery can be implemented with a range of solutions.

RESTful Web Services

REST stands for REpresentational State Transfer. It is developed by Roy Thomas Fielding who
also developed HTTP. The main goal of RESTful web services is to make web services more
effective. RESTful web services try to define services using the different concepts that are already
present in HTTP. REST is an architectural approach, not a protocol.

It does not define the standard message exchange format. We can build REST services with both XML
and JSON. JSON is more popular format with REST. The key abstraction is a resource in REST. A
resource can be anything. It can be accessed through a Uniform Resource Identifier (URI). For
example:
The resource has representations like XML, HTML, and JSON. The current state is captured by
representational resource. When we request a resource, we provide the representation of the resource.
The important methods of HTTP are:

o GET: It reads a resource.


o PUT: It updates an existing resource.
o POST: It creates a new resource.
o DELETE: It deletes the resource.

For example, if we want to perform the following actions in the social media application, we get the
corresponding results.

POST /users: It creates a user.

GET /users/{id}: It retrieve the detail of one user.

GET /users: It retrieve the detail of all users.

DELETE /users: It delete all users.

DELETE /users/{id}: It delete a user.

GET /users/{id}/posts/post_id: It retrieve the detail of a specific post.

POST / users/{id}/ posts: It creates a post for a user.

GET /users/{id}/post: Retrieve all posts for a user

HTTP also defines the following standard status code:

o 404: RESOURCE NOT FOUND


o 200: SUCCESS
o 201: CREATED
o 401: UNAUTHORIZED
o 500: SERVER ERROR

RESTful Service Constraints


o There must be a service producer and service consumer.
o The service is stateless.
o The service result must be cacheable.
o The interface is uniform and exposing resources.
o The service should assume a layered architecture.

Advantages of RESTful web services


o RESTful web services are platform-independent.
o It can be written in any programming language and can be executed on any platform.
o It provides different data format like JSON, text, HTML, and XML.
o It is fast in comparison to SOAP because there is no strict specification like SOAP.
o These are reusable.

These are language neutral.

Example :
Here is an example of a simple RESTful service that allows a client to create, read, update, and
delete (CRUD) a resource :
Javascript

// GET /resource/123

// Returns the state of the resource with ID 123

app.get('/resource/:id', function(req, res) {

var id = req.params.id;

var resource = findResourceById(id);

res.json(resource);

});
// POST /resource

// Creates a new resource with the state specified in the request body

app.post('/resource', function(req, res) {

var resource = req.body;

var id = createResource(resource);

res.json({ id: id });

});

// PUT /resource/123

// Updates the state of the resource with ID 123 with the state specified in the request body

app.put('/resource/:id', function(req, res) {

var id = req.params.id;

var resource = req.body;

updateResource(id, resource);

res.sendStatus(200);

});

// DELETE /resource/123

// Deletes the resource with ID 123

app.delete('/resource/:id', function(req, res) {


var id = req.params.id;

deleteResource(id);

res.sendStatus(200);

});

In this example, the service uses the GET, POST, PUT, and DELETE HTTP methods to implement
the CRUD operations on a resource. The service uses the app.get(), app.post(), app.put(), and
app.delete() methods to register the appropriate handler functions for each operation. The req and res
objects represent the request and response, respectively, and are used to access information about the
request and send a response to the client.

Rest API Architecture


REST API architecture refers to the design and structure of a web service that follows the principles of

REST (Representational State Transfer). Here’s an overview of the components and considerations

involved in REST API architecture


1. REST Key Components
 Resources: Key entities exposed by the API, each identified by a unique URI.

 HTTP Methods: Used to perform CRUD operations on resources (GET, POST, PUT, DELETE).

 Representations: Data format representing resource state (e.g., JSON, XML).

 Hypermedia Links: Embedded links in responses to enable dynamic navigation.

 Status Codes: Indicate the status of a request (e.g., 200 OK, 404 Not Found).

2. Uniform Interface

2.1. Identification of Resources:


 Resources are uniquely identified by URIs.

 Example: /api/users, /api/products

2.2. Manipulation of Resources through Representations:

 Resources have uniform representations in server responses.

 Example

// GET /api/users/1
{
"id": 1,
"name": "John Doe",
"email": "[email protected]"
}

2.3. Self-Descriptive Messages:

 Resource representations carry information to describe processing.

 Example:
// GET /api/users/1
{
"id": 1,
"name": "John Doe",
"links": [
{ "rel": "self", "href": "/api/users/1" },
{ "rel": "orders", "href": "/api/users/1/orders" }
]
}

2.4. Hypermedia as the Engine of Application State (HATEOAS):

 Clients navigate resources and interactions using hyperlinks.

 Example:

{
"id": 1,
"title": "RESTful API Design",
"content": "Best practices for designing RESTful APIs...",
"author": {
"id": 123,
"name": "John Doe",
"links": [
{ "rel": "self", "href": "/api/authors/123" },
{ "rel": "posts", "href": "/api/authors/123/posts" }
]
}
}

Explanation:
 The blog post resource includes hypermedia links to related resources:

 "author": Links to the author resource, allowing clients to retrieve author details or posts written by
the author.
 "comments": Links to the comments resource for the specific post, enabling clients to retrieve

comments associated with the post.

 Each hyperlink includes a rel attribute indicating the relationship type and a href attribute providing

the URI of the related resource.

 Clients can navigate the API dynamically by following these hyperlinks, discovering and accessing

related resources as needed.


3. Client-Server Architecture:
 Separation of concerns between client and server components.

 Clients request resources, and servers provide responses.

 Promotes scalability and independent evolution of client and server.

Example: Consider a scenario where a client-side web application communicates with a server-side

REST API to retrieve and manipulate user data.

 Client-side: A web application built using HTML, CSS, and JavaScript running in a user’s web

browser.

 Server-side: A backend server implemented using a framework like Express.js or Django, exposing

RESTful endpoints to handle client requests.


4. Statelessness:
 Each request from client to server must contain all necessary information.

 Servers do not maintain client state between requests.

 Enhances scalability and reliability.


5. Cacheability
 Responses from the server can be labeled as cacheable or non-cacheable using appropriate HTTP

headers.

 Caching improves performance and reduces server load by serving cached responses for
subsequent identical requests
6. Layered System
 Clients interact with a layered architecture of servers, providing an abstraction of services.

 Intermediate servers can be used for load balancing, caching, security, etc., without affecting the

client-server interaction.
Why Use RESTful APIs?
 Scalability: REST APIs scale well, allowing for increased traffic and usage without significant

changes to the infrastructure.

 Interoperability: They facilitate interaction between different systems, platforms, and languages.

 Simplicity: RESTful APIs leverage standard HTTP methods and status codes, making them easy to

understand and implement.

 Statelessness: Simplifies server logic and improves reliability and scalability.


Latest Adaptations and Best Practices
1. Versioning
 Use versioning in URIs (e.g., /api/v1/resource) or headers to manage changes to the API while

maintaining backward compatibility.

 Avoid breaking changes in existing versions whenever possible.


2. HATEOAS (Hypermedia as the Engine of Application State)
 Enhance discoverability and navigation of the API by providing hypermedia links in responses.
 Include links to related resources, actions, and documentation.
3. Security
 Implement authentication mechanisms such as OAuth, JWT, or API keys to control access to

resources.

 Use encryption (SSL/TLS) to protect data transmitted over the network.


4. Validation
 Validate input data on the server side to prevent malformed requests and ensure data integrity.

 Use appropriate validation libraries or frameworks based on the programming language used.
5. Error Handling
 Use standard HTTP status codes (e.g., 200 OK, 400 Bad Request, 404 Not Found) to indicate the

status of the request.

 Provide detailed error messages in the response body to help clients understand and resolve issues.
6. Performance
 Optimize performance by minimizing latency, leveraging caching, and implementing efficient data

retrieval mechanisms.

 Use compression techniques (e.g., gzip) to reduce the size of responses transmitted over the

network.
7. Documentation
 Provide comprehensive documentation for the API, including endpoints, request/response formats,

authentication methods, and usage examples.

 Use tools like Swagger or OpenAPI to generate interactive documentation automatically.


What to Avoid
1. Overuse of HTTP Methods
 Stick to the standard HTTP methods (GET, POST, PUT, DELETE) for CRUD operations.

 Avoid creating custom methods unless absolutely necessary, as it can lead to confusion and non-

standard behavior.
2. Over-fetching and Under-fetching
 Design resource representations to provide the right amount of data without overloading clients

with unnecessary information.

 Use pagination, filtering, and sparse fieldsets to optimize data retrieval.


3. Ignoring Security
 Neglecting security measures can expose sensitive data and compromise the integrity of the API.

 Regularly audit and update security protocols to address emerging threats and vulnerabilities.

 Authentication and Authorization: Authentication mechanisms such as OAuth, JWT, or API keys

are used to verify the identity of clients. Authorization mechanisms control access to resources

based on permissions and roles.


4 Poor Error Handling
 Inadequate error handling can lead to confusion and frustration for clients.

 Provide clear and informative error messages with actionable steps to resolve issues.

 Status Codes: HTTP status codes are used to indicate the status of a request. Common status codes

include:

200: OK

201: Created

400: Bad Request

404: Not Found

500: Internal Server Error


5. Ignoring Performance
 Neglecting performance considerations can result in slow response times and poor user experience.

 Monitor API performance regularly and optimize where necessary to ensure optimal performance.
Conclusion
REST API architecture provides a flexible and scalable approach to designing web services. By

adhering to the principles and components outlined above, developers can create APIs that are easy to

understand, maintain, and integrate with other systems.


By using examples and diagrams, we can visualize how these architectural concepts are applied in

practice, making it easier to understand and implement RESTful APIs effectively.

You might also like