Create REST API’s using Spring Boot
Hi All,
In this blog, we will see how we can get started with spring boot and quickly create REST api’s for our testing purpose. Below are the steps you can follow:
- Create a spring project using https://start.spring.io/ . Add Spring Web dependency. Download the jar and open in IntelliJ IDE.
2. You will see the below dependencies already added in pom.xml file.
3. Now we will create a Controller. In Spring Boot, the controller class is responsible for processing incoming REST API requests, preparing a model, and returning the view to be rendered as a response.
Create a package controller inside main. And create a new Class “UserController” inside it. Create a GET request function with @GetMapping annotation.
4. Run SpringBootApplication class file. It will start a tomcat server on default port: 8080.
5. Go to browser and open localhost:8080/user . It will return the response as below:
6. Let’s modify it further. We will now create a model for User as below. here I am using lombok to generate getters, setters and to use the Builder pattern.
Please add lombok dependency in your project.
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
7. Modify the GET request in Controller to set user properties and return user object as below:
@RestController
public class UserController {
@GetMapping("/user")
public User getUser(){
return User.builder()
.id(1)
.name("User_1")
.address("Kishor Street")
.build();
}
}
8. Run the application again and you will see the json response as below:
So, this way you can create your own API’s for testing purpose. You can explore more than this by creating POST, PUT and DELETE Api as well.
Happy Learning :)