Photo by Daniel Cheung on Unsplash
GraphQL is the most easygoing way to querying APIs. With a single endpoint, we can directly execute queries from the defined schema and it will perform actions accordingly.
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 command below.
npm install --save vue-apollo graphql apollo-client apollo-link apollo-link-http apollo-link-context apollo-cache-inmemory graphql-tag
Import files from the library and add a plugin to your Vue app.
1import { ApolloClient } from 'apollo-client'
2import { HttpLink } from 'apollo-link-http'
3import { InMemoryCache } from 'apollo-cache-inmemory'
4import { ApolloLink } from 'apollo-link'
5import VueApollo from 'vue-apollo'
6
7Vue.use(VueApollo)
Add your graphql API endpoint in httpLink. Here, I am connecting to mock API https://api.graph.cool/simple/v1/ciyz901en4j590185wkmexyex.
1const httpLink = new HttpLink({
2 uri: 'https://api.graph.cool/simple/v1/ciyz901en4j590185wkmexyex'
3})
4
5// set authorization header to authenticate the request using apollo link, it is optional.
6/*
7 const authMiddleware = new ApolloLink((operation, forward) => {
8 const token = 'cllHNFlaZkpXbg64Qzh0Z3VJT2FOdz09'
9 operation.setContext({
10 headers: {
11 authorization: `Bearer ${token}`
12 }
13 })
14 return forward(operation)
15})
16*/
17
18const link = ApolloLink.from([
19 // authMiddleware,
20 httpLink
21])
Create a custom link using ApolloLink interface. Add authMiddleware in the link, if you have set authorization header.
1// Create the apollo client
2const apolloClient = new ApolloClient({
3 link,
4 cache: new InMemoryCache(),
5 connectToDevTools: true
6})
7
8const apolloProvider = new VueApollo({
9 defaultClient: apolloClient
10})
11
12new Vue({
13 router,
14 apolloProvider,
15 apolloClient,
16 render: h => h(App)
17}).$mount('#app')
Create ApolloClient instance, link is one of the required objects 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.
Let’s take a simple example, we have 3 fields: the 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 having it called 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.
Import template literal tag gql in your component.
1<script>
2import gql from 'graphql-tag'
3const GET_USER_DETAILS = gql`
4query getUsers($character: String!) {
5 allUsers(orderBy: name_ASC, filter: {email_contains: $character}) {
6 id,
7 name,
8 email
9 }
10}
11`
12</script>
Making graphql query to fetch data from the user table, retrieve names in ascending order and details of only those users whose email Id contains the particular character. $character is variable. we will assign value to $character whenever we’ll fire this 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.
1<script>
2export default {
3 data () {
4 return {
5 userList: [],
6 isLoading: false
7 }
8 },
9 created () {
10 const vm = this
11 vm.getUserList({ character: '@' })
12 },
13 methods: {
14 /**
15 * fetch users records using apollo client
16 */
17 getUserList (variables = {}) {
18 const vm = this
19 vm.isLoading = true
20 vm.$apolloProvider.defaultClient
21 // it will fire queries here
22 .query({
23 query: GET_USER_DETAILS,
24 variables: {
25 ...variables
26 }
27 // fetchPolicy: 'cache-and-network'
28 })
29 .then(result => {
30 vm.userList = result.data.allUsers
31 vm.isLoading = result.data.loading
32 })
33 .catch(error => {
34 // write your error message here
35 console.log(error)
36 })
37 }
38 }
39}
40</script>
Apollo-client will provide a loading state in response, based on this we can set loader.
Using fetchPolicy we can define interaction with apollo cache. By default, it is cache-first. You can also use the values: cache-and-network, network-only, no-cache, or cache-only based on your requirements.
1<template lang="pug">
2 .container
3 div(v-if="isLoading") Loading......
4 .user-table(v-if="!isLoading")
5 .table-row.table-header
6 div User Id
7 div User Name
8 div User Email
9 .table-row.table-data(:key="index" v-for="(user, index) in userList")
10 div {{user.id}}
11 div {{user.name}}
12 div {{user.email}}
13</template>
That's all there is to it! You can access the complete source code here.
If you're interested in exploring more programming topics, we invite you to check out our other insightful blog posts.
Additionally, we recommend reading our informative blog post on building a masked input textbox in Vue. It provides valuable insights and guidance for implementing this feature in your projects.