Creating a simple Spring Boot RESTful Web Service

In this tutorial, we will make a RESTful Web Service aka API in Spring framework using Spring Boot and Maven build system.

Spring framework is an open source Java platform that provides MVC infrastructure support for developing robust Java applications very easily and very rapidly using recommended MVC pattern.

What is RESTful programming?

REST is the underlying architectural principle of the web. The awesome thing about the web is the fact that clients (browsers) and servers can interact in complex ways without the client knowing anything about the server and the resources it hosts. The key rule is that the server and client must both agree on the media used, which in the case of the web is HTML.

An API that follows the principles of REST does not need the client to know anything about the structure of the API. Rather, the server needs to provide whatever information the client needs to interact with the API. An HTML form is an example of this: The server specifies the location of the resource, and the required fields. The browser doesn’t know in advance where to submit the information, and it doesn’t know in advance what information to submit. Both forms of information are entirely supplied by the server. (This principle is called HATEOAS.)

So, how does this apply to HTTP, and how can it be implemented in practice? HTTP is oriented around verbs and resources. The two verbs in mainstream usage are GET and POST, which I think everyone will recognize. However, the HTTP standard defines several others such as PUT and DELETE. These verbs are then applied to resources, according to the instructions provided by the server.

Maven Dependency

To start, let’s add required Maven dependencies in our project. We will be using Spring Boot related dependencies here.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.1.RELEASE</version>
    <relativePath/>
</parent>
<dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
</dependencies>

Main Class

The advantage of using Spring Boot is that we get up and running with Spring framework and a working RESTful service in less than 15 minutes.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AvoidErrorsApp {
  public static void main(String[] args) {
  SpringApplication.run(AvoidErrorsApp.class, args);
 }
}

This is a simple class with a main method which we can run and start easily. Let us break above program into parts:

@SpringBootApplication is a convenience annotation that adds all of the following:
  • @Configuration tags the class as a source of bean definitions for the application context.
  • @EnableAutoConfiguration tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.
  • Normally you would add @EnableWebMvc for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath. This flags the application as a web application and activates key behaviors such as setting up a DispatcherServlet.
  • @ComponentScan tells Spring to look for other components, configurations, and services in the hello package, allowing it to find the controllers.

The main() method uses Spring Boot’s SpringApplication.run() method to launch an application. Did you notice that there wasn’t a single line of XML? No web.xml file either. This web application is 100% pure Java and you didn’t have to deal with configuring any plumbing or infrastructure.

Controller

Let is start by writing a very simple controller, describing a RESTful service which returns plain text.

import org.springframework.web.bind.annotation.RestController;

@RestController 
public class HelloController {

@RequestMapping("/") 
public String hello() { 
  return "Hello World"; 
}

The @RequestMapping annotation ensures that HTTP requests to /are mapped to the hello() method.

A key difference between a traditional MVC controller and the RESTful web service controller above is the way that the HTTP response body is created. Rather than relying on a view technology to perform server-side rendering of the greeting data to HTML, this RESTful web service controller simply populates and returns a String object. The object data will be written directly to the HTTP response as JSON.

Literally, we are done with our RESTful service. In just that amount of code, we can run our Spring Boot application to see our result.

The Controller implementation is non-public because it receives HTTP requests from the Spring front controller, the DispatcherServlet and simply delegates them forward to a service layer. If there is no use case where the controller has to be injected or manipulated through a direct reference, then we should not declare it as public.

Why Spring Boot?

Using and choosing Spring Boot over Spring MVS can have huge advantages for you when you start a project. Let us list them down here:

  • Boot is the “future of Spring”. With this words, I want to say that with Boot you can benefit of many commitments of the Spring community, most of the Spring projects today are completely integrated with Boot.
  • With Spring Boot you can benefit of very nice and useful feature such as actuator and remote shall for managing and monitoring, that improves your application with production ready feature very useful.
  • Very nice and powerful properties and configuration controls, we can configure our application with application.properties/yml and extends the boot in a very simple and impressive way, even the managements in term of overriding is very powerful.
  • It is one of the first micro-service ready platform, and in my opinion today is the best, but even if you don’t build a micro-service projects with boot you can benefit of using a modern approach in which you have a auto-consistent jar that can benefit of all the features that I described above, or if you prefer you can impose the packaging as a classical war and deploy your war in any of the container that you want.
  • Spring Initialiser is a cool tool attainable at the link: https://start.spring.io/ is a very cool tool just to create your project in a very fast way.

With those points down the belt.

Conclusion

This article shows how to implement and configure a REST Service using Spring Boot.

It is important to get the web services right and introduce 100% REST behaviour in them to ensure they perform fast and error-free.

Leave a Reply