01 Spring Rest
01 Spring Rest
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
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
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.
@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.
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);
}
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.
Spring REST
Spring REST
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
Spring REST
Spring REST
Spring REST
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
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.