Using REST APIs
Explore how to use REST APIs in Vue projects by leveraging Vuex to manage state and API calls. Understand REST principles, perform CRUD operations, and organize API requests with actions and mutations. Learn to optimize data fetching, avoid over-fetching, and maintain synchronization between your Vue app and external APIs effectively.
When building a Vue app, we often need to use an API to retrieve and store data. Very often, such APIs are built on the REST architecture. Usually, we could do fetch operations directly in the Vue components. However, thanks to Vuex, we can move these API calls near the data storage. The tools that will help us achieve this are actions, mutations, and custom plugins.
What is the REST architecture?
REST stands for Representational State Transfer and describes how to communicate with a web service. RESTful APIs are built upon several principles.
The client-server principle: Any client can request data from the server, allowing for vertical scaling and independent development of client and server applications.
The API is stateless: Each API response contains all the information for the client. Therefore, an app can make any API request independently and in arbitrary order.
Caching: HTTP offers powerful caching methods that an app should use. The saying goes, "A request that doesn't have to be made is the fastest."
A uniform interface: This is the essential principle. It contains a total of four subprinciples.
Resource identification in requests: Every entity that a Uniform Resource Identifier (URI) can locate is a resource. Each resource has a distinct address.
Resource manipulation through representations: When a client holds a resource, including its metadata, it has enough information to change or delete it.
Self-descriptive messages: Each message contains enough information to determine how to process the message. This principle explicitly includes the HTTP verbs GET, PUT, ...