Saturday 18 April 2020

Spring Boot RestTemplate POST JSON Example

In this Spring Boot RestTemplate POST request test example, we will create a POST API and then test it by sending request body along with request headers using postForEntity() method.

1. Maven dependencies

Make sure to have spring-boot-starter-test dependency in the project to enable loading of spring text context, bean initialization and dependency management.
pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

2. HTTP POST API

We are using the code base of Spring boot 2 rest example. The POST API is given as below.
  1. It adds an employee in the employees collection.
  2. It accept employee data in Employee object.
  3. It accepts and creates JSON media type.
  4. It accepts two HTTP headers i.e. X-COM-PERSIST and X-COM-LOCATION. First header is required and second header is optional.
  5. It returns the location of resource created.
EmployeeController.java
package com.howtodoinjava.rest.controller;
import java.net.URI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.howtodoinjava.rest.dao.EmployeeDAO;
import com.howtodoinjava.rest.model.Employee;
import com.howtodoinjava.rest.model.Employees;
@RestController
@RequestMapping(path = "/employees")
public class EmployeeController
{
    @Autowired
    private EmployeeDAO employeeDao;
      
    @PostMapping(path= "/", consumes = "application/json", produces = "application/json")
    public ResponseEntity<Object> addEmployee(
        @RequestHeader(name = "X-COM-PERSIST", required = true) String headerPersist,
        @RequestHeader(name = "X-COM-LOCATION", defaultValue = "ASIA") String headerLocation,
        @RequestBody Employee employee)
            throws Exception
    {      
        //Generate resource id
        Integer id = employeeDao.getAllEmployees().getEmployeeList().size() + 1;
        employee.setId(id);
         
        //add resource
        employeeDao.addEmployee(employee);
         
        //Create resource location
        URI location = ServletUriComponentsBuilder.fromCurrentRequest()
                                    .path("/{id}")
                                    .buildAndExpand(employee.getId())
                                    .toUri();
         
        //Send location in response
        return ResponseEntity.created(location).build();
    }
}

3. Spring boot Test Class

A test class in Spring boot application can be written like this.
SpringBootDemoApplicationTests.java
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class SpringBootDemoApplicationTests
{   
    @LocalServerPort
    int randomServerPort;
     
    @Test
    public void testGetEmployeeListSuccess() throws URISyntaxException
    {
    
}

4. Spring RestTemplate POST Request Example

In given below example, I will first write the rest api code and then unit test which invoke the rest api and verify api response.

4.1. REST POST without headers

4.1.1. REST API Code
REST API without headers.java
@PostMapping(path= "/", consumes = "application/json", produces = "application/json")
public ResponseEntity<Object> addEmployee(@RequestBody Employee employee) throws Exception
{      
    //
}
4.1.2. Junit Test
Unit test without headers
@Test
public void testAddEmployeeWithoutHeader_success() throws URISyntaxException
{
    RestTemplate restTemplate = new RestTemplate();
     
    final String baseUrl = "http://localhost:"+randomServerPort+"/employees/";
    URI uri = new URI(baseUrl);
     
    Employee employee = new Employee(null, "Adam", "Gilly", "test@email.com");
    ResponseEntity<String> result = restTemplate.postForEntity(uri, employee, String.class);
     
    //Verify request succeed
    Assert.assertEquals(201, result.getStatusCodeValue());
}

4.2. REST POST with request headers

4.2.1. REST API Code
REST API with headers
@PostMapping(path= "/", consumes = "application/json", produces = "application/json")
public ResponseEntity<Object> addEmployee (
        @RequestHeader(name = "X-COM-PERSIST", required = true) String headerPersist,
        @RequestHeader(name = "X-COM-LOCATION", defaultValue = "ASIA") String headerLocation,
        @RequestBody Employee employee ) throws Exception
{      
    //
}
4.2.2. Junit Test
Unit test with headers
@Test
public void testAddEmployeeWithoutHeader_success() throws URISyntaxException
{
    RestTemplate restTemplate = new RestTemplate();
    final String baseUrl = "http://localhost:"+randomServerPort+"/employees/";
    URI uri = new URI(baseUrl);
    Employee employee = new Employee(null, "Adam", "Gilly", "test@email.com");
     
    HttpHeaders headers = new HttpHeaders();
    headers.set("X-COM-PERSIST", "true");   
    headers.set("X-COM-LOCATION", "USA");     
    HttpEntity<Employee> request = new HttpEntity<>(employee, headers);
     
    ResponseEntity<String> result = restTemplate.postForEntity(uri, request, String.class);
     
    //Verify request succeed
    Assert.assertEquals(201, result.getStatusCodeValue());
}

4.2. REST POST with missing header – expected error

4.2.1. REST API Code
REST API with headers
@PostMapping(path= "/", consumes = "application/json", produces = "application/json")
public ResponseEntity<Object> addEmployee (
        @RequestHeader(name = "X-COM-PERSIST", required = true) String headerPersist,
        @RequestHeader(name = "X-COM-LOCATION", defaultValue = "ASIA") String headerLocation,
        @RequestBody Employee employee ) throws Exception
{      
    //
}
4.2.2. Junit Test
Do not pass the mandatory header X-COM-PERSIST. It shall the return the response code 400 with message that request header is missing.
Unit test with missing header
@Test
public void testAddEmployeeWithoutHeader_success() throws URISyntaxException
{
    RestTemplate restTemplate = new RestTemplate();
    final String baseUrl = "http://localhost:"+randomServerPort+"/employees/";
    URI uri = new URI(baseUrl);
    Employee employee = new Employee(null, "Adam", "Gilly", "test@email.com");
     
    HttpHeaders headers = new HttpHeaders();  
    headers.set("X-COM-LOCATION", "USA");     
    HttpEntity<Employee> request = new HttpEntity<>(employee, headers);
     
    ResponseEntity<String> result = restTemplate.postForEntity(uri, request, String.class);
     
    //Verify request succeed
    Assert.assertEquals(201, result.getStatusCodeValue());
}
Let me know if you have query in this spring resttemplate postforentity with headers example.

No comments:

Post a Comment