SpringBoot RestAPIs @GetMapping, @PostMapping, @DeleteMapping, @PutMapping, @PatchMapping

How to create SpringBoot RestAPIs with new features Annotations @GetMapping @PostMapping @PutMapping @PatchMapping @DeleteMapping

“How to create SpringBoot RestAPIs?” is one of the most common questions in Java development world. So in the tutorial, loizenjava.com will guide step by step how to do it with clearly explaination and pratice with running sourcecode by using a new annotation features of SpringBoot framework: @GetMapping, @PostMapping, @DeleteMapping, @PutMapping, @PatchMapping

New Annotations of SpringBoot RestApis

@GetMapping

@org.springframework.web.bind.annotation.GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).
@GetMapping is used for mapping HTTP GET requests onto specific handler methods.

Detail about @GetMapping annotation:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.GET)
public @interface GetMapping {
    //...
}

@PostMapping

@org.springframework.web.bind.annotation.PostMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.POST). It is used for mapping HTTP POST requests onto specific handler methods.

Detail about @PostMapping annotation:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.POST)
public @interface PostMapping {
    //...
}

@DeleteMapping

@org.springframework.web.bind.annotation.DeleteMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.DELETE). It is used for mapping HTTP DELETE requests onto specific handler methods.

Detail about @DeleteMapping annotation:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.DELETE)
public @interface DeleteMapping {
    //...
}

@PutMapping

org.springframework.web.bind.annotation.PutMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PUT). It is used for mapping HTTP PUT requests onto specific handler methods.

Detail about @PutMapping annotation:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.PUT)
public @interface PutMapping {
    //...
}

@PatchMapping

@org.springframework.web.bind.annotation.PatchMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PATCH). It is used for mapping HTTP PATCH requests onto specific handler methods.

Detail about @PathMapping:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.PATCH)
public @interface PatchMapping {
    //...
}

Practice: SpringBoot RestApis Development

Now we create a SpringBoot project to build RestAPIs with annotations: @GetMapping @PostMapping @PutMapping @DeleteMapping @PatchMapping

For development, we need to add a web dependency:

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

We will implement a SpringBoot project as below structure:

springboot-project-structure-for-build-restapi-with-new-annotation-features
Springboot Project Structure

We implement 5 RestApi Controllers:

  1. GetController.java implements requestmapping with @GetMapping annotation for GET requests
  2. PostController.java implements requestmapping with @PostMapping annotation for POST requests
  3. PutController.java implements requestmapping with @PutMapping annotation for PUT requests
  4. PatchController.java implements requestmapping with @PatchMapping annotation for Patch requests
  5. DeleteController.java implements requestmapping with @DeleteMapping annotation for Delete requests

Create Customer model

We create a simple Customer model class with 4 attributes: id, name, salary, birthday.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.fasterxml.jackson.annotation.JsonFormat;

public class Customer {
	private int id;
	private String name;
	private long salary;
	
	@JsonFormat(pattern="yyyy-MM-dd")
	private Date birthday;
	
	public Customer(int id, String name, long salary, Date birthday) {
		this.id = id;
		this.name = name;
		this.salary = salary;
		this.birthday = birthday;
	}
        // getters & setters

Implement CustomerStorage Bean

We implement CustomerStorage.java class to store or retrieve Customer instances when having any post/get/update/delete requests.

Springboot RestApi Tutorial - Customer Storage Implementation
Springboot RestApi Tutorial – Customer Storage Implementation
package com.loizenjava.restapis.storage;

import java.util.Calendar;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Component;

import com.loizenjava.restapis.model.Customer;

@Component("customerStorage")
public class CustomerStorage {
	
	private Map _customers = new HashMap();
	
    @PostConstruct
    public void init() throws Exception {
        Customer jack = new Customer(1, "Jack", 2100, 
        								new GregorianCalendar(1989, Calendar.JANUARY, 3).getTime());
        Customer peter = new Customer(2, "Peter", 2300, 
        								new GregorianCalendar(1993, Calendar.JUNE, 17).getTime());
        
        Customer david = new Customer(3, "David", 2600, 
				new GregorianCalendar(1985, Calendar.MAY, 22).getTime());
 
        _customers.put(jack.getId(), jack);
        _customers.put(peter.getId(), peter);
        _customers.put(david.getId(), david);
    }
	
    public void add(Customer customer) {
    	_customers.put(customer.getId(), customer);
    }
    
