Spring Boot RestTemplate POST 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.

<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.
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.

@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 the given example, I will first write the rest API code and then unit test which invokes the rest API and verifies API response.

4.1. Spring RestTemplate postForEntity() Example

4.1.1. REST API Code
@PostMapping(path= "/", consumes = "application/json", produces = "application/json")
public ResponseEntity<Object> addEmployee(@RequestBody Employee employee) throws Exception 
{       
    //
}
4.1.2. Junit Test
@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. Spring RestTemplate POST with Headers Example

4.2.1. REST API Code
@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
@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
@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.

@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 post with headers and body example.

Happy Learning !!

References:

SpringBootTest Java Doc
LocalServerPort Java Doc
Spring Test Java Doc

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

9 thoughts on “Spring Boot RestTemplate POST Example”

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.