0% found this document useful (0 votes)
42 views

Rest Web Services Spring Boot

The document discusses web services, describing RESTful and SOAP web services as well as their architectures and differences. RESTful services use HTTP and lightweight formats like JSON while SOAP relies on XML. REST has simpler protocols but SOAP provides stricter standards and is used for enterprise systems.
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)
42 views

Rest Web Services Spring Boot

The document discusses web services, describing RESTful and SOAP web services as well as their architectures and differences. RESTful services use HTTP and lightweight formats like JSON while SOAP relies on XML. REST has simpler protocols but SOAP provides stricter standards and is used for enterprise systems.
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/ 9

JAVA WEB SERVICES

Introduction to Web Services:


Web services are software components that enable communication between different
applications over a network, typically the internet. They use standard protocols and data
formats such as HTTP, XML, JSON, and SOAP to facilitate data exchange. Web services can be
categorized into two main types:

RESTful Web Services: Representational State Transfer (REST) is an architectural style for
designing networked applications. RESTful web services use HTTP methods (GET, POST, PUT,
DELETE) to perform CRUD (Create, Read, Update, Delete) operations on resources, which are
represented as URLs. They are lightweight, scalable, and widely used for building APIs.

SOAP Web Services: Simple Object Access Protocol (SOAP) is a protocol for exchanging
structured information in the implementation of web services. SOAP services use XML as the
message format and typically rely on HTTP or SMTP as the transport protocol. They are
known for their strict standards and can be used in enterprise-level systems.
--------------------------------------------------------------------------------------------------------------------------------------

Architecture of web service:


The architecture of a web service is the structural design that defines how the various
components of the service interact with each other and with external systems or clients.
Web service architectures are typically based on specific design patterns and protocols that
enable communication over the internet. There are two primary architectural styles for web
services: RESTful and SOAP-based. Let's explore the architecture of each:

RESTful Web Service Architecture:


REST (Representational State Transfer) is an architectural style for designing networked
applications that use HTTP as the communication protocol. The architecture of a RESTful
web service typically includes the following components:

a. Resources: In REST, resources are the key abstractions. Resources are represented by URLs
(Uniform Resource Locators) and can be thought of as entities or objects that the web
service manages. For example, in a blog application, articles and comments could be
considered resources.

b. HTTP Methods: RESTful web services use HTTP methods to perform operations on
resources. The primary HTTP methods used are:

GET: Retrieve data from a resource.

POST: Create a new resource.

PUT: Update an existing resource.


DELETE: Remove a resource.

c. HTTP Status Codes: HTTP status codes (e.g., 200 OK, 404 Not Found) are used to indicate
the outcome of an HTTP request. They convey whether an operation was successful,
encountered an error, or had other outcomes.

d. Stateless: RESTful web services are stateless, meaning that each request from a client to
the server must contain all the information needed to understand and process the request.
There is no session state stored on the server between requests.

e. Representation: Resources in REST can have multiple representations, such as JSON, XML,
HTML, or others. Clients request a specific representation of a resource using content
negotiation.

SOAP-based Web Service Architecture:


SOAP (Simple Object Access Protocol) is a protocol for exchanging structured information in
web services. The architecture of a SOAP-based web service includes the following
components:

a. XML Messages: SOAP messages are formatted as XML documents. They consist of an
envelope, which contains headers and a body. The body typically carries the actual data.

b. Service Description: SOAP-based web services are described using a Web Services
Description Language (WSDL) document. The WSDL defines the service's interface, including
the operations it supports, the data types used, and the protocols for communication.

c. Remote Procedure Calls (RPC): SOAP is often associated with RPC-style communication,
where clients invoke remote methods on a server. The server processes the request and
sends back a response.
d. Transport Protocols: SOAP can be used with various transport protocols, such as HTTP,
SMTP, and more. When used with HTTP, it is similar to REST in terms of using HTTP for
communication.

e. Stateful or Stateless: SOAP web services can be designed to be stateful or stateless,


depending on the application requirements.
--------------------------------------------------------------------------------------------------------------------------------------

