How to Build a Rest API using Spring Boot

Anup Sarkar
5 min readNov 18, 2019

--

Microservices are gaining popularity day by day and Rest APIs are becoming part of most of the web or mobile applications. If you are a Java developer, then building Rest APIs using Spring boot is really easy.

Why we need Spring Boot?

Spring framework is becoming more popular nowadays but what it makes more popular is Spring Boot. Spring Boot provides a lot of inbuilt auto-configuration annotation that helps us to build a production-ready application configuration. For enterprise application development in the spring framework, it’s become very easy after the Spring Boot came into the picture as it needs a lot of configuration. For more details please refer to the official Spring Boot documentation https://spring.io/guides.

In this blog, I will explain how to build Rest APIs using Spring Boot. I will use STS IDE for the coding part as it is specially designed for spring application development whatever you can also prefer Eclipse or Visual Studio Code IDE.

How to Create a Spring Boot Project?

Please follow the below steps

Fill the required info to create a project.

Once done, click on the Finish button. Now you have successfully created a Spring Boot Application.

How Does Spring Boot Application Start?

Go to the “src/main/java” directory in your application and inside that one a default main class is created named “SpringbootRestapiApplication.java” which is the starting point of the Spring Boot application. The main() method of this class uses “SpringApplication.run()” method to launch the Spring Boot application. “SpringbootRestapiApplication.java” class use @SpringBootApplication annotation to load all the configuration for the Spring Boot app.

/*SpringbootRestapiApplication.java */package com.springboot.restapi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootRestapiApplication {
public static void main(String[] args) {SpringApplication.run(SpringbootRestapiApplication.class, args);}}

Spring Boot Application Dependencies

Now paste the following in the “pom.xml” which contain all the dependencies of the application including the Rest API dependencies.

<!--pom.xml--><?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.springboot</groupId>
<artifactId>restapi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-restapi</name>
<description>This is the test for rest API</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions><exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

How to make JSON type output for Rest APIs in Spring Boot?

In Spring-Boot, there is no direct way to get JSON type output from the Rest API. To get the JSON type response from the Rest API we have to create another class type called “APIResponse.java” inside the same package itself. During Rest API implementation we will use this “APIResponse.java” class as the return type of the Rest Controller method so that the Rest API will give us the response is in “APIResponse.java” format and that is nothing but the JSON type response.

API Response type Class for JSON Output


/* APIResponse.java */
package com.springboot.restapi;
public class APIResponse {private String status;
private String message;
public APIResponse() {}public APIResponse(String status, String message) {
this.status = status;
this.message = message;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return "APIResponse [status=" + status + ", message=" + message + "]";
}
}

Useful Annotations Details of Rest API

For building a Rest API in Spring Boot, there are some inbuild Spring Boot annotations like “@RestController”, “@RequestMapping” and “@RequestParams”.

@RestController: This annotation is used to make the class as a Rest Controller which handles the HTTP requests.
@RequestMapping: This annotation helps to map all the HTTP Request to the specified route with the Rest controller method. For example “/test-post-api” route is mapped with the Rest controller method named “postRestAPIResponse()”.
@RequestParams: This annotation is used for including any params for the Rest API.

Rest Controller Class for Rest APIs

Now create a controller class named “TestRestAPI.java” under the same package “com.springboot.restapi” for Rest API Implementation. Inside the controller class, I used both HTTP GET and POST methods to create the Rest APIs. Please refer to the below code.

/* RestAPITest.java */package com.springboot.restapi;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RestAPITest {
@RequestMapping(value = "/test-post-api")
public APIResponse postRestAPIResponse() throws Exception {
APIResponse response = new APIResponse();
response.setStatus("success");
response.setMessage("Your test API response for POST request.");
return response;
}@RequestMapping(value = "/", method = RequestMethod.GET)
public String testAPIResponse() throws Exception {
return "Your test API message.";}@RequestMapping(value = "/test-get-api", method = RequestMethod.GET)
public APIResponse getRestAPIResponse() throws Exception {
APIResponse response = new APIResponse();
response.setStatus("success");
response.setMessage("Your test API response for Get Request.");
return response;
}
}

Rest API Response Testing for HTTP GET Method

After running your application, type “http://localhost:8080/" in your browser, you will get “Your test API message.” response, as we set the return type of “testAPIResponse()” method is in String format. Please refer to the controller class “TestRestAPI.java”.

Now enter this “http://localhost:8080/test-get-api" URL in your browser, you will receive the JSON type response as we set the response type of this Rest API as “APIResponse.java” type. Please refer to the below Rest API response for HTTP GET request.

{"status":"success","message":"Your test API response for Get Request."}

Rest API Response Testing for HTTP POST Method

Now if you want to test the Rest API response for the HTTP POST method, you can use the POSTMAN app. This Rest API will also return the response in JSON format i.e in “APIResponse.java” type format. Please refer to the below screenshot of the POSTMAN app.

Conclusion:

This is the initial tutorial on Spring Boot, keep in touch for future blogs on Spring Boot and if you have any doubts about this topic, please let me know in the comments section. Also, subscribe to our newsletter for more interesting updates.

Originally published at https://blogs.tensult.com on November 18, 2019.

--

--