Consume RESTful API using Spring Framework’s RestClient

If your application uses Spring Framework 7 or later, you can now use the RestClient class to consume RESTful APIs. How exactly? Let’s find out in this tutorial!

For example, I will create a new Spring Boot project version 4.0.0 or later, using the Web Starter dependency as follows:

I will consume 2 APIs that I have exposed in 2 tutorials about API Versioning using request header and path parameter, guys!

For example, to keep it simple, I will also use the CommandLineRunner class so that when running the Spring Boot application, it will call the 2 APIs above using the RestClient class.

You can initialize the RestClient class object with baseURL as follows:

Suppose the RESTful API you need to consume uses API Versioning, like the example in the tutorial API Versioning using request headers with Spring framework. In that case, you can use the ApiVersionInserter class to add version information, for example, as follows:

Because the API in the tutorial API Versioning using request headers with Spring framework using headers for API versioning, you can use the useHeader() method of the ApiVersionInserter class to add header name information. The value of this header name will be declared when we call the “/hello” endpoint as follows:

As you can see, we use the apiVersion() method to pass the endpoint version information.

The result when you run this example is as follows:

If you request the API in the tutorial API Versioning using path parameter with Spring framework, you can use the usePathSegment() method of the ApiVersionInserter class to define a segment containing version information as follows:

The result when I run this example is as follows:

Add Comment