Skip to content

Commit b33c7c7

Browse files
committed
Call External API using Spring Boot
1 parent 7f63114 commit b33c7c7

18 files changed

+758
-2
lines changed
300 KB
Loading
271 KB
Loading
263 KB
Loading
301 KB
Loading

SpringBoot REST APIs.md

+1-2
Original file line numberDiff line numberDiff line change
@@ -870,8 +870,7 @@ Hibernate: alter table book_table add constraint FKsjw4gp278w3h7t6pr4pb755hl for
870870

871871

872872
- Above learnings are implemented [here](https://github.com/codophilic/LearnSpringBoot/tree/main/SpringBoot%20REST%20APIs/restapi/src/main/java/com/springboot/rest)
873-
- Lets learn about [SpringBoot without Maven](https://github.com/codophilic/LearnSpringBoot/blob/main/SpringBoot%20Without%20Maven.md)
874-
873+
- Learn try to call [external api using spring boot](/SpringBoot%20and%20External%20API.md)
875874

876875

877876

SpringBoot and External API.md

+142
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
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+
![alt text](image.png)
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+
![alt text](image-1.png)
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+
![alt text](image-2.png)
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+
![alt text](/Images/springbootexternalapi/image-3.png)
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+
+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
/.metadata/
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
/mvnw text eol=lf
2+
*.cmd text eol=crlf
+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
HELP.md
2+
target/
3+
!.mvn/wrapper/maven-wrapper.jar
4+
!**/src/main/**/target/
5+
!**/src/test/**/target/
6+
7+
### STS ###
8+
.apt_generated
9+
.classpath
10+
.factorypath
11+
.project
12+
.settings
13+
.springBeans
14+
.sts4-cache
15+
16+
### IntelliJ IDEA ###
17+
.idea
18+
*.iws
19+
*.iml
20+
*.ipr
21+
22+
### NetBeans ###
23+
/nbproject/private/
24+
/nbbuild/
25+
/dist/
26+
/nbdist/
27+
/.nb-gradle/
28+
build/
29+
!**/src/main/**/build/
30+
!**/src/test/**/build/
31+
32+
### VS Code ###
33+
.vscode/
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Licensed to the Apache Software Foundation (ASF) under one
2+
# or more contributor license agreements. See the NOTICE file
3+
# distributed with this work for additional information
4+
# regarding copyright ownership. The ASF licenses this file
5+
# to you under the Apache License, Version 2.0 (the
6+
# "License"); you may not use this file except in compliance
7+
# with the License. You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing,
12+
# software distributed under the License is distributed on an
13+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
# KIND, either express or implied. See the License for the
15+
# specific language governing permissions and limitations
16+
# under the License.
17+
wrapperVersion=3.3.2
18+
distributionType=only-script
19+
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip

0 commit comments

Comments
 (0)