Let’s imagine that you are developing a native mobile client for a shopping application. you would have to implement a product details page, which displays following information,
- Items in the shopping cart
- Order history
- Customer reviews
- Low inventory warning
- Shipping options
- Various recommendations, (other products bought by customers who bought this product)
- Alternative purchasing options
In a monolithic application architecture, Those data would retrieve by making a single REST call (GET api.company.com/productdetails/<productId>) to the application. A load balancer routes the request to one of N identical application instances. The application would then query various database tables and return the response to the client.
But if you use microservice architecture the data which need to displayed must retrieve by multiple microservices. Here are some of the example microservices we would need.
- Shopping Cart Service – items in the shopping cart
- Order Service – order history
- Catalog Service – basic product information, such as it’s name, image, and price
- Review Service – customer reviews
- Inventory Service – low inventory warning
- Shipping Service – shipping options, deadlines, and costs drawn separately from the shipping provider’s API
- Recommendation Service(s) – suggested items
All above microservice would have a public endpoint (https://<serviceName>.api.company.name) and client would have to make many requests to retrieve the all necessary data. If app need to make hundreds of request to render a one page, the app would be inefficient. Also if already existing microservices response with different data type, the app have to handle it too.
Due to these reasons, its wise to use an API Gateway for encapsulates the internal microservices and provides an API that respond to each client. The API Gateway is responsible for request meditions and compose a singe respond.
A great example of an API Gateway is the Netflix API Gateway. The Netflix streaming service is available on hundreds of different kinds of devices including televisions, set-top boxes, smartphones, gaming systems, tablets, etc. Initially, Netflix attempted to provide a one-size-fits-all API for their streaming service. However, they discovered that it didn’t work well because of the diverse range of devices and their unique needs.