Using REST APIs

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, POST, and DELETE.

  • Hypermedia as the engine of the application state: The API should use links to tell the client about other related resources. There should be no need to hardcode any information about the structure of an API.

RESTful APIs usually implement these principles by applying stateless resource access and manipulation via URIs and HTTP verbs. An example could be a product API of a grocery store. To create a single product on the API, request a single product by ID and manipulate it or delete it. We could use the following client URL (cURL) requests:

Get hands-on with 1200+ tech skills courses.