Common HTTP Operations
GET Request
There are 3 methods available in RestTemplate for GET Requests, which are getForObject, getForEntity, and exchange.
- getForObject should be used when you have an exact declaration of Java class for the same, so that the response automatically converts it to a Java object, making it convenient for straightforward use cases.
- getForEntity returns the response encapsulated into a ResponseEntity Object. It also contains HTTP status codes and headers, allowing more control over the handling of the data. Provides more flexibility over getForObject.
- exchange is the most advanced and widely used for GET requests. Using it you can access the full range of response information, including status code, headers, and the response body. Best suitable when you need to customize the request headers or non-standard response types.
Java
// We have 3 methods available for a GET using // RestTemplate in Spring Boot Application @GetMapping ( "/getForObject/allEmployees" ) public ResponseEntity<?> getCustomersUsingGetForObject() { // Using getForObject method to fetch // Customer Data from URL and automatically // convert the response into array of customer Customer[] CustomerData = restTemplate.getForObject( URI_CUSTOMER, Customer[]. class ); // Returning a Response of 200 OK along with // Customer-Data wrapped into ResponseEntity return new ResponseEntity<>(Arrays.asList(CustomerData), HttpStatus.OK); } @GetMapping ( "/getForEntity/allEmployees" ) public ResponseEntity<?> getCustomersUsingGetForEntity() { // Using getForEntity method to fetch // Customer Data from URL and automatically // recieve Customer-Data wrapped into ResponseEntity ResponseEntity<Customer[]> responseEntity = restTemplate.getForEntity(URI_CUSTOMER, Customer[]. class ); return responseEntity; } @GetMapping ( "/exchange/allEmployees" ) public ResponseEntity<?> getCustomersUsingExchange() { // Instantiate HttpHeaders to add custom properties. HttpHeaders httpHeaders = new HttpHeaders(); // set the Accept-header as APPLICATION_JSON to get the // content in JSON format httpHeaders.setAccept(Collections.singletonList( MediaType.APPLICATION_JSON)); // building a HttpEntity using HttpHeaders to // customize the request HttpEntity<String> entity = new HttpEntity<>(httpHeaders); // exchange method can be used for GET request with // cutomer headers. It returns Customer Data Wrapped // into ResponseEntity with response body, headers and // status return restTemplate.exchange(URI_CUSTOMER, HttpMethod.GET, entity, Customer[]. class ); } |
POST Request
There are two methods to call any POST API using RestTemplate, which are exchange, and postForObject.
- postForObject: It receives a response as an object. Mainly it accepts URL, request entity, and response class type as parameters making it a straightforward and easy option.
- exchange: It offers greater flexibility by allowing various customization in request and response. It accepts an HTTP method, URL, request entity, and response type as parameters, making it suitable for complex cases.
Java
// We have 2 methods available for a POST using // RestTemplate in Spring Boot Application @PostMapping ( "/postForObject/customer" ) public ResponseEntity<?> addCustomerUsingPostForObject( @RequestBody Customer) { // Sending post request to create a newCustomer using // postForObject method Customer createdCustomer = restTemplate.postForObject( URI_CUSTOMER, newCustomer, Customer. class ); // Returning a Response of 201 CREATED, indicates that a // new resource has been created. // with the created-customer wrapped into // ResponseEntity. return new ResponseEntity(createdCustomer, HttpStatus.CREATED); } @PostMapping ( "/exchange/customer" ) public ResponseEntity addCustomerUsingExchange( @RequestBody Customer newEmployee) { // Instantiate HttpHeaders to add custom properties. HttpHeaders httpHeaders = new HttpHeaders(); // set the Accept-header as APPLICATION_JSON to get the // content in JSON format httpHeaders.setAccept(Collections.singletonList( MediaType.APPLICATION_JSON)); // building a HttpEntity using HttpHeaders to // customize the request HttpEntity<Customer> entity = new HttpEntity<>(newEmployee, httpHeaders); // exchange method can be used for POST request with // custom headers, to create a new Customer // It also that new created Customer return restTemplate.exchange(URI_CUSTOMER, HttpMethod.POST, entity, Customer. class ); } |
PUT Request
There are 2 methods available in RestTemplate for PUT Requests, which are put, and exchange.
- put: It allows to update/replace a resource on the server by specifying the URL and updated Data. No extra configuration or custom handling is required.
- exchange: you can customize headers, set request parameters, and extract detailed information from the HTTP response, making it suitable for complex scenarios and advanced use cases.
Java
// for PUT we have two methods in Rest Template // for changing Customer Resource @PutMapping ( "/put/customer/{id}" ) public ResponseEntity<?> updateCustomerUsingPut( @PathVariable Integer id, @RequestBody Customer newEmployee){ // creating Map to populate all the parameters Map<String, String> params = new HashMap<>(); // adding "id" as parameter // similarly you can add Authrization token, if required. params.put( "id" , String.valueOf(id)); // Update call using RestTemplate for Customer Resource restTemplate.put(URI_CUSTOMER_ID, newEmployee, params); // Generating a response of 200 OK return new ResponseEntity( "Customer Updated with id " + id, HttpStatus.OK); } @PutMapping ( "/exchange/customer/{id}" ) public ResponseEntity<?> updateCustomerUsingExchange( @PathVariable Integer id, @RequestBody Customer newEmployee){ // set the Accept-header as APPLICATION_JSON to get the // content in JSON format HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setAccept(Collections.singletonList( MediaType.APPLICATION_JSON)); // building a HttpEntity using HttpHeaders and updated // customer object to customize the request HttpEntity<Customer> entity = new HttpEntity<>(newEmployee, httpHeaders); // sending put request using RestTemplate return restTemplate.exchange(URI_CUSTOMER + id, HttpMethod.PUT, entity, Customer. class ); } |
DELETE Request
There are 2 methods available in RestTemplate for DELETE Requests, which are delete, and exchange.
- delete: a simple way to send an HTTP DELETE request. It accepts a URL and URI variable (Optional) for requests. No customization is required.
- exchange: while handling authentication or working with APIs that require custom headers exchange is the best choice.
Java
// We have 2 methods available for a POST using // RestTemplate in Spring Boot Application @DeleteMapping ( "/delete/customer/{id}" ) public ResponseEntity deleteCustomerUsingDelete( @PathVariable Integer id){ // creating Map to populate all the parameters // for delete request Map<String, String> params = new HashMap<>(); // adding "id" as parameter // similarly you can add Authrization token, if required. params.put( "id" , String.valueOf(id)); // delete call using RestTemplate for // removing Customer Resource restTemplate.delete(URI_CUSTOMER_ID, params); // Generating a response of 200 OK return new ResponseEntity<>( "Customer deleted with id " + id, HttpStatus.OK); } @DeleteMapping ( "/exchange/customer/{id}" ) public ResponseEntity<Customer> deleteCustomerUsingExchange( @PathVariable Integer id){ // Instantiate HttpHeaders to add custom properties. HttpHeaders httpHeaders = new HttpHeaders(); // set the Accept-header as APPLICATION_JSON to get the // content in JSON format httpHeaders.setAccept(Collections.singletonList( MediaType.APPLICATION_JSON)); // building a HttpEntity using HttpHeaders to // customize the request HttpEntity<Customer> entity = new HttpEntity<>(httpHeaders); // sending put request using exchange method return restTemplate.exchange(URI_CUSTOMER + id, HttpMethod.DELETE, entity, Customer. class ); } |
Notes:
- In case you are still using Spring the you can refer Spring – RestTemplate article.
- In case you want to know the implementation of RestTemplate in a sample project please refer to this article Spring Boot Microservices Communication using RestTemplate with Example
Spring Boot – Rest Template
RestTemplate is a powerful synchronous client for handling HTTP communication in Spring Boot applications. It internally uses an HTTP client library i.e. java.net.HttpURLConnection, simplifying the process of making RESTful requests to external services and APIs, including convenience, along with integration, and flexibility for various HTTP communication. Overall in this article, we will see how to invoke external APIs using methods provided by RestTemplate in your Spring Boot Application. RestTemplate is a well-known rest client in the Spring framework to performs synchronous HTTP requests.