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.

import { ApolloClient } from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { ApolloLink } from 'apollo-link'
import VueApollo from 'vue-apollo'

Vue.use(VueApollo)

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.

const httpLink = new HttpLink({
  uri: 'https://api.graph.cool/simple/v1/ciyz901en4j590185wkmexyex'
})

// set authorization header to authenticate the request using apollo link, it is optional.
/*
  const authMiddleware = new ApolloLink((operation, forward) => {
  const token = 'cllHNFlaZkpXbg64Qzh0Z3VJT2FOdz09'
  operation.setContext({
    headers: {
      authorization: `Bearer ${token}`
    }
  })
  return forward(operation)
})
*/

const link = ApolloLink.from([
  // authMiddleware,
  httpLink
])

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 the apollo client
const apolloClient = new ApolloClient({
  link,
  cache: new InMemoryCache(),
  connectToDevTools: true
})

const apolloProvider = new VueApollo({
  defaultClient: apolloClient
})

new Vue({
  router,
  apolloProvider,
  apolloClient,
  render: h => h(App)
}).$mount('#app')

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.

#graphql #vue #apollo #api #developer

Building GraphQL APIs with Vue.js and Apollo Client
8.70 GEEK