    public Customer get(int id) {
    	return _customers.get(id);
    }
    
    public Customer delete(int id) {
    	return _customers.remove(id);
    }

    public boolean exists(int id) {
    	if(_customers.containsKey(id)) return true;
    	return false;
    }
    
    public Collection getAll() {
    	return _customers.values();
    }   
}

Implement GetController.java

We implement GetController.java class to handle any GET Http request with @GetMapping annotation.

SpringBoot RestApi Tutorial - Get Controller
Get Controller
package com.loizenjava.restapis.controller;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.loizenjava.restapis.model.Customer;
import com.loizenjava.restapis.storage.CustomerStorage;

@RestController
@RequestMapping("/api/get")
public class GetController {

	@Autowired
	CustomerStorage customers;
	
	@GetMapping("/string")
	public String getString() {
		return "https://loizenjava.com site hello everybody!";
	}
	
	@GetMapping("/customer/{id}")
	public ResponseEntity<?> getCustomer(@PathVariable int id) {
		if(customers.exists(id)) {
			return new ResponseEntity<Customer>(customers.get(id), HttpStatus.OK);	
		} else {
			return new ResponseEntity<String>("Not found a customer with id = " + id, HttpStatus.NOT_FOUND);
		}
	}
	
	@GetMapping("/customer/all")
	public ResponseEntity<Collection<Customer>> getAllCustomers(){
		return new ResponseEntity<Collection<Customer>>(customers.getAll(), HttpStatus.OK);
	}
}
  • String getString() method handles simple http GET requests with URL /api/get/string and then returns back a simple string.
  • ResponseEntity<?> getCustomer(@PathVariable int id) method handles http GET requests with URL /api/get/customer/{id} attached a pathvariable id and then returns back a corresponding Customer entity after processing.
  • ResponseEntity<Collection<Customer>> getAllCustomers() methods handles http GET requests with URL /api/get/customer/all and then returns all Customer entities.

org.springframework.http.ResponseEntity<T> is an extension of HttpEntity that adds a HttpStatus status code. Used in RestTemplate as well @Controller methods.

Testing: GetMapping Controller

– Make a http GET request http://localhost:8080/api/get/string

springboot restapi tutorial - testing @getmapping
Testing @Getmapping – request 1

– Make a http GET request with URL code http://localhost:8080/api/get/customer/2

SpringBoot RestAPIs Tutorial - testing @GetMapping - request 2
Testing @GetMapping – get a Customer

– Make a http GET request http://localhost:8080/api/get/customer/all to get all customer entities.

SpringBoot RestApi Tutorial - Testing @GetMapping - Get All Customers
Get All Customers

– Make a http GET request to get a Customer But not found

SpringBoot RestApi Tutorial - Testing @GetMapping - GET a Customer NOT Existed
GET a Customer NOT Existed

Implement PostController.java

We implement PostController.java class to handle any http POST request with @PostMapping annotation

SpringBoot RestApis Tutorial - @PostMapping annotation Controller
@PostMapping Controller
package com.loizenjava.restapis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.loizenjava.restapis.model.Customer;
import com.loizenjava.restapis.storage.CustomerStorage;

@RestController
@RequestMapping("/api/post")
public class PostController {

	@Autowired
	CustomerStorage customers;
	
	@PostMapping("/customer")
	public ResponseEntity<Customer> postCustomer(@RequestBody Customer customer) {
		customers.add(customer);
		
		// after posting
		customers.getAll().forEach(System.out::println);
		
		return new ResponseEntity<Customer>(customer, HttpStatus.OK);
	}
}

We implement one method postCustomer(@RequestBody Customer customer) to handle http POST requests with body is a Customer and then returns back the Customer entity to client.

Testing: PostMapping Controller

Make a http POST request with URL http://localhost:8080/api/post/customer

SpringBoot RestAPI Tutorial - PostMapping Controller
Post Request

Make a http GET request to retrieve all Customers to check the posting:

SpringBoot RestApi Tutorial - Get All Customers
Get All Customers

Nancy had been added to backend. The POST request is successfully!

Implement PutController.java

We implement PutController.java class to handle any http PUT request with @PutMapping annotation

SpringBoot RestAPIs Tutorial - @PutMapping Controller
@PutMapping Controller
package com.loizenjava.restapis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.loizenjava.restapis.model.Customer;
import com.loizenjava.restapis.storage.CustomerStorage;

@RestController
@RequestMapping("/api/put")
public class PutController {

