|
| 1 | +# SpringBoot and External API |
| 2 | + |
| 3 | +- In Spring Boot, you can call external APIs using the `RestTemplate` (for older versions) or `WebClient` (a newer alternative). |
| 4 | + |
| 5 | +## `RestTemplate` |
| 6 | + |
| 7 | +- `RestTemplate` is a class provided by the Spring Framework that simplifies the process of making HTTP requests and handling responses. It abstracts away much of the boilerplate code typically associated with making HTTP calls, making it easier to interact with RESTful web services. |
| 8 | +- So here we will be calling external API, by calling our api end points. Here as an external API we will be using [JSON Placeholder](https://jsonplaceholder.typicode.com/) which provides fake data by consuming its API. |
| 9 | +- Lets see when we hit [`https://jsonplaceholder.typicode.com/posts`](https://jsonplaceholder.typicode.com/posts) what we get in response? |
| 10 | + |
| 11 | + |
| 12 | + |
| 13 | +- We get list of post in a JSON format. Now to call this external api via spring boot first we need to download its dependencies |
| 14 | + |
| 15 | +``` |
| 16 | + <dependency> |
| 17 | + <groupId>org.springframework.boot</groupId> |
| 18 | + <artifactId>spring-boot-starter-web</artifactId> |
| 19 | + </dependency> |
| 20 | +``` |
| 21 | + |
| 22 | +- After that we need to configure `RestTemplate` in our Java Configuration. |
| 23 | + |
| 24 | +``` |
| 25 | +package com.api.api; |
| 26 | +import org.springframework.context.annotation.Bean; |
| 27 | +import org.springframework.context.annotation.Configuration; |
| 28 | +import org.springframework.web.client.RestTemplate; |
| 29 | +
|
| 30 | +@Configuration |
| 31 | +public class ApiConfiguration { |
| 32 | + @Bean |
| 33 | + public RestTemplate restTemplate() { |
| 34 | + return new RestTemplate(); |
| 35 | + } |
| 36 | +} |
| 37 | +``` |
| 38 | + |
| 39 | +- Now we need to create a simple rest controller which will be calling the external api json placeholder. |
| 40 | + |
| 41 | +``` |
| 42 | +package com.api.api; |
| 43 | +
|
| 44 | +import org.springframework.beans.factory.annotation.Autowired; |
| 45 | +import org.springframework.web.bind.annotation.GetMapping; |
| 46 | +import org.springframework.web.bind.annotation.RestController; |
| 47 | +import org.springframework.web.client.RestTemplate; |
| 48 | +
|
| 49 | +@RestController |
| 50 | +public class ExternalApiCall { |
| 51 | +
|
| 52 | + @Autowired |
| 53 | + private RestTemplate restTemplate; |
| 54 | +
|
| 55 | + @GetMapping("/restTemplate/get") |
| 56 | + public String getJsonData() { |
| 57 | + String url = "https://jsonplaceholder.typicode.com/posts/"; |
| 58 | + return restTemplate.getForObject(url, String.class); |
| 59 | + } |
| 60 | +} |
| 61 | +``` |
| 62 | + |
| 63 | +- Here we will be calling the segment path `/restTemplate/get` which will be calling `https://jsonplaceholder.typicode.com/posts/`. Lets run the application. When we hit `http://localhost:8080/restTemplate/get` end point we can see list of post as the json response. |
| 64 | + |
| 65 | + |
| 66 | + |
| 67 | +- `getForEntity()` or `getForObject()` sends a **GET** request to uri `https://jsonplaceholder.typicode.com/posts/` to fetch data from the server. Retrieves the response, either as a `ResponseEntity` or as the response body directly. |
| 68 | +- The above was an example to retrieve data or get data, now lets see an example of post request. To send **POST** request we need to first form the required data which will be accepted by the server, so json placeholder opens an endpoint where we can **POST** below kind of data on its end point `https://jsonplaceholder.typicode.com/posts` |
| 69 | + |
| 70 | + |
| 71 | +``` |
| 72 | +{ |
| 73 | + id: 1, |
| 74 | + title: 'foo', |
| 75 | + body: 'bar', |
| 76 | + userId: 1 |
| 77 | +} |
| 78 | +``` |
| 79 | + |
| 80 | +- So below is the implementation using `RestTemplate`. |
| 81 | + |
| 82 | +``` |
| 83 | + @PostMapping("/restTemplate/post") |
| 84 | + public String postJsonData(@RequestBody String requestBody) { |
| 85 | + HttpHeaders headers = new HttpHeaders(); |
| 86 | + headers.setContentType(MediaType.APPLICATION_JSON); |
| 87 | +
|
| 88 | + HttpEntity<String> request = new HttpEntity<>(requestBody, headers); |
| 89 | +
|
| 90 | + ResponseEntity<String> response = restTemplate.postForEntity("https://jsonplaceholder.typicode.com/posts", request, String.class); |
| 91 | + return response.getBody(); |
| 92 | + } |
| 93 | +``` |
| 94 | + |
| 95 | +- When we run the application and hit the `/restTemplate/post` it will post the data in the `https://jsonplaceholder.typicode.com/posts` server. |
| 96 | + |
| 97 | + |
| 98 | + |
| 99 | +- `postForEntity()` or `postForObject()` sends a POST request to the specified URL. Submits a request body (typically JSON or form data) to the server. Returns the response, either as a `ResponseEntity` (with status, headers, body) or as the response body directly. |
| 100 | +- `HttpHeaders` represents the HTTP headers to be included in the request. Allows you to set headers like Content-Type, Authorization, and custom headers. Here we have set content type as |
| 101 | + |
| 102 | +``` |
| 103 | + headers.setContentType(MediaType.APPLICATION_JSON); |
| 104 | +``` |
| 105 | + |
| 106 | +- Alternatively we can add more content headers like below |
| 107 | + |
| 108 | +``` |
| 109 | +HttpHeaders headers = new HttpHeaders(); |
| 110 | +headers.set("Content-Type", "application/json"); |
| 111 | +headers.set("Authorization", "Bearer your_token"); |
| 112 | +``` |
| 113 | + |
| 114 | +- `HttpEntity` represents the entire HTTP request body, including |
| 115 | + - Headers: Metadata about the request (e.g., content type, authentication). |
| 116 | + - Body: The actual data to send (e.g., JSON, form data). |
| 117 | +- It combines headers and body into a single object for easier handling in methods like `postForEntity`. The `HttpEntity` encapsulates the `requestBody` and `headers` into one object to pass to the RestTemplate method. |
| 118 | +- Whats the difference between `postForEntity()` and `postForObject()` ? `postForEntity` gives you more information (headers, status), while `postForObject` gives only the body. |
| 119 | +- Now lets see an example of `DELETE`. |
| 120 | + |
| 121 | +``` |
| 122 | + @DeleteMapping("/restTemplate/delete/{id}") |
| 123 | + public String deleteJsonData(@PathVariable String id) { |
| 124 | + String url = "https://jsonplaceholder.typicode.com/posts/"+id; |
| 125 | + restTemplate.delete(url); |
| 126 | + return id+" is delete"; |
| 127 | + } |
| 128 | +``` |
| 129 | + |
| 130 | +- Output |
| 131 | + |
| 132 | + |
| 133 | + |
| 134 | +- `delete(url)` sends a DELETE request without returning any response body |
| 135 | +- Lets learn about [SpringBoot without Maven](https://github.com/codophilic/LearnSpringBoot/blob/main/SpringBoot%20Without%20Maven.md) |
| 136 | + |
| 137 | + |
| 138 | + |
| 139 | + |
| 140 | + |
| 141 | + |
| 142 | + |
0 commit comments