How to consume an external API using spring boot

H

So you’ve just been assigned a task to integrate with an API but you are not sure where to start? Keep reading.

I have integrated with a vast number of API’s and this also means that I have read multiple API documentation. Below is a guideline to help you with your integrations as a developer using Spring Boot.

1. Read through the Documentation. I understand that some documentations are hard to read but to be honest, you save yourself a lot of time and stress reading through the documentation. Some things you can look out for in the documentation:

    • A postman collection. If the documentation has a postman collection then half of your problem is solved, all you would have to do is import it in postman and you can see all the endpoints you need to call as well as the sample requests, API convention.
    • A test section. Some documentations have test sections beside or above the endpoints. Once you see a test section, play around with it, this way you are able to verify that the endpoint works as well as see how it works.
    • A swagger documentation. Some documentations may not have a postman collection but a swagger documentation can do the work.

2. Test first. Before you open your code editor to write your first line of code, test the endpoints first, be certain that the endpoints return the error codes they ought to return at different instances, the requests and responses are as they should be and just an all-round test. This helps to avoid making numerous changes to your code.

3. Choose your client. Now that you properly understand what the integration entails and you have tested to be sure the endpoints work properly, you can begin your integration.

For consuming an Restful API with Spring Boot, there are 2 major clients you can use:

  •  Rest Template: This is a synchronous and blocking REST client provided by the core Spring Framework. Up until Spring 5, it was the most used client but it has now been deprecated, this doesn’t mean you still cannot use it, it just means it’s not really future proof. I personally still use Rest Template
  • WebClient: This is an asynchronous and non-blocking client provided by the Spring Reactive Framework. 
The client you decide to use would be depending on your use case, sometimes I use Rest Template and sometimes I use WebClient. Read more here.

Summary

Let me know if you found the tips helpful. In the coming articles, I would be consuming API’s using either of the clients I mentioned so make sure to check back. Cheers!

Add Comment

By admin

admin

Get in touch