Introduction
Learn about the API layer and how to manage Async operations.
We'll cover the following
Modern applications often have to communicate with a backend server for different purposes, like authenticating users, fetching data, submitting forms, and so on. Making a request is as simple as calling the fetch function and passing a URL of an API endpoint. This way, we make direct calls to a server from anywhere in an application, be it a component or a service, as shown in the figure below.
This approach is sufficient for small applications, but in larger applications, there are usually many different endpoints and third-party servers that our app can communicate with.
Issues
Two significant issues quickly arise when working on large applications:
Lack of standardization
Projects that don’t have a specific and opinionated way of doing something have as many ways of doing it as many developers that currently work and have worked on an application in the past. For example, one part of an app could be using the fetch API, another the Axios library, and another pure xhr request. This inconsistency increases the maintenance burden and wastes developers’ time, especially those who recently joined the team. Instead of coding, they now need to think about the appropriate way to perform API requests.
Updating the client-side when the server-side endpoint changes
Imagine that our app has a custom analytics endpoint that receives requests from 30 different pages, and the calls are done in this manner:
axios.post('https://www.mydomain.com/api/analytics/user/user_id', {timestamp: Date.now(),action: 'click',page: 'Profile'})
This works perfectly fine, but what happens if:
- The website is moving to a different domain?
- The backend is rolling out a new API endpoint under
/api/v2/
? - The company decided to move to a third-party analytics solution?
- An endpoint now accepts payload data in a different format?
We now have to update every place where the aforementioned API call is made, so in this example case, just 30 pages. Of course, it can be done, but we have to modify many different files by doing so. What’s more, we also have to test every single page that’s making this API call to ensure that it works as it should. It’s also worth mentioning that, unfortunately, not every app has automated test suites, difficult to do manually. Thankfully, we can avoid all of that by implementing an API layer.
In this chapter, we cover:
- What an API Layer is and what problems it solves.
- How to handle API states during requests and avoid loader flickering.
- How to use Composition API for API requests and state handling.
- Cancellation requests.
- Managing APIs with Vuex.
- Error logging.