Building bridges: Connecting to a third-party service

Photo by Luca Bravo


You will find some new and cool spring feature implementations, focusing on practical examples and learn some insights in the meantime. We will use cache spring module, it’s easy to implement and very useful.

What you will learn in this article

  • Build a REST service.
  • Request information from a third party REST service.
  • Caching information to speed up and avoid unnecessary requests.
  • Gain a better understanding of spring-boot and its components.
  • How to make integration tests using Mockito.
  • Use of JUnit 5 with parameterized tests.
  • Package your service for delivery with Docker.
  • How to handle properties production ready.



Model objects with Lombok

To reduce time coding models for the weather API (I could create a common lib, what do you think?) I used several Lombok annotations that will create the code needed for getters, setters and a builder pattern very useful when mock responses.

Requesting weather

Once you created your account in open weather map and you have your appid, is as simple as use RestTemplate to get current weather by zip code with this URL:

What is a cache?

A cache is a component that stores data so that future requests for the same data can be served faster; the data stored in a cache might be the result of an earlier computation or a copy of the data stored elsewhere, in our case a third party service.

  • @Cacheable triggers cache population
  • @CacheEvict triggers cache eviction
  • @CachePut updates the cache without interfering with the method execution
  • @Caching regroups multiple cache operations to be applied on a method
  • @CacheConfig shares some common cache-related settings at class-level


Before going to the specifics of the test I wrote, we need to talk about Mockito, sounds more as a little mucus in Spanish than a drink based on tequila, Mockito is a framework that helps you imitate responses from anything very easily, so we can control the outcome of a call without actually doing it and validate or test the behavior of our service accordingly.



Today we learned how to call an external API using rest template, how to cache information using @Cacheable to optimize our service and avoid unnecessary process and on top of that how to use Mockito to test these cases to imitate external service behavior.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Marco Capo

Marco Capo

I’m a senior software engineer working in technology development for 12+ years from marketing, videogames and microservices for big companies