Spring Rest Initial Concept
In earlier days we are familiar about WEB Services. This WEB Services mainly follows a specific protocol named as SOAP (Simple Object Access Protocol). Though consuming a WEB Service or publishing in a WEB Service is really painful for a Developer. During that time developer use SoapUI to test the WEB Services.
But later in this Information Technology world came a new Service known as REST Service. This REST Service is totally different from WEB Service. While the introduction of REST Service also makes the life of a developer happy. REST stands for REpresentational State Transfer. It uses the normal underlying protocols like HTTP, HTTPS, etc. And REST Service not only deals with only XML type of data but also deals with HTML, TEXT, JSON type of data.
Later, Spring comes with his own approach and named it as Spring REST. The introduction of Spring REST helps the developer much more happy in compare to the introduction of REST. The foremost advantage of Spring REST is that by default it uses JSON type of data for both producing and consuming perspectives.
Comparison between Spring REST and JAX-RS
Spring REST | JAX-RS |
Spring REST is an alternative way of writing REST Services in Java | JAX-RS is the standard Java specification for RESTful Services |
Spring REST is the complete implementation for RESTful Services by Spring. It can be used by itself. | JAX-RS is just a specification, one will need to include an implementation of Jersey in order to write services |
Spring REST uses its own custom annotations for REST | JAX-RS uses standard annotations that are part of Java EE |
Spring REST does not implement JAX-RS | JAX-RS is a specification and it doesn’t implement Spring REST |
Important Annotations in Spring REST and JAX-RS
Spring REST | JAX-RS | Annotation Significance |
@RequestMapping, @GetMapping | @Get | Specify a method to a HTTP GET Method |
@RequestMapping, @PostMapping | @Post | Specify a method to a HTTP POST Method |
@RequestMapping, @PutMapping | @Put | Specify a method to a HTTP PUT Method |
@RequestMapping, @DeleteMapping | @Delete | Specify a method to a HTTP DELETEMethod |
@RequestMapping | @Path | Specify the URI that the method or class maps to |
@RequestParam | @QueryParam | Specify a Query Parameter |
@PathVariable | @PathParam | Specify a path parameter |
Using Spring REST with Spring Boot
As we all know that Spring Boot is a platform on top of the Spring Framework where we can create stand-alone applications. Spring Boot provides numerous implementations like Spring REST, Spring Data, Spring Micro-services, etc. So, lets made hand dirty by creating a Spring REST application using Spring Boot.
I have created a Demo project named as spring-rest-masterclass uploaded in my personal GitHub account. One can clone the project and can test locally in their system. All the steps that are required to download the project from GitHub and running it locally are mentioned in the README.md file of spring-rest-masterclass repository.
- Brief Description – I have used Spring Boot, Maven and Java in this spring-rest-masterclass project. The main purpose of this project is to focus on implementing Spring-REST Service using Spring Boot. I have not used any database in this project. I have simply used Java Collection Framework to show all the HTTP operations like GET, POST, PUT and DELETE. To test the Services, I have used Postman.
- Software Used – Software required to develop this project.
- Spring Tool Suite-4.7.0-RELEASE – If latest version is available then download that one
- Apache Maven 3.6.3 – If latest version is available then download that one
- Java 8 – Not less than Java8
- Git 2.27.0 – Latest version as available
- Postman v8.3.0 – To test the REST Service
- List of the software and their download link with the installation steps are briefly described in the README.md file of spring-rest-masterclass repository
- Project Components – The project that I develop in support to the Spring-REST concept is a Maven project. Here I have used one dependency named as spring-boot-starter-web dependency. This dependency provides the support of Spring-REST libraries
<!-- Spring REST Dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- Structure of the Project – To support and use Spring REST and its libraries in your project you need to structure in a right way as provided below:
Spring Boot expects that all source files are located in sub packages of the class annotated with @SpringBootApplication. In the above sample project, I have one class named as SpringRestMasterclassApplication.java which has the @SpringBootApplication annotations in it.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringRestMasterclassApplication {
public static void main(String[] args) {
SpringApplication.run(SpringRestMasterclassApplication.class, args);
}
}
- Spring-Rest Implementation – To implement Spring-REST I have used one of its dependencies named spring-boot-starter-web. You need to have a Controller class annotated with @RestController annotation.
Let’s look to the Controller class first named as SpringRestMovieController.java. Below I have provided the signatures of the methods that I have used in this class.
@RestController
public class SpringRestMovieController {
@GetMapping("/allMovies")
public List<Movie> getAllMovies();
@GetMapping("/findMovieByName/{name}")
public Movie getMovieByName(@PathVariable(value = "name") String movieName);
@GetMapping("/findMoviesByYear/{year}")
public List<Movie> getMoviesByReleaseYear(@PathVariable(value = "year") String releaseYear);
@PostMapping("/saveMovie")
public List<Movie> saveMovie(@RequestBody Movie movie);
@PutMapping("/updateMovie/{name}")
public List<Object> updateMovie(@PathVariable(value = "name") String movieName, @RequestBody Movie movie);
@DeleteMapping("/deleteMovie/{name}")
public List<Object> deleteMovie(@PathVariable(value = "name") String movieName);
I have used almost all of the HTTP Methods as GET, POST, PUT and DELETE. To serve the purpose, I have used different Annotations for that which are as follows:
- @GetMapping – Serving the GET HTTP Method
- @PostMapping – Serving the POST HTTP Method
- @PutMapping – Serving the PUT HTTP Method
- @DeleteMapping – Serving the DELETE HTTP Method
- @PathVariable – To pass the parameter within the URI. Like, /<<relative-URI>>/{pathVariable}
- @RequestBody – In case of POST or PUT method you need to pass the desired Object which will either insert or update in DB. For that we use @RequestBody annotation. So that the desired object will pass in the body of the REST Endpoint.
- @PathParam – To pass the parameter as Query String in URI. Like, /<<relative-URI>>?pathParam1=value1&pathParam2=value2. I haven’t used this annotation in the above mentioned sample project.
Following the MVC Architecture Pattern, I have used Service Interface and its implementation in ServiceImpl Class. There is a Model Class which is used to pass as a request object and also to display as a response object. No database is implemented. Because the sole purpose of the project is to understand the Spring-REST implementation.
- Testing the application – In this application there is no UI component and no integration of Database. One can simply integrate the code with UI and Database. No restrictions on that. While here I have used Postman to test the REST endpoint as defined in the Controller class.
- Clone the application from GitHub and set up the application locally in any one of the IDEs like Spring Tool Suite (STS) or Eclipse.
- Right Click on the Application
- Click the Option Run As
- Select the option Spring Boot App.
- It will start the application in the port no. 7113.
- Now in Postman you can test the endpoints.
Below I have provided the lists of endpoints as available in this application.
- Get all Movies – localhost:7113/allMovies
- Get Movie by Name – localhost:7113/findMovieByName/{name}
- Get all Movies by Release Year – localhost:7113/findMoviesByYear/{year}
- Save a Movie – localhost:7113/saveMovie, in the Body provide the JSON Object. A dummy JSON object is provided.
- Update a Movie – localhost:7113/updateMovie/{name}, in the Body again provides the JSON data.
- Delete a Movie – localhost:7113/deleteMovie/{name}
- Sample JSON Data – I have provided 2 sample JSON Data, one will be used in the POST Method and another for PUT Method.
POST Request – JSON Data
{
“name” : “movie name”,
“releaseYear” : “2021”,
“rating” : “8.2”,
“actors” : [ “actor name”, “actress name” , “villain name” ],
“director” : “director name”,
“producer” : “producer name”
}
PUT Request – JSON Data (Same as that of POST JSON Data)
{
“name” : “movie name”,
“releaseYear” : “2021”,
“rating” : “8.2”,
“actors” : [ “actor name”, “actress name” , “villain name” ],
“director” : “director name”,
“producer” : “producer name”
}
GitHub Code Link
Download the Source Code from GitHub
Common Faced Problems
Interview FAQs
Other Useful Links of Spring REST
Spring Data using RDBMS (MySQL DB) and Spring REST
Spring Data using NoSQL DB and Spring REST
Spring Data using Cypher Neo4j DB and Spring REST
Spring Data using Redis and Spring REST
Spring Apache Kafka – Producer & Consumer
Spring Kafka Confluent – Set Up
Spring Kafka Confluent – Producer & Consumer
Spring Cloud using Google Cloud SQL & Google Cloud Storage
Spring Cloud using Google Cloud Pub-Sub