Consume External API Spring-Boot

Mercy Jemosop
5 min readJan 14, 2022

Call another API from your end-point using http-request,webClient and RestTemplate in spring-boot.

INTRODUCTION

Source:HttpRequest

There several ways of consuming an API from your end-point including Rest template, WebClient or HttpRequest. In this tutorial we are going to see all the scenarios then you can decide which is good for your project.

HttpRequest, click on the link above to access the HttpRequest github code.

We are going to get countries API data from countriesnow

Here is a link to fake API you can practice with.

WebClient

This is an interface representing the main entry point for performing web requests. It’s part of the spring web reactive module, you can use it to replace RestTemplate in scenarios where, RestTemplate is not applicable.

Advantage

  • It is a reactive, non-blocking solution that works over the Http/1.1 protocol.
  • It supports both synchronous and asynchronous operation hence suitable for applications running on a servlet stack.

The dependencies required to use web-client

Step 1.

Add the dependency below to your pom.xml. Here is a github link to my Pom.xm

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency

Step 2.

Build a client using the DefaultWebClientBuilder class which allows full customization.

I will use the Get cities and their population data endpoint from cities and country API click this link to get the endpoint.

https://countriesnow.space/api/v0.1/countries/population/cities

The data from the endpoint will look like:

you can check the format of the data you are looking for and create a model from it. You can just pick the first items and generate a model from it. Use the jsontopojo online formatter to autogenerate the model. Copy the content above and paste it on the Jsonschema2pojo.

Step 3: Generating Model

if you don’t have a model class from. Here is a link to generate a model class from a Json response.

Step 4:Web Client Custom Configuration

DataBufferLimitException: Exceeded limit on max bytes to buffer webflux error.

The ExchangeStrategies are used to resolve the above error since most codecs are limited to 256K by default. This calculates a new limit.

WebClient.builder() is the builder method to create webClient instance. This is reusable: you can create one instance at one class that can be used to instantiate multiple web client instance when required.

Step 5: Custom Web Service

We pass the Model Class here, you can also pass the String.java class instead of the Model class if you don’t have any. The retrieve()/exchange() methods are used to retrieve data, it makes an http request and retrieves a response body directly. The ClientResponse with the status and header.

  • The retrieve() method contain the bodyToFlux()(retrieve many items) and bodyToMono()(retrieve 0 or 1 item) method, it is mostly when response body entity is important.If no response content is expected, use bodyToMono(Void.class).
  • The exchange() method returns a ClientResponse with all the response elements : status, headers, response body.

Step 6:

In our Controller we call our method we defined in

HttpRequest

Step 1: Create GET countries controller

Create a util package/folder with HttpRequest class (you place it in any folder, in my case I created a util folder for custom file).

Step 2: Create HttpRequest class in your project.

Click the link below for the HttpRequest code.

HttpRequest

Step 3: Run the code to get a list of countries

Rest template

N.B Before you get started with RestTemplate have a look at webClient


One of the main differences between RestTemplate and WebClient is RestTemplate is synchronous and blocking i.e. when you do a rest call you need to wait till the response comes back to proceed further.

But WebClient is complete opposite of this. The caller need not wait till response comes back. Instead he will be notified when there is a response.

If you need such a functionality, then yes you need to replace your Resttemplate with WebClient.
You can in fact achieve Rest template like synchronous processing in webclient using .block(). But the other way is not possible.

source

The Rest Template is the central Spring class used to create applications that consume RESTful Web Services. You can use the methods available in the Rest Template class to consume the web services for all HTTP methods.

Step 1: Create a controller to call external API. Import the RestTemplate to your machine.

Step 2: Run the application to call the external API

POST Request to External API

Idontcarebro I have used a request body to pass parameters not sure if it will apply to your question.

POST request is used to send data to the server to create or update a resource. The data sent to the server is stored in the request body of http request.

we use the @PostMapping annotation to indicate a Post method. I have used the airline fake API for this demo

REST TEMPLATE POST REQUEST

We create a request body(Model to pass data(parameters) to the endpoint)

The model above will be passed to the request body with the annotation @RequestBody which allows you to retrieve the request body(model).

The main/Application class

@SpringBootApplication
public class HttprequestApplication {

@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(HttprequestApplication.class, args);
}

}

To your application properties add the properties below

#Spring Unknown property settings
spring.jackson.serialization.fail-on-empty-beans=false

HTTPREQUEST POST REQUEST

Here is a link on ObjectMapper, hope it will be helpful.

Sending our Post request in postman.

The Request is the same for both RestTemplate and HttpRequest.

{  "id": 128116,
"name": "Rwanda Airways",
"country": "Rwanda",
"logo": "https://upload.wikimedia.org/wikipedia/en/thumb/9/9b/Qatar_Airways_Logo.svg/sri_lanka.png",
"slogan": "From Rwanda",
"head_quaters": "Rwanda",
"website": "www.tzairways.com",
"established": "1979"
}

N.B in both the RestTemplate and HttpRequest, we have logged the status code to confirm if the request was success (200 status) is always a success.

You can get all the airlines to confirm if your post request was successful, this method is not always efficient and it is time consuming. Using the status code is always the best.

complete github code.

Do more research on what will work out for you. Any addition or correction are welcome.

Happy coding!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

--

--

Mercy Jemosop

Software Developer. I am open to job referrals. connect with me on twitter @kipyegon_mercy