	@Autowired
	CustomerStorage customers;
	
	@PutMapping("/customer/{id}")
	public ResponseEntity<String> putCustomer(@PathVariable int id, @RequestBody Customer customer) {
		
		if(customers.exists(id)) {
			// get customer from storage
			Customer _customer = customers.get(id);
			
			// update new values
			_customer.setName(customer.getName());
			_customer.setSalary(customer.getSalary());
			_customer.setBirthday(customer.getBirthday());
			
			// save again to customer storage
			customers.add(_customer);
			
			return new ResponseEntity<String>("Update Successfully!", HttpStatus.OK);
		} else {
			return new ResponseEntity<String>("Not found customer with id = " + id, HttpStatus.NOT_FOUND);
		}
	}
}

We implement a method ResponseEntity<String> putCustomer(@PathVariable int id, @RequestBody Customer customer) to handle any http PUT request with URL path /api/put/customer/{id}.

Testing: PutMapping Controller

– Make a http PUT request to URL http://localhost:8080/api/put/customer/2 to modify the salary and birthday of Peter:

SpringBoot RestAPI Tutorial - PUT request
PUT request

– Make a http GET request to get all customers to check the modification is applied or not:

SpringBoot RestApi Tutorial - Get All Customer - Check PUT request applied or NOT
Get All Customer – Check PUT request applied or NOT

Implement PatchController.java

We implement PatchController.java class to handle any http PATCH request with @PatchMapping annotation.

SpringBoot RestAPI Tutorial - PatchMapping Controller
PatchMapping Controller
package com.loizenjava.restapis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.loizenjava.restapis.model.Customer;
import com.loizenjava.restapis.storage.CustomerStorage;

@RestController
@RequestMapping("/api/patch")
public class PatchController {

	@Autowired 
	CustomerStorage customers;
	
	@PatchMapping("/customer")
	public ResponseEntity patchSalaryUpdate(@RequestBody Customer customer){
		
		if(customers.exists(customer.getId())) {
			// get customer from storage
			Customer _customer = customers.get(customer.getId());
			
			// update new values
			_customer.setSalary(customer.getSalary());
			
			// save again to customer storage
			customers.add(_customer);
			
			return new ResponseEntity("Update Successfully!", HttpStatus.OK);
		} else {
			return new ResponseEntity("Not found customer with id = " + customer.getId()
													, HttpStatus.NOT_FOUND);
		}
	}
}

We implement a ResponseEntity<String> patchSalaryUpdate(@RequestBody Customer customer) method that is used to update just only one field salary for a Customer.

Testing: PatchMapping Controller

– Make a http PATCH request to change the salary for Jack with id = 1:

Springboot RestApi Tutorial - PatchMapping Request
PatchMapping Request

Implement DeleteController.java

We implement DeleteController.java class to handle any Http DELETE request with @DeleteMapping annotation.

SpringBoot RestAPIs Tutorial - DeleteMapping Request
DeleteMapping Request
package com.loizenjava.restapis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.loizenjava.restapis.storage.CustomerStorage;

@RestController
@RequestMapping("/api/delete")
public class DeleteController {
	
    @Autowired
    CustomerStorage customers;
    
    @DeleteMapping("/customer/{id}")
    public ResponseEntity deleteCustomer(@PathVariable int id){
    	
    	if(!customers.exists(id)) {
    		return new ResponseEntity("Not found customer with id = " + id, HttpStatus.NOT_FOUND);
    	} else {
        	// process deleting
        	customers.delete(id);
            System.out.println("customers after deleting:");
            customers.getAll().forEach(System.out::print);
     
            return new ResponseEntity("Successfully!", HttpStatus.OK);	
    	}
    }
}

Testing: DeleteMapping Controller

– Make a http Delete request to URL http://localhost:8080/api/delete/customer/3 to delete a Customer with id = 3:

SpringBoot RestAPIs Tutorial - @DeleteMapping request
@DeleteMapping request

Sourcecode

– Full sourcecode for the SpringBoot RestAPIs tutorial with new annotations @GetMapping, @PostMapping, @DeleteMapping, @PutMapping, @PatchMapping:

One thought on “SpringBoot RestAPIs @GetMapping, @PostMapping, @DeleteMapping, @PutMapping, @PatchMapping”

Leave a Reply

Your email address will not be published. Required fields are marked *