How to create an API in Spring Boot

We have already seen what Spring Framework and Spring Boot are and how to create a Spring Boot application using Spring initializer, we will create an API in Spring Boot and see how we can get the details using SpringBoot RestController.

We can refer to the same Spring Boot project we created in the previous blog and will make a controller class as shown below.

Note that we are using @RestController for Rest API. Here we will create a simple get method which will return “Welcome to Ugtworld” when called.

The code for the Rest API is as follows.

We scan the controller class we need to add @ComponentScan to our Spring Boot main class as shown in the below image.

Once changes are done we can Run the spring boot main class as a Java Application and once Tomcat is started we will get the default port 8080.

We can access our API as below.

We can skip the @RequestMapping(“/test”) code then our URL will change as shown. 

If we are skipping the @RequestMapping(“/test”) but want to keep the same URL then we can update the get mapping values below.

We can also change the default port of Tomcat to another port by using spring boot application properties.

In the resources folder of our Spring Boot project. We have an application.properties file created as shown in the below image.

In this properties file, we can add the server.port property for Tomcat Port as shown below to update the 

default port 8080 to 8085 user-defined new port.

Once the port is updated restart the application. We can see from the console logs that the Tomcat port is updated to 8085 as shown below.

Our URL will also be updated to below.

We can also use @Controller annotation instead of @RestController but we also need to add @ResponseBody annotation at method level for Rest API.

Difference between @Controller and @RestController

@Controller@RestController
@Controller is used to create web controllers that return views, which is further resolved by a view resolver.@RestController is used to create web services  REST APIs that return JSON or XML data.
Controller annotation does not call @ResponseBody to all Controller’s method itself hence if we need to return plain text, XML, or JSON response for our API we need to add @ResponseBody annotation explicitly.RestController combines Controller and @ResponseBody, which use @ResponseBody to all its methods by default.
In @Controller, we can return a view in Spring Web MVC.In @RestController, we can not return a view.
It was added to the Spring 2.5 version.It was added to the Spring 4.0 version.

-A blog by Shwetali Khambe

Related Posts