Rest Web Services Spring Boot
Rest Web Services Spring Boot
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.
--------------------------------------------------------------------------------------------------------------------------------------
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:
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.
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.
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:
For example, if we want to perform the following actions in the social media
application, we get the corresponding results.
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.
--------------------------------------------------------------------------------------------------------------------------------------
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.
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.
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.
--------------------------------------------------------------------------------------------------------------------------------------
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.
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).
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.
--------------------------------------------------------------------------------------------------------------------------------------
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")
@GET
// 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.
@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.
}
}
--------------------------------------------------------------------------------------------------------------------------------------
Before proceeding with exception handling, let us gain an understanding on the following
annotations.
Controller Advice
Exception Handler
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());
}