In rest API tutorial of Spring Boot Rest API, we are going to learn spring boot rest API with example. How to create spring boot restful web service in Java.
What is rest API ? You can learn here. Let’s go through the code snippet.
We are going to use spring boot for this tutorial. If you are new to spring boot, please refer to creating first spring boot application blog.
Spring Boot Rest API @RestController:
First, we need to create a rest controller for our test case of User Object (we have created a POJO class called User). e.g. User Controller like this: Don’t worry, we will provide full source code for this tutorial at the end.
@RestController
public class UserController {----}
@RestController: annotation create rest controller for us which will handle a lot of things internally like mapping of request and response object based on type.
Then we will create one method, getUser to get the user object:
// @RequestMapping(path = "/user", method = RequestMethod.GET) alternative way
@GetMapping("/user")
public User getUser(){
return userService.getUser("1");
}
Output of the above: hit localhost:8080/user (as per your port specified)
@GetMapping
@GetMapping(“/user”) you can also use it like this @RequestMapping(path = “/user”, method = RequesrtMethod.GET)
Here, what we are doing is that we are using @GetMapping annotation which defines the mapping of request and its get call, similarly we can use @PostMapping for post method.
@GetMapping is actually shortcut of @RequestMapping(method = RequestMethod.GET) same for @PostMapping.
In the above code snippet, what we’re doing is that we mapped GET /user request to getUser() method, which will return the User whose ID is 1. Note that for simplicity we have hardcoded these IDs and some of the database calls, later we will add more functionalities in the same code.
RequestMethod is an ENUM provided by spring framework which contains Http request methods.
public enum RequestMethod {
GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE
}
Now, let’s create another get mapping which will return the list of users rather than a single user.
@GetMapping("/users")
public List<User> getUsers(){
return userService.getUsers();
}
Here, we are calling get mapping with /users, which is returning the list of users.
O/P:
What is userService here ? For this tutorial we have created a dummy service which will return the data which is mock data, later will connect service layer to DAO and get the data of users from database. Here is the code snippet of the same.
Interface UserService :
public interface UserService {
User createUser(User user);
User getUser(String userId);
List<User> getUsers();
}
UserServiceImpl:
@Service
public class UserServiceImpl implements UserService{
@Override
public User createUser(User user) {
//we are just returning dummy user here
return createDummyUser();
}
@Override
public User getUser(String userId) {
return createDummyUser();
}
private User createDummyUser(String name, String id, String address){
return new User(name,"12","TEST ADDRESS");
}
private User createDummyUser(){
return new User("SLB","12","TEST ADDRESS");
}
@Override
public List<User> getUsers() {
//later will get all these details from db/file/service, etc
ArrayList<User> users = new ArrayList<>();
users.add(createDummyUser("abc","2","test1"));
users.add(createDummyUser("tes","3","test1"));
users.add(createDummyUser("res","4","test1"));
users.add(createDummyUser("tse","5","test1"));
return users;
}
}
@Service Annotation is used to mark is as service provider class where in these classes provides some business related functionalities. Spring context will autodetect these classes when annotation based configuration and XML based configuration is used.
Creating Users: Post Mapping ():
Post mapping is used to create or generate new objects/entities. In our example, we will use it to create a user object.
@PostMapping(value = "/user")
public User getUser(@RequestBody(required = true) User user){
System.out.println("executing post user with " + user.toString());
userService.createUser(user);
return user;
}
In the above code snippet, we are using @PostMapping to create user. We are also using @RequestBody for sending user object as a part of the body of the request.
To hit this, we need to use postman. Here, is the sample request and response of the request.
Output:
Spring Boot Rest API Complete source code:
In pom.xml add below dependency:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.26</version>
<scope>provided</scope>
</dependency>
Controller:
package com.slb.spring.boot.controller;
import com.slb.spring.boot.domain.User;
import com.slb.spring.boot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class UserController {
@Autowired
UserService userService;
//@RequestMapping(path = "/user", method = RequestMethod.GET) alternative way
@GetMapping("/user")
public User getUser(){
return userService.getUser("1");
}
@GetMapping("/users")
public List<User> getUsers(){
return userService.getUsers();
}
@PostMapping("/user")
public User getUser(@RequestBody(required = true) User user){
System.out.println("executing post user with " + user.toString());
userService.createUser(user);
return user;
}
}
Service :
package com.slb.spring.boot.service;
import com.slb.spring.boot.domain.User;
import java.util.List;
public interface UserService {
User createUser(User user);
User getUser(String userId);
List<User> getUsers();
}
Service Implementation:
package com.slb.spring.boot.service;
import com.slb.spring.boot.domain.User;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class UserServiceImpl implements UserService{
@Override
public User createUser(User user) {
//we are just returning dummy user here
return createDummyUser();
}
@Override
public User getUser(String userId) {
return createDummyUser();
}
private User createDummyUser(String name, String id, String address){
return new User(name,"12","TEST ADDRESS");
}
private User createDummyUser(){
return new User("SLB","12","TEST ADDRESS");
}
@Override
public List<User> getUsers() {
//later will get all these details from db/file/service, etc
ArrayList<User> users = new ArrayList<>();
users.add(createDummyUser("abc","2","test1"));
users.add(createDummyUser("tes","3","test1"));
users.add(createDummyUser("res","4","test1"));
users.add(createDummyUser("tse","5","test1"));
return users;
}
}
User Class:
package com.slb.spring.boot.domain;
import lombok.Builder;
import lombok.Data;
@Data
public class User {
String name;
String id;
String address;
public User(String name, String id, String address) {
this.name = name;
this.id = id;
this.address = address;
}
}
Checkout GitHub for Complete Code of the tutorial.
FAQ on Spring Boot
- What Are the Advantages of Spring Boot?
- One of the main advantages of using Spring Boot is its ease in creating production-grade applications quickly and with minimal setup. This is accomplished via features like auto-configuration that remove the need for manual configuration; additionally, Spring Boot comes preloaded with features like an embedded web server and actuator endpoint that make creating production applications simple and fast.
- How Can I Begin Working With Spring Boot?
- Getting started with Spring Boot is relatively straightforward. The first step should be adding Spring Boot starter dependencies (pom.xml for Maven projects). After this step has been completed, you can then begin writing application code using its features – Spring Boot also offers numerous samples and guides online that can help get you going quickly.
- How Can I Deploy a Spring Boot Application?
- There are various ways of deploying your Spring Boot app, depending on your specific requirements. One option is packaging it as a jar file and running it using Java’s -jar command; alternatively you could deploy it directly onto a cloud platform such as Heroku or AWS; Spring Boot also provides support for containerization using Docker.
- How Can I Customize Spring Boot for My Specific Needs?
- Spring Boot offers various ways of customizing its application to fit your specific requirements. One option is using application.properties or application.yml files to set application-wide configuration properties. Another way is creating configuration classes that implement the EnvironmentPostProcessor interface so as to set configuration properties programmatically.
- How Can I Test My Spring Boot App ?
- Spring Boot offers several testing solutions, such as JUnit and Mockito. Furthermore, its Spring Boot Test framework makes writing integration tests for your application simpler with features such as auto-configuration and embedded servers making setting up test environments straightforward.