Let’s say you’re writing a frontend for an online store. You would have to make requests to get the shopping cart, add items to the cart, get product details, search for a product, list all products, etc.
If you’re directly calling
axios in your code, they would look something like this.
This is totally fine if you’re only making a handful of requests, but if your codebase makes a lot of HTTP requests, it might be better to abstract them into their own modules instead of calling them directly.
An API module is just a JS module that contains HTTP logic organized by business domain. For the online store example, the business domains would be
Order, etc. The respective API modules would be
Let’s rewrite the above code using the API module pattern by creating
Now we can import these into the UI modules:
- Improve readability and testability by abstracting the HTTP code away from the UI or business code
- One place to make modifications like renaming payload structure, query param names etc
- One place to massage response into something that’s useful for the other parts of the codebase
- Organizing HTTP code by business domain thereby improving code discoverability by new members of the team
- Colocate custom app status codes sent by the server
If we see that there’s a lot of common code used in API modules, we can add one more layer called
ApiClient to keep them DRY. The common code can be things like:
- Adding extra headers
- Using right config for production, development etc — hostnames, headers, etc
- Session handling etc
We can now update our API modules to use HttpClient:
Thanks for reading! :)