How to create a REST API in Spring Boot 2

This is an introduction tutorial on how to create a REST API that performs CRUD operations. It can get, add, updated and delete data.

Dependency

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

Explanation

  • “GET”: Retrieve data from the API.
  • “POST”: Send data to the API. You want to add a new object for example.
  • “UPDATE”: Update data. You want to update an existing object.
  • “DELETE”: Delete data. Delete an existing object.

API endpoints are grouped together in a class which is a “RestController”. A “RestController” class is created by using the annotation “@RestController”. For example: if you want to save products and addresses in your API, then you have to create one “RestController” class for products and one “RestController” class for addresses.
An API endpoint could load a certain product with the product id “1” from your database. API endpoints are declared by adding a “Mapping” annotation to a function which has the functionality of that API endpoint.
For example these “Mapping” annotations are available:

@GetMapping("/MY_API_URL")@PostMapping("/MY_API_URL")@PutMapping("/MY_API_URL")@DeleteMapping("/MY_API_URL")

These perform the “HTTP” operations that are mentioned above. You add one of these annotations to a function to implement the functionality of that operation.
Parameters are defined by their name in curly brackets in the “URI” and are added to the arguments of a function with the annotation “@PathVariable”. They can then be retrieved by the function.
Example:

@GetMapping("/customer/{customerId}")
public ResponseEntity<Customer> getCustomerById(@PathVariable Long id) {
...
}

If you call the API URL with any number “/customer/1”, then the function “getCustomerById” will be called. The annotation “GetMapping” maps the API url to this function and the passed id “id” to the “Long” variable “id” in the argument of this function.

If you want to send data to the “API”, then you have to use a JSON object in the “body” of the HTTP request. A “@PostMapping” annotation is used in this case. The annotation “@RequestBody” is used to map a JSON object (that is sent by the API user) to the argument variable of an API function. All communication between the API and the client is done through JSON objects.
The function of the API endpoint returns a “ResponseEntity” object which contains an object and an HTTP status code. If the “API” request was successful, then the requested object and HTTP status “200 OK” are returned.

The mentioned “Mapping” annotations have also additional arguments.
Example:

@PostMapping(path= "/save", consumes = "application/json", produces = "application/json")

The argument “consumes” defines the object data of the data type that is sent to the API”. “produces” defines the object data type that is returned by the API.

@RequestMapping(path="/users")

You can define a base path for the API endpoints of “RestController” class, by using this command.

Code Example

@RestController
public class CustomerController {
@Autowired
private CustomerService customerService;
private final String BASE_API_URL = "/api/customer";
/**
* Get all customers. HTTP GET command.
*
* @return
*/
@GetMapping(BASE_API_URL + "/all")
public ResponseEntity<List<Customer>> getAllCustomer() {
List<Customer> customerList = this.customerService.getAllCustomer();
if (!CollectionUtils.isEmpty(customerList)) {
return status(HttpStatus.OK).body(customerList);
} else {
return status(HttpStatus.BAD_REQUEST).body(new ArrayList<Customer>());
}
}
/**
* Get a customer with a certain id. HTTP GET command.
*
* @return
*/
@GetMapping(BASE_API_URL + "/get/byEmail/{email}")
public ResponseEntity<Customer> getOwnerByEmail(@PathVariable String email) {
try {
return status(HttpStatus.OK).body(this.customerService.getCustomerByEmail(email));
} catch (DataValueNotFoundException e) {
return status(HttpStatus.BAD_REQUEST).body(new Customer());
}
}
/**
* Add a customer. HTTP POST command.
* @param newCustomer
* @return
*/
@PostMapping(BASE_API_URL + "/add")
public ResponseEntity<String> addCustomer(@RequestBody Customer newCustomer) {
int resultCode = this.customerService.save(newCustomer);
switch (resultCode) {
case 0:
return ResponseEntity.ok("OK. Customer was added successfully.");
case 1:
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("ERROR. Customer cannot be null!");
case 2:
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("ERROR. Customer could not be saved!");
case 3:
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("ERROR. Customer E-Mail already exists! Please select another e-mail.");
default:
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("ERROR. Customer could not be saved!");
}
}

/**
* Update an existing customer. HTTP PUT command.
* @param id
* @param customer
* @return
*/
@PutMapping(BASE_API_URL + "/update/{id}")
public ResponseEntity<String> updateOwner(@PathVariable Long id, @RequestBody Customer customer) {
int resultCode = this.customerService.update(customer);
switch (resultCode) {
case 0:
return ResponseEntity.ok("OK. Update was successful.");
case 1:
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("ERROR. Customer cannot be null!");
case 2:
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("ERROR. Customer does not exist!");
case 3:
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("ERROR. Customer E-Mail already exists! Please select another e-mail.");
default:
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("ERROR. Update failed!");
}
}
/**
* Delete an existing customer. HTTP DELETE command.
* @param customerId
* @return
*/
@DeleteMapping(BASE_API_URL + "/delete/{id}")
public ResponseEntity<String> deleteAccountType(@PathVariable Long customerId) {
if (this.customerService.deleteById(customerId)) {
return ResponseEntity.ok("Your customer was deleted successfully.");
} else {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error. Customer does not exists!");
}
}
}

Here the API can be accessed from the base url “/api/customer” and the respective API endpoint.
For example if you would want to get all customers you would call this API URL with the “GET” HTTP command:

/api/customer/all

Documentation Spring Boot:
https://docs.spring.io/spring-boot/docs/current/api/

Download Postman:
https://www.postman.com/downloads/

Documentation Spring:
https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/

https://docs.spring.io/spring-framework/docs/current/javadoc-api/

Tutorials about Linux, Java and information about IT — https://ard-site.net

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store