Using Facades to Decouple API Integrations

This is a technical article that explains some of the things we do at CloudWork.

The most important part of building an integration with an API is actually writing the code that will connect with the Web service and invoke its methods. I’ll show you why using the Façade pattern to decouple calls from your existing code is a good idea and help you identify what kind of problems you might be able to prevent.

So, first things first, what is the Facade pattern?

A Façade is an object that provides simple access to complex – or external – functionality. It might be used to group together several methods into a single one, to abstract a very complex method into several simple calls or, more generically, to decouple two pieces of code where there’s a strong dependency of one over the other.

What happens when you develop API calls inside your code and, suddenly, the API is upgraded and some of its methods or parameters change? You’ll have to change your application code to handle those changes. Also, by changing your internal application code, you might have to change the way some of your objects behave. It is easy to overlook every instance and can require you to doublecheck multiple lines of code.

There’s a better way to keep API calls up-to-date. By writing a Façade with the single responsibility of interacting with the external Web service, you can defend your code from external changes. Now, whenever the API changes, all you have to do is update your Façade. Your internal application code will remain untouched.

APIFacade

Advantages

From a Test Driven Development point-of-view, using a Facade offers a big advantage. You’re now able to write simple tests against the Façade without affecting your internal code test results. By using this strategy, you’ll be able to know immediately whenever an API is not working as you expected and make the necessary changes to the Façade.

This is the approach we follow at CloudWork when building integrations between any third-party APIs. API Façades act as tight compartments that protect the rest of the application from external changes and simplify the way we interact with different Web services.