Rest Template in Spring Boot

Posted By : Amit Maurya | 27-Jan-2021

Rest Template is used to create applications that consume RESTful Web Services. Here we will use Spring Boot to create Rest Template which will consume a RestApi.  Here we will map Rest Template to all CRUD (Create, Read, Update, Delete) operations in the Rest API. In this, we will also use validation to check if the data we accepting is valid or not. 

 

First of all, we need to create a Spring Boot Project and import the below dependency.

1. Spring Web

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-web</artifactId>

        </dependency>

 

2. Spring Validation

        <dependency> 

            <groupId>org.springframework.boot</groupId> 

            <artifactId>spring-boot-starter-validation</artifactId> 

        </dependency>

 

Here we have created a getTemplate method in the application class and annotate it with @Bean.

@SpringBootApplication

public class RestApiTemplateApplication {

 @Bean

    public RestTemplate getRestTemplate() {

        return new RestTemplate();

    }

    public static void main(String[] args) {

        SpringApplication.run(RestApiTemplateApplication.class, args);

    }

}

 

Also Read: Spring security basics

 

Here we have created a DTO (Data Transfer Object). Here we have used @NotNull annotation which is used for validation. If any of the blocks will be null it will through a Validation failed exception.

public class EmployeeDTO {

    private Integer id;

    @NotNull(message = "first name is null")

    private String firstname;

    @NotNull(message = "last name is null")

    private String lastname;

    @NotNull(message = "email is null")

    @Email(message = "invalid email address")

    private String email;

    @NotNull(message = "salary is null")

    private Integer salary;

    @NotNull(message = "department is null")

    private String department;

    //All the Getters and Setters.

}

 

 

Here we have created a controller that will map all the requests and responses. Here we are using the exchange() method of rest template. It executes the HTTP method to the given URI template by sending the given HttpEntity to the request while returning the response as ResponseEntity.

 

1. GET mapping to get all employees. Here we are calling the Get method of Restful web service. 

@GetMapping("/template/employees")
    public ResponseEntity<?> getEmployees() {
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<Object> entity = new HttpEntity<Object>(headers);
        try {
            ResponseEntity<?> response = restTemplate.exchange(
                     "http://localhost:8080/employees", HttpMethod.GET, entity, EmployeeDTO[].class);
            if(response!=null) {
                response.getBody();
                return response;
            }
            else {
                return new ResponseEntity<>("Data not Available", HttpStatus.OK);
            } 
        }
        catch(Exception e) {
            return new ResponseEntity<>("Unable to connect", HttpStatus.BAD_REQUEST);
        }
    }

 

Also Read: Profiles in Spring Boot

 

2. GET Mapping to get employee by Id. Here we are accepting an id calling Get method of the Restful web service with that id.

@GetMapping("/template/employee/{id}")
    public ResponseEntity<?> getEmployee(@PathVariable String id) {
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<Object> entity = new HttpEntity<Object>(headers);
        
        try {
            ResponseEntity<?> response = restTemplate.exchange(
                     "http://localhost:8080/employee/"+id, HttpMethod.GET, entity, String.class);
            if(response!=null) {
                response.getBody();
                return response;
            }
            else {
                return new ResponseEntity<>("Data not Available", HttpStatus.OK);
            }
        }
        catch(Exception e) {
            return new ResponseEntity<>("Unable to connect", HttpStatus.BAD_REQUEST);
        }
    }

 

3. POST mapping. In post mapping, we have used @Valid to ensure that the input is valid or not. If the validation is failed it will throw an exception. Just next to it We have used BindingResult which will store the result of validation. Then using the if condition we are returning all the errors.

@PostMapping("/template/employee")

    public ResponseEntity<?> save(@Valid @RequestBody EmployeeDTO employee, BindingResult bindingResult) {

        //Binding Result is used to get validation result.

        if (bindingResult.hasErrors()) {

            List<String> errors = bindingResult.getAllErrors().stream().map(e -> e.getDefaultMessage()).collect(Collectors.toList());

            return new ResponseEntity<>(errors, HttpStatus.OK);

        }

        

        HttpHeaders headers = new HttpHeaders();

        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

        HttpEntity<EmployeeDTO> entity = new HttpEntity<EmployeeDTO>(employee, headers);

        

        try {

            ResponseEntity<?> response = restTemplate.exchange(

                     "http://localhost:8080/employee", HttpMethod.POST, entity, String.class);

            if(response!=null) {

                response.getBody();

                return response;

            }

            else {

                return new ResponseEntity<>("Data not Available", HttpStatus.OK);

            }

        }

        catch(Exception e) {

            return new ResponseEntity<>("Unable to connect", HttpStatus.BAD_REQUEST);

        }

    }

 

Also Read: Make Logging Easy In Spring Boot

 

4. PUT mapping. Here we are accepting an employee record with RequestBody and Id with PathVariable. Here we have used validation if the record is not valid. It will throw an error which will be stored in BindingResult.

@PutMapping("/template/employee/{id}")

    public ResponseEntity<?> update(@Valid @RequestBody EmployeeDTO employee, BindingResult bindingResult, @PathVariable String id) {

        if (bindingResult.hasErrors()) {

            List<String> errors = bindingResult.getAllErrors().stream().map(e -> e.getDefaultMessage()).collect(Collectors.toList());

            return new ResponseEntity<>(errors, HttpStatus.OK);

        }

        

        HttpHeaders headers = new HttpHeaders();

        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

        HttpEntity<EmployeeDTO> entity = new HttpEntity<EmployeeDTO>(employee, headers);

        

        try {

            ResponseEntity<?> response = restTemplate.exchange(

                     "http://localhost:8080/employee/"+id, HttpMethod.PUT, entity, String.class);

            if(response!=null) {

                response.getBody();

                return response;

            }

            else {

                return new ResponseEntity<>("Data not Available", HttpStatus.OK);

            }

        }

        catch(Exception e) {

            return new ResponseEntity<>("Unable to connect", HttpStatus.BAD_REQUEST);

        }

    }

 

5. DELETE mapping. In this, we are accepting an Id and calling the Delete method of restful web service with that id.

@DeleteMapping("/template/employee/{id}")

    public ResponseEntity<?> delete(@PathVariable String id) {

          HttpHeaders headers = new HttpHeaders();

          headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

          HttpEntity<Object> entity = new HttpEntity<Object>(headers);

          

          try {

              ResponseEntity<?> response = restTemplate.exchange(

                         "http://localhost:8080/employee/"+id, HttpMethod.DELETE, entity, String.class);

              if(response!=null) {

                    response.getBody();

                    return response;

                }

                else {

                    return new ResponseEntity<>("Data not Available", HttpStatus.OK);

                }

          }

          catch(Exception e) {

                return new ResponseEntity<>("Unable to connect", HttpStatus.BAD_REQUEST);

            }

          

    }

 

Also Read: Spring Boot Data Rest

 

Choose Oodles For SaaS App Development Services 

 

We are a 360-degree SaaS app development company that provides end-to-end software development services with a focus on next-gen technologies. Our development team specializes in using JavaScript technologies like Angular, Node, and ReactJS to build scalable, responsive, and feature-rich web applications.

About Author

Author Image
Amit Maurya

He has knowledge of Java, Spring Boot, Hibernate, JSP, MySQL and web technologies(HTML, CSS, JavaScript). He Love to learn new Technologies.

Request for Proposal

Name is required

Comment is required

Sending message..