Types of Web Services:


In Spring Boot, you can create various types of web services, but the two most common types are:

o RESTful Web Servies


o SOAP Web Services

RESTful Web Services: REST (Representational State Transfer) is an architectural style for
designing networked applications, and it is well-supported in Spring Boot. RESTful web
services are used to expose APIs over HTTP, and they use standard HTTP methods (GET,
POST, PUT, DELETE) to perform CRUD (Create, Read, Update, Delete) operations on
resources. Spring Boot makes it easy to create RESTful APIs using annotations like
@RestController and @RequestMapping. You can return data in various formats such as
JSON or XML.
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
SOAP Web Services: SOAP (Simple Object Access Protocol) is another protocol for building
web services that use XML as the message format. Spring Boot also provides support for
creating SOAP-based web services using the Spring Web Services (Spring-WS) framework.
With Spring-WS, you can define SOAP endpoints, create XML schemas (XSD), and generate
Java classes for handling SOAP messages. This is often used in enterprise-level systems and
when strict standards and security features are required.

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.

--------------------------------------------------------------------------------------------------------------------------------------

Differences between REST vs SOAP Web Application:


Protocol:

REST: REST is an architectural style that uses a variety of protocols, with HTTP being the
most common choice. It relies on standard HTTP methods like GET, POST, PUT, and DELETE to
perform operations on resources.

SOAP: SOAP, on the other hand, is a protocol itself. It uses XML as its message format and
can operate over a variety of lower-level protocols like HTTP, SMTP, or even TCP.

Message Format:

REST: REST typically uses lightweight data interchange formats like JSON or XML for message
serialization, but it is not tied to any specific format. JSON is more commonly used due to its
simplicity and readability.

SOAP: SOAP messages are always XML-based, which makes them more rigid and verbose
compared to REST.

Service Description:

REST: REST services typically lack a formal service description language. Documentation is
often provided separately using tools like Swagger.

SOAP: SOAP services are described using a formal contract called a WSDL (Web Services
Description Language) document. WSDL defines the service's operations, message format,
and transport protocol.

Statelessness:
REST: RESTful services are inherently stateless. Each request from a client to the server must
contain all the information needed to understand and process the request.

SOAP: SOAP services can be designed to be stateful or stateless depending on the


application's requirements.

Ease of Use:

REST: REST is generally considered easier to understand and use due to its simplicity. It relies
on standard HTTP methods and leverages URLs to represent resources, making it more
intuitive for developers.

SOAP: SOAP can be more complex to work with due to the XML-based messages and the
need to generate or parse XML. It often requires more boilerplate code.

Performance:

REST: REST is typically more lightweight and efficient, making it a good choice for scenarios
with limited bandwidth or where performance is a critical concern.

SOAP: SOAP messages tend to be larger and more resource-intensive, which can impact
performance, especially in low-bandwidth environments.

Flexibility:

REST: REST is more flexible in terms of data formats and can support a wide range of data
representations. It can also be easier to evolve and extend.

SOAP: SOAP is more rigid in terms of message format and tends to be less flexible when
changes to the service contract are required.

Ecosystem and Adoption:

REST: REST has gained widespread adoption, particularly for public APIs and web services on
the internet. It is the de facto standard for web APIs.
SOAP: SOAP is still prevalent in enterprise-level systems and scenarios where strict standards
and security features are required.

--------------------------------------------------------------------------------------------------------------------------------------

REST API Principles:


RESTful API principles, based on the REST (Representational State Transfer) architectural
style, provide a set of guidelines and constraints for designing web services that are simple,
scalable, and easy to understand. Adhering to these principles helps ensure that your API is
intuitive and follows best practices for web service development. Here are the key RESTful
API principles:

Resource-Based:
Resources are the fundamental concept in RESTful APIs. Everything is considered a resource, and
each resource is identified by a unique URL (Uniform Resource Locator).

Resources can represent entities, objects, or data in your application, such as users, products,
articles, etc.

