0% found this document useful (0 votes)
49 views15 pages

01 Spring Rest

Uploaded by

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

01 Spring Rest

Uploaded by

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

Customer Self Care Web Portal (CSWP)

Spring REST

Introduction to REST
Representational State Transfer (REST) is an architectural style that
describes how one system communicates or shares state with another system. The
fundamental concept of REST is a resource, which is anything that can be accessed
or manipulated. These states need to be represented using a common format such
as XML or JSON. In the case of web applications, HTTP is commonly used to
support a RESTful architecture. In other words, REST is used to create a web
application that exposes an HTTP API.
HTTP Methods and CRUD Operations
Standard HTTP methods such as GET, POST, PUT, and DELETE are used to access
and manipulate REST web resources. The CRUD operations have four basic
persistent functions: create, read, update, and delete.
The mapping of CRUD operations to the four HTTP verbs

HTTP Status Codes


The meaningful HTTP status codes help clients utilize your RESTful API. Following
are some HTTP status code elements that might be returned as the server response
when calling a RESTful API.

Build a RESTful Service


Lets build a RESTful application called UserRegistrationSystem with REST
endpoints for user registration.
Introducing UserRegistrationSystem
UserRegistrationSystem can be understood as a software as a service (SaaS)
provider, which allows the user to perform CRUD operations such as creating a new
user, getting a list of all users, getting individual users, updating a user, and
Customer Self Care Web Portal (CSWP)

Spring REST

deleting a user.
UserRegistrationSystem will be formed with a REST API layer and a repository
layer, with a domain layer crosscutting those two, which gives a separation of
concerns.
The REST API layer is responsible for handling client requests, validating client
input, interacting with the repository layer (or service layer), and generating a
response.
The domain layer contains a domain object that has business data. The repository
layer interacts with the database and supports CRUD operations. Lets begin the
development of our RESTful service by understanding these requirements:
• Consumers register themselves by creating as a new user.
• A list of users can be obtained.
• Individual user details can be obtained.
• User details can be updated at the later time.
• A user can be deleted when required.
Identifying REST Endpoints
A URI endpoint is used to identify REST resources. The name we choose for the
UserRegistrationSystem REST API endpoint should have a clearly defined meaning
to consumers.
To design endpoints for services, we should follow some best practices and
conventions that are widely used in the software industry.
• Use a base URI for the RESTful API to provide an entry point.
• Name resource endpoints using plural nouns.
• Use a URI hierarchy to represent related resources.
The UserRegistrationSystem application will have a User resource. This User
resource can be accessed using the GET, POST, PUT, and DELETE HTTP methods.
The following are the REST endpoints we will be creating for our application.

The next step is to define a resource representation and the representation format.
REST typically supports multiple formats such as HTML, JSON, and XML.
JSON Format
JavaScript Object Notation (JSON) is a syntax for storing and exchanging data
between the client and the server. A JSON object is a key-value data format where
each key-value pair consists of a key in double quotes followed by a colon (:),
followed by a value. JSON objects are surrounded by curly braces ({}) where each
key value is separated by a comma (,).
Following is an example of a User JSON object.
Customer Self Care Web Portal (CSWP)

Spring REST

Creating the UserRegistrationSystem Application


We will be creating UserRegistrationSystem by generating a Spring Boot
application using Spring Initializr,Select Web, JPA, and H2 as dependencies. By
default, the Spring Boot application runs on port 8080.

Embedded Database: H2
H2 is an open source lightweight relational database management system written in
Java. The H2 database can be easily embedded in any Java-based application and
can be easily configured to run as an in-memory database.
The H2 database cannot be used for production development because the data will
not persist on the disk. That’s why this database is mostly used for development and
testing. The H2 database supports SQL and the JDBC API and has strong
security features.
In the UserRegistrationSystem application, we will be using H2 to persist our data.
To use H2 in a Spring Boot application, we need to include a build dependency in
the pom.xml file. While using H2 as an in-memory database, we do not need to
provide any database connection URLs or username and password. The starting and
stopping of the database during deployment and application shutdown will be taken
care by Spring Boot.
Domain Implementation: User
Customer Self Care Web Portal (CSWP)

