Overview
In this tutorial, we show you how to create a RESTful Web Service CRUD Operations with Spring Boot Example. We create a UserController with @RestController, and map requests (HTTP request methods GET, POST, PUT, DELETE) with request mapping annotations @GetMapping, @PostMapping, @PutMapping, @DeleteMapping.Follow the steps mentioned below to build the Spring Boot RESTFul Web Services CRUD Example.
Tools and technologies used for this application
- Eclipse Oxygen and Install Spring Tool Suite for Eclipse IDE
- Spring Boot v2.0.1.RELEASE
- spring-boot-starter-web
- Java 1.8+
- Postman
Project Structure
Review the following Spring Boot RESTFul Web Services project structure.Creating a web application with Spring Boot
Launch Eclipse IDE. Go to File -> New -> Other... Select Spring Starter Project under Spring Boot category then click Next as shown belowIn the next screen, you enter the content as shown below then click Next
In the next step, you choose Spring Boot Version is 2.0.1 and choose the Web, then click Finish.
Maven Dependencies
The pom.xml file will have the following code<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jackrutorial</groupId> <artifactId>SpringBootWithRESTFulWebService</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>SpringBootWithRESTFulWebService</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <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-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
Model
Create a Customer class under com.jackrutorial.model package with the following contents.package com.jackrutorial.model; public class Customer { private int id; private String name; private String email; private String description; public Customer() { super(); } public Customer(int id, String name, String email, String description) { super(); this.id = id; this.name = name; this.email = email; this.description = description; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
Create the Customer Service
Create a CustomerService interface under com.jackrutorial.service package with the following contents.package com.jackrutorial.service; import java.util.List; import com.jackrutorial.model.*; public interface CustomerService { public List<Customer> getAllCustomer(); public Customer getCustomerById(int id); public Customer addCustomer(Customer customer); public void updateCustomer(Customer customer); public void deleteCustomer(int id); }Create a CustomerServiceImpl class implements CustomerService interface under com.jackrutorial.service package with the following contents.
package com.jackrutorial.service; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.springframework.stereotype.Component; import com.jackrutorial.model.Customer; @Component public class CustomerServiceImpl implements CustomerService { private static List<Customer> customers = new ArrayList<>(); static { Customer jack1 = new Customer(1, "Jack Rutorial 1", "admin@jackrutorial.com", "This is a Jack 1"); Customer jack2 = new Customer(2, "Jack Rutorial 2", "support@jackrutorial.com", "This is a Jack 2"); Customer jack3 = new Customer(3, "Jack Rutorial 3", "test@jackrutorial.com", "This is a Jack 3"); customers.add(jack1); customers.add(jack2); customers.add(jack3); } @Override public List<Customer> getAllCustomer() { return customers; } @Override public Customer getCustomerById(int id) { for(Customer customer : customers) { if(customer.getId() == id) { return customer; } } return null; } @Override public Customer addCustomer(Customer customer) { Random random = new Random(); int nextId = random.nextInt(1000) + 10; customer.setId(nextId); customers.add(customer); return customer; } @Override public void updateCustomer(Customer customer) { for(Customer oldCustomer : customers) { if(oldCustomer.getId() == customer.getId()) { oldCustomer.setName(customer.getName()); oldCustomer.setEmail(customer.getEmail()); oldCustomer.setDescription(customer.getDescription()); } } } @Override public void deleteCustomer(int id) { for(Customer c : customers) { if(c.getId() == id) { customers.remove(c); break; } } } }
Customer Controller
Create a CustomerController class under com.jackrutorial.controller package with the following contents.package com.jackrutorial.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.UriComponentsBuilder; import com.jackrutorial.model.Customer; import com.jackrutorial.service.CustomerServiceImpl; @RestController public class CustomerController { @Autowired private CustomerServiceImpl customerService; @GetMapping("/customer/") public List<Customer> getAllCustomer(){ return customerService.getAllCustomer(); } @GetMapping("/customer/{customerId}") public Customer getCustomerById(@PathVariable int customerId) { return customerService.getCustomerById(customerId); } @PostMapping("/customer/") public ResponseEntity<Void> addCustomer(@RequestBody Customer newCustomer, UriComponentsBuilder builder){ Customer customer = customerService.addCustomer(newCustomer); if(customer == null) { return ResponseEntity.noContent().build(); } HttpHeaders headers = new HttpHeaders(); headers.setLocation(builder.path("/customer/{id}").buildAndExpand(customer.getId()).toUri()); return new ResponseEntity<Void>(headers, HttpStatus.CREATED); } @PutMapping("/customer/") public ResponseEntity<Customer> updateCustomer(@RequestBody Customer customer){ Customer c = customerService.getCustomerById(customer.getId()); if(c == null) { return new ResponseEntity<Customer>(HttpStatus.NOT_FOUND); } c.setName(customer.getName()); c.setEmail(customer.getEmail()); c.setDescription(customer.getDescription()); customerService.updateCustomer(c); return new ResponseEntity<Customer>(c, HttpStatus.OK); } @DeleteMapping("/customer/{customerId}") public ResponseEntity<Customer> deleteCustomer(@PathVariable int customerId){ Customer c = customerService.getCustomerById(customerId); if(c == null) { return new ResponseEntity<Customer>(HttpStatus.NOT_FOUND); } customerService.deleteCustomer(customerId); return new ResponseEntity<Customer>(HttpStatus.NO_CONTENT); } }
- HTTP GET request to /customer/ returns a list of all customers
- HTTP GET request to /customer/{customerId} returns the customer with {customerId}
- HTTP POST request to /customer/ with a customer object in JSON creates a new customer
- HTTP PUT request to /customer/ with a customer object in JSON updates the customer with {customerId}
- HTTP DELETE request to /customer/{customerId} deletes the customer with {customerId}
Deploy and Test Spring Boot RESTFul Web Services using Postman
Use the following steps to build, deploy and run application.Right click to the Project and follow the below steps:
select Run As -> Maven clean.
select Run As -> Maven install.
select Run As -> Spring Boot App.
INFO 21268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/customer/],methods=[GET]}" onto public java.util.List<com.jackrutorial.model.Customer> com.jackrutorial.controller.CustomerController.getAllCustomer() INFO 21268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/customer/{customerId}],methods=[GET]}" onto public com.jackrutorial.model.Customer com.jackrutorial.controller.CustomerController.getCustomerById(int) INFO 21268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/customer/],methods=[POST]}" onto public org.springframework.http.ResponseEntity<java.lang.Void> com.jackrutorial.controller.CustomerController.addCustomer(com.jackrutorial.model.Customer,org.springframework.web.util.UriComponentsBuilder) INFO 21268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/customer/],methods=[PUT]}" onto public org.springframework.http.ResponseEntity<com.jackrutorial.model.Customer> com.jackrutorial.controller.CustomerController.updateCustomer(com.jackrutorial.model.Customer) INFO 21268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/customer/{customerId}],methods=[DELETE]}" onto public org.springframework.http.ResponseEntity<com.jackrutorial.model.Customer> com.jackrutorial.controller.CustomerController.deleteCustomer(int) INFO 21268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest) INFO 21268 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) INFO 21268 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] INFO 21268 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] INFO 21268 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup INFO 21268 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' INFO 21268 --- [ main] ringBootWithRestFulWebServiceApplication : Started SpringBootWithRestFulWebServiceApplication in 2.64 seconds (JVM running for 4.546)
We will use the Postman tool to test the RESTFul Web Services CRUD.
GET All Customer APIRequest Method: GET
URL: http://localhost:8080/customer/
GET Customer By ID API
Request Method: GET
URL: http://localhost:8080/customer/1
POST Add Customer API
Request Method: POST
URL: http://localhost:8080/customer/
PUT Update Customer API
Request Method: PUT
URL: http://localhost:8080/customer/
DELETE Customer API
Request Method: DELETE
URL: http://localhost:8080/customer/2