HTTP Methods:
RESTful APIs use standard HTTP methods (verbs) for performing CRUD (Create, Read,
Update, Delete) operations on resources.
The primary HTTP methods used are:
GET: Retrieve data from a resource.

POST: Create a new resource.

PUT: Update an existing resource or create it if it doesn't exist.

DELETE: Remove a resource.

Uniform Interface:
RESTful APIs have a consistent and uniform interface, which simplifies interactions between
clients and servers.
This uniformity is achieved through the use of standard HTTP methods, resource URLs, and a
small set of well-defined headers.

Statelessness:
RESTful APIs are stateless, meaning that each request from a client to the server must
contain all the information needed to understand and process the request.
There is no session state stored on the server between requests, which simplifies server
design and scalability.

Representation:
Resources in REST can have multiple representations, such as JSON, XML, HTML, or others.
Clients specify the desired representation through content negotiation using HTTP headers
(e.g., Accept and Content-Type).

HATEOAS (Hypermedia as the Engine of Application State):


HATEOAS is a principle that suggests that a RESTful API should provide hyperlinks within the
responses that guide clients on how to interact with the service.
Clients follow links to navigate the application's state, making the service discoverable and
self-descriptive.

Layered System:
RESTful systems can be composed of multiple layers, where each layer has a specific
responsibility.This architecture promotes separation of concerns and can improve scalability
and security.

Caching:
RESTful APIs encourage the use of HTTP caching mechanisms. Responses can include cache-
control headers to specify how long the response can be cached by clients or intermediary
cachesCaching can improve performance and reduce server load.

Security:
Security measures such as HTTPS (HTTP Secure), authentication, and authorization
mechanisms can be applied to RESTful APIs to ensure data confidentiality and integrity.

Idempotence:
Some HTTP methods (e.g., GET, PUT, DELETE) are idempotent, meaning that making the
same request multiple times should have the same effect as making it once.
This property is important for the reliability of web services.
By following these RESTful API principles, you can design APIs that are consistent, intuitive,
and well-structured, making them easier for developers to work with and for clients to
integrate into their applications.
--------------------------------------------------------------------------------------------------------------------------------------

JAX-RS injection - PathParam, QueryParam, FormParam:


@PathParam:
@PathParam is used to inject values from the URI path into Java method parameters.

It allows you to specify a template variable within the URI path, and JAX-RS will
automatically match and extract the corresponding value from the actual URI.

@Path("/users")
public class UserResource {
@GET
@Path("/{userId}")
public Response getUserById(@PathParam("userId") String userId) {
// userId will be extracted from the URI path.

}
}

@QueryParam:
@QueryParam is used to inject values from query parameters in the URI into Java method
parameters.

Query parameters are typically included in the URI after a ? character and separated by &
characters.

@Path("/search")

public class SearchResource {

@GET

public Response search(

@QueryParam("query") String query,

@QueryParam("page") int page) {

// query and page will be extracted from the query parameters in the URI.

@FormParam:
@FormParam is used to inject values from form parameters submitted in the body of an
HTTP request with the application/x-www-form-urlencoded content type.

Form parameters are commonly used in HTML forms.


@Path("/submit")
public class FormSubmissionResource {

@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response processForm(
@FormParam("username") String username,
@FormParam("password") String password) {
// username and password will be extracted from the form parameters in the request
body.
}
}
--------------------------------------------------------------------------------------------------------------------------------------

Exception Handling In Spring Boot:


Handling exceptions and errors in APIs and sending the proper response to the client is good
for enterprise applications. In this chapter, we will learn how to handle exceptions in Spring
Boot.

Before proceeding with exception handling, let us gain an understanding on the following
annotations.

Controller Advice

The @ControllerAdvice is an annotation, to handle the exceptions globally.

Exception Handler

The @ExceptionHandler is an annotation used to handle the specific exceptions and


sending the custom responses to the client.

Example:

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(ApplicationException.class)
public ResponseEntity<String>
handleApplicationException(ApplicationException ex) {

return
ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.getMessa
ge());
}

You might also like