Spring REST

Below shows the UML class diagram representing the Users domain object in the
UserRegistrationSystem application.

In the UserRegistrationSystem project, we will create a data transfer object (DTO)


class called UserDTO corresponding to the Users domain’s Object inside a
subpackage called com.cswp.webstore.domain under the src/main/java folder.
The DTO object contains just data and access modifiers and no logic; it is used to
transfer data between different layers of the application when there is a separation
of concerns. We can annotate this class with Java Persistence API (JPA) annotations,
which allows the Users class to be easily persisted and retrieved using the JPA
technology.
implementation of the UserDTO entity class

@Entity
@Table(name = "Users")
public class User {
@Id
Customer Self Care Web Portal (CSWP)

Spring REST

@GeneratedValue
@Column(name = "USER_ID")
private Long id;
@Column(name = "NAME")
private String name;
@Column(name = "ADDRESS")
private String address;
@Column(name = "EMAIL")
private String email;
//generate setters and getters

Here the User class has four attributes, named id, name, address, and email.
UserDTO is annotated with the @Entity annotation to make it a JPA entity. This
entity class is annotated with the @Table annotation to define the table name as
Users.
The User’s id property has been annotated with the @Id annotation to make it the
primary key. The id attribute has been annotated with the @GeneratedValue
annotation to indicate that the id value should be generated automatically. The id
attribute also has been annotated with the @Column annotation to specify the
details of the column to which a field or property will be mapped.
The other three properties (name, address, and email) are annotated with the
@Column annotation.
Repository Implementation: UserJpaRepository
Repositories or DAOs abstract and encapsulate all access to the data source. The
repository includes an interface that manages the connection with the data source
and provides a set of methods for retrieving, manipulating, deleting, and persisting
data. It is good practice to have one repository per domain object. With the goal of
eliminating the need to write any repository implementations, the Spring Data
project provided the JpaRepository interface that automatically generates its
implementation at runtime. Below is the dependency information that needs to be in
the Maven pom.xml to support JpaRepository.

We will be creating a repository interface by extending the Spring Data JPA


subproject’s org.springframework.data.jpa.repository.JpaRepository interface to
persist the User domain object into a relational database.
We begin the repository implementation by creating the
com.cswp.webstore.repository package under the src/main/java folder inside the
UserRegistrationSystem application. Also, we can create a UserJpaRepository
interface, as shown below
Customer Self Care Web Portal (CSWP)

Spring REST

package com.cswp.webstore.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.cswp.webstore.domain.User;
@Repository
public interface UserJpaRepository extends JpaRepository<User, Long> {
User findByName(String name);
}

As shown above, the UserJpaRepository interface extends Spring Data’s


JpaRepository, which takes the type of domain object that it can manipulate and the
type of User domain object’s identifier field,
User and Long, as its generic parameters, T and ID. UserJpaRepository inherits all
of JpaRepository’s CRUD methods for working with User persistence. Spring Data
JPA allows developers to define other query methods just by declaring their method
signature.
As shown in the previous code, we define a custom finder method called
findByName, which basically creates a JPA query of the form “select u from User
u where u.name equals :name".
The benefit of Spring Data JPA is that developers do not have to write
implementations of the repository interface. Spring Data JPA creates an
implementation at runtime when we run the application. Now, let’s create the REST
controller class and implement the REST endpoints.
Build a RESTful API
Before we start implementing the RESTful API, we need to understand some basic
Spring elements that will be used to implement the RESTful API in Spring.
• @RestController: This is a stereotype annotation that itself is annotated with
@Controller and @ResponseBody, which eliminates the need of annotating each
method with @ResponseBody. This annotation is used to define an API endpoint.
This annotation lets Spring render the result back to the caller. To build RESTful
web services in Spring, create a controller class using the @RestController
annotation to handle the HTTP request.
• @RequestMapping: This annotation is used to provide routing information. The
HTTP request in Spring is mapped to the corresponding handler method. This
annotation can be applied to the class level to map the HTTP request to the
controller class or can be applied to the method level to map the HTTP request to
the controller handler method.
• ResponseEntity: This class extends HttpEntity and is used in the controller
Customer Self Care Web Portal (CSWP)

Spring REST

method to add the HTTP status to the response. It can contain HTTP status codes,
headers, and the body.
public class ResponseEntity<T> extends HttpEntity<T>
• @RequestBody: This annotation is used to bind the method parameter to the
body of the incoming HTTP request. Spring will use an HttpMessageConverter to
convert the body of the web request into a domain object depending on the content
type of the request. The @valid annotation can be applied to perform automatic
validation, which is optional.
• @ResponseBody: This annotation is used to bind the return value from the
annotated method to the outgoing HTTP response body. Spring will use an
HttpMessageConverter to convert the return value to the HTTP response body
(typically to return data formats such as JSON or XML), depending on the content
type of the request HTTP header.
• @PathVariable: This annotation is used to bind a method parameter to a URI
template variable (the one in {}).
• MediaType: This is a subclass of MimeType. While using the @RequestMapping
annotation, we can also specify the MediaType to be produced or consumed by the
controller method.
Create a RESTful Controller: UserRegistrationRestController
We will be creating a Spring MVC controller and implementing REST API
endpoints. Let’s create the UserRegistrationRestController class within the
com.cswp.webstore.rest package under the src/main/java folder. This controller
class provides all the necessary endpoints to retrieve and manipulate users. Below
shows the necessary code changes for the UserRegistrationRestController class.

We annotated the UserRegistrationRestController class with the @RestController


annotation and defined a new @RequestMapping to map the URI /api/user to the
entire class, which means the HTTP request received on the /api/user URI is
Customer Self Care Web Portal (CSWP)

Spring REST

attended by the UserRegistrationRestController class. We have used the


@Autowired annotation to autowire UserJpaRepository to the RESTful controller.
Let’s define different endpoints in the controller class to access and manipulate
User domain. we will be using the new annotations @GetMapping, @PostMapping,
@PutMapping, and @DeleteMapping instead of the standard @RequestMapping,
which have been available since Spring MVC 4.3 and are a standard way of defining
REST endpoints. These new annotations act as a wrapper to @RequestMapping,
simplifying mappings for common HTTP methods.
@GetMapping: Retrieve All Users
This is a composed annotation that is a shortcut for
@RequestMapping(value="/", method =RequestMethod.GET). The GET
request on the /api/user/ endpoint returns the list of users available in the
UserRegistrationSystem application. Below shows the necessary code for
implementing this functionality.

The listAllUsers method returns ResponseEntity containing the HTTP response.


This method reads all of the users using UserJpaRepository. We then created an
instance of ResponseEntity by calling its constructor, which takes two arguments:
User domain is data that became part of the response body, and the HttpStatus.OK
status value is data that became the response status code.
Let’s test the first endpoint by running the UserRegistrationSystem application as a
Spring Boot application from STS and launching the Postman app. Enter the URL
http://localhost:8080/api/user/ and hit Send, we will see the following post man
page, Because there are no users created yet, this results in an empty collection.
So, the next task is to add a user to UserRegistrationSystem by implementing the
POST verb functionality.
Customer Self Care Web Portal (CSWP)

Spring REST

@PostMapping: Create a New User


The @PostMapping annotation is a composed annotation that is a shortcut for
@RequestMapping(value="/",method=RequestMethod.POST). The POST request on
the /api/user/ endpoint creates a new user using the enclosed body of the request.
POST Verb Implementation to Create a New User

The createUser method takes a parameter of type User annotated with the
@RequestBody annotation, which requests Spring to convert the entire request
body to an instance of User domain.
We have configured content negotiation using consumes =
MediaType.APPLICATION_JSON_VALUE, which indicates this method will accept
only JSON data from the request body. The produces and consumes attributes are
used to narrow the mapping types. we can eliminate this because @RequestBody
uses HttpMessageConverters to determine the right converter to use and to
convert the body of the HTTP request to domain objects. The message converters in
Spring BOOT support JSON and XML resource representations.Inside the method,
we delegated the User persistence to userJpaRepository’s save method. Then we
created a new ResponseEntity with the created user (User) and HTTP status
HttpStatus.CREATED (201) and returned it.
To test this newly added endpoint, start the UserRegistrationSystem application. If
the UserRegistrationSystem application is already running, then we need to
terminate the process and restart it. Launch Postman and select the request type as
POST. Click Body and select raw; then from the drop-down, select JSON
(application/json) as the Content-Type header. Enter some information and hit
Send.
Customer Self Care Web Portal (CSWP)

Spring REST

@GetMapping ("/ {id}"): Retrieve an Individual User


The next step is to implement an endpoint to access an individual user.
GET Verb Implementation to Retrieve Individual User

As shown above we have annotated the getUserById method with the


@GetMapping("/{id}") annotation. The placeholder {id} in the URI along with the
@PathVariable annotation allows Spring to extract the id parameter value. Inside
the method, we have used UserJpaRepository’s findOne method to read the User
object and pass it as part of a ResponseEntity along with the HTTP status
HttpStatus.OK (200).
To test this functionality, launch Postman and restart the UserRegistrationSystem
application. Enter the URL http://localhost:8080/api/user/1 and hit Send, as shown
below
Customer Self Care Web Portal (CSWP)

Spring REST

@PutMapping: Update a User


This annotation is a composed annotation that is a shortcut for
@RequestMapping(method = RequestMethod.PUT). It requests that the enclosed
entity be considered as a modified version of an existing resource at the request
Below shows the necessary code.

We retrieved the existing User object as currentUser using UserJpaRepository’s


findById method by passing the argument as user’s id Then we updated the
currentUser property data from the user’s information in requestbody.
we also called UserJpaRepository’s saveAndFlush method by passing currentUser,
which saves User and flushes the changes instantly. Finally, we returned
ResponseEntity with currentUser as the response body and HttpStatus.OK as the
HTTP status.
Let’s test this endpoint by launching Postman and restarting the application, as
shown in below
Customer Self Care Web Portal (CSWP)

Spring REST

@DeleteMapping: Delete a User


This is a composed annotation that is a shortcut for @RequestMapping(method
=RequestMethod.DELETE). It requests that the application deletes resources
identified by Request-URI.

In the inside method we called UserJpaRepository’s delete method by passing the


argument id from pathvariable. And, then we returned ResponseEntity with an
HTTP status of HttpStatus.NO_CONTENT (204).
Restart the UserRegistrationSystem application and launch Postman to test this
functionality, as shown in below
Customer Self Care Web Portal (CSWP)

Spring REST

Handle Errors in a RESTful API


Although a developer takes care of handling error, it is important to design error
responses in a suitable format that allows a client who consumes a RESTful API to
understand the issues and help by using the API correctly.
Error handling is one of the most important concerns of RESTful API development.
In the real world, a RESTful API is being consumed in various scenarios, and it is
difficult to predict everything about the scenario in which the API is being
consumed.
Consider a scenario in the UserRegistrationSystem application where the client
tries to fetch user information that doesn’t exist in the system.Lets say GET request
for a nonexistent user with an ID of 50.

As shown above the RESTful API returns the empty body because
UserJpaRepository’s findOne method returns null to UserRegistrationRestController
for a user ID of 50, which doesn’t exist. The RESTful API returns the HTTP status
code as 200 OK, instead of status code 404, which should indicate the requested
user doesn’t exist.
To achieve this behavior, we will validate the user id attribute in
UserRegistrationRestController’s getUserById method. For a nonexistent user,
Customer Self Care Web Portal (CSWP)

Spring REST

return ResponseEntity containing CustomErrorType and status code


HttpStatus.NOT_FOUND (404).
Lets create CustomErrorType as shown below

The CustomErrorType class declared errorMessage as a member variable with its


corresponding getter method. This errorMessage is getting initialized inside the
constructor of this class. With this modification in the UserRegistrationSystem
application, restart the application and launch Postman to send a GET request for
the user with an ID of 50. The UserRegistrationRestController result with the right
status code and error message is shown below
Customer Self Care Web Portal (CSWP)

Spring REST

The same user ID verification needs to be performed for other methods that are
involved in CRUD operations with HTTP methods such as GET, PUT, and DELETE
in the UserRegistrationSystem application to return the right status code and
message.

You might also like