GraphQL is the most easygoing way to querying APIs. With the single endpoint, we can directly execute queries from the defined schema and it will perform actions according to that.
Apollo client is a community-driven effort to build an easy-to-understand, flexible and powerful GraphQL client.
Let’s quickly Integrate APIs through GraphQL using Vue-apollo.
First of all, install the vue-apollo-client and their dependencies 📦 in your Vue application using the below command.
npm install --save vue-apollo graphql apollo-client apollo-link apollo-link-http apollo-link-context apollo-cache-inmemory graphql-tag
⚙️ Set up vue-apollo-client in main.js:
Step 1: 🗃 Import files
Import files from the library and add a plugin to your Vue app.
Step 2: Create a custom link
Add your graphql API endpoint in httpLink. Here, I am connecting to mock API https://api.graph.cool/simple/v1/ciyz901en4j590185wkmexyex.
Create a custom link using ApolloLink interface. Add authMiddleware in the link, if you have set authorization header.
Step 3: Add apolloProvider in Vue instance
Create ApolloClient instance, link is one of the required object of ApolloClient instance. InMemoryCache is a normalized data store. connectToDevTools will enable apollo client DevTools chrome extension to connect to your application.
Add apolloProvider in vue instance. apolloProvider holds multiple apolloClient instances which are used by the components.
Now, your app is ready to use vue apollo.
✏️ Integrate API in your component:
Let’s take a simple example, we have 3 fields user id, name, and email in the user table. We are going to fetch those records from the user table and display them on the client-side.
Write a query in your component and call it from anywhere instead of calling automatically when the component has been mounted. That’s why we are not using apollo special option because we don’t want to skip queries using the skip() method.
Step 1: Make graphql query
Import template literal tag gql in your component.
Making graphql query to fetch data from the user table. Retrieving name in ascending order and only those users detail whose email Id contains the particular character. $character is variable. we will assign value to $character whenever we’ll fire this query.
Step 2: Fetch data with query
Create a method which fires query through vue-apollo-client. We are passing constant GET_USER_DETAILS in a query. If you are using variables in query then pass those in variables. We’ll pass the value of $character in arguments.
apollo-client will provide a loading state in response based on that we can set loader.
Using fetchPolicy we can define interaction with apollo cache. By default, it is cache-first. You can also use values cache-and-network, network-only, no-cache, cache-only based on your requirements.
Step 3: Here’s what the template looks like