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 the request body along with request headers using postForEntity() method.

1. Setup

We are using the code base of Spring boot REST example. The POST API is given below.

  • It adds an employee to the employee’s collection.
  • It accepts employee data in Employee object.
  • It accepts and creates JSON media type.
  • It accepts two HTTP headers i.e. X-COM-PERSIST and X-COM-LOCATION. The first header is required and the second header is optional.
  • It returns the location of the resource created.
@PostMapping(value = "/employees", 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 {
       
  Integer id = employeeDao.getAllEmployees().getEmployeeList().size() + 1;
  employee.setId(id);
   
  employeeDao.addEmployee(employee);
   
  URI location = ServletUriComponentsBuilder.fromCurrentRequest()
                              .path("/{id}")
                              .buildAndExpand(employee.getId())
                              .toUri();
   
  return ResponseEntity.created(location).build();
}

2. 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 the API response.

2.1. A Simple POST API with Request Body

We can use postForEntity(), postForEntity() or postForLocation() methods for posting the JSON request

POST API to Consume

@PostMapping(path= "/", consumes = "application/json", produces = "application/json")
public ResponseEntity<Object> addEmployee(@RequestBody Employee employee) throws Exception 
{       
    //
}

Using RestTemplate.postForEntity()

The postForEntity() method returns a ResponseEntity that can be used to check the response status, headers and body.

RestTemplate restTemplate = new RestTemplate();
URI uri = new URI("http://localhost:" + randomServerPort + "/employees/");

Employee employee = new Employee("Adam", "Gilly", "test@email.com");

ResponseEntity<Employee> result = restTemplate.postForEntity(uri, employee, Employee.class);

Assertions.assertEquals(201, result.getStatusCodeValue());
Assertions.assertNotNull(result.getBody().getId());

Using RestTemplate.postForObject()

The postForObject() API returns only the response body.

Employee createdEmployee = restTemplate.postForObject(uri, employee, Employee.class);

Assertions.assertNotNull(createdEmployee.getId());

Using RestTemplate.postForLocation()

The postForLocation() API returns only the location of the created resource that we can use in the future to fetch the resource representation if needed.

URI createdEmployeeURL = restTemplate.postForLocation(uri, employee);

Assertions.assertNotNull(createdEmployeeURL);

2.2. Sending HTTP Headers

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 
{       
    //
}

Sending Headers with RestTemplate

To send the request headers with the request, we need to create an HttpEntity object, set HttpHeaders and post it to API.

To set the ACCEPT and Content-Type headers, we can use the inbuilt methods of HttpHeaders.

HttpHeaders headers = new HttpHeaders();

headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

Similarly, we send the basic auth credentials using the headers.setBasicAuth() method:

headers.setBasicAuth("username", "password");

To set the custom headers, use its HttpHeaders.set() method:

URI uri = new URI("http://localhost:"+randomServerPort+"/employees/");
Employee employee = new Employee("Adam", "Gilly", "test@email.com");

HttpHeaders headers = new HttpHeaders();
headers.set("X-COM-PERSIST", "true");
headers.set("X-COM-LOCATION", "USA");

HttpEntity<Employee> httpEntity = new HttpEntity<>(employee, headers);

ResponseEntity<String> result = restTemplate.postForEntity(uri, httpEntity, String.class);

Assertions.assertEquals(201, result.getStatusCodeValue());

2.3. Handling Bad Request – Missing Required Header

REST API

@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 
{       
    //
}

Verify Bad Request Status

Do not pass the mandatory header X-COM-PERSIST. It shall return the response code 400 with a message that the request header is missing.

RestTemplate restTemplate = new RestTemplate();

URI uri = new URI("http://localhost:"+randomServerPort+"/employees/");
Employee employee = new Employee("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);

Assertions.assertEquals(400, result.getStatusCodeValue());

Let me know if you have a query in this Spring RestTemplate POST with headers and body examples.

Happy Learning !!

Sourcecode Download

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode