REST – Spring Boot

Since its inception in 2002, the Spring framework saw a tremendous growth in terms of functionalities which ultimately made the framework a bit complex. One of the main error-prone areas in traditional Spring programming was, of course, the enormous amount of config XML files that one had to create for a fairly large Spring project. SpringBoot was introduced by Pivotal software to deal with this by allowing autoconfiguration. SpringBoot is built on top of the Spring framework. Using SpringBoot, we can convert our application into an executable jar or war file that can be deployed. We need not create any explicit XML configuration in a SpringBoot Application.

In this tutorial, we will learn how to create a REST service using SpringBoot.

Maven Configurations

To create the project structure, we can manually do the steps below or use Spring Tool Suite to build the project.If you are using STS, you can create a Spring Boot application using New -> Spring Starter Project.Either ways, the final pom.xml created would be almost the same.

Let us see how to build the project with maven now.

In command prompt, we need to create the directory structure. Type the following command into the console:

This command will trigger download of many maven dependencies that are required to set up this project. At the end of the build, we should see a build success message.

Import project into eclipse using import -> maven -> existing maven projects into eclipse.

Modify pom.xml :

 

If we don’t specify the parent as spring boot starter parent, we would have to individually show the same version number for all the spring related dependencies. If there is a need to add a separate central parent project which contains all the dependencies, we should remove the <parent> tag to ensure nothing is broken by our code. In this case, we need to add the following in pom.xml.

 

After required changes are made to pom.xml, run the following in command prompt:

On the first run, this should download all the dependencies to the M2_HOME folder.

Gradle Configurations

If we are using gradle for building, just like pom.xml of maven, we need to add build.gradle build file. We can generate the build file from existing pom.xml by navigating to the root folder of the project and typing:

Generated gradle.build file:

After successful creation of the first REST application, we may invoke gradle build by the following command:

POJO

We will define an Employee class which has details like employee ID, name, department and date of joining.

Note that we use @JsonSerialize annotation. This is to ensure that the Date object is serialized correctly. The required format in which dateOfJoining shall be shown in XML and JSON outputs is specified using @JsonFormat‘s parameter value.

RestController

So far, we have created the Employee POJO. We need to create a Controller that serves the HTTP GET, PUT, callPOST and DELETE requests. In addition to the response body, we will take care of returning the correct status code according to the result at the server rather than just returning 200 STATUS OK for every call.

We are going to use ResponseEntity to give the correct status codes. Our code will do the following in addition to the core functionalities:

  • GET request to a resource that has not been created yet will return 404 NOT FOUND
  • POST request with an account id which is already stored in the HashMap will return 409 CONFLICT which means that the request could not be completed due to a conflict with the current state of the resource.
  • PUT and DELETE calls will give 204 NO CONTENT which means that the operation was successfully done at server end but no content is returned.

Note that we are using @RestController annotation. @RestController annotation is a replacement for @Controller and @ResponseBody annotations. It takes care of conversion of the responses to XML or JSON format according to the request’s accept header. There is no need to explicitly specify @Produces inside the @RequestMapping annotation as far as you have the dependencies for XML and JSON parsers correctly specified inside the project’s pom.xml.

EmployeeController.java:

 

Constants.java:

 

Making Our Application Executable

So far, we have created the model and controller which shall handle the HTTP Request. Now we need to convert this application into executable format.
We will use @SpringBootApplication for running this code as a standalone application. This is essentially the starting point of the SpringBoot Application and dependency injection is done via SpringApplication.run(StartupApplication.class, args).

 

Testing Our SpringBoot Application

This can be done in two ways

  • One way is to use mvn or gradle command for spring boot run

    or
  • Second way is by following the traditional approach to create jar and run it via command prompt.
    • We can create the jar with the following maven or gradle command

      OR

      On successful packaging, the jar file should be available at target/RestWithSpring-1.0-SNAPSHOT.jar in case of maven build OR build/libs/RestWithSpringBoot -0.1.0.jar in case of gradle build.
    • Run the following command to get the service up and running.

In order to see the output in json format, type the following in our browser:

http://localhost:8080/employees/default.json

The JSON output obtained will be:

To see the output in XML format, change the URL to:

http://localhost:8080/employees/default.xml

The XML output generated will be:


 

SOAPUI can be handy in case we need to verify the HTTP Status code returned in case of a failed HTTP Request.

We have attached the screenshot of a successful POST request and  a failed POST request for reference. Note that the HTTP Response headers contain 409 as response code when POST request is repeated with same Employee details.

Successful POST request:

successful POST request
successful POST request

 

Failed POST request due to duplicate content:

Failed POST call
Failed POST call

 

 

Leave a Reply