Vue.js with GraphQL

Image

GraphQL is a replacement for REST API to maintain structured and strict layer between your client and server. It allows client to define what data exactly then need and exactly this information will be returned from server. Strict data types solves problems of requesting wrong data.

In this article we will build simple GraphQL API and fetch data from it in our Vue application. We will create single GraphQL request which will return "Hello GraphQL" message. Then in our Vue application we fetch this data and render on the page.

Implementing server

Let's first create server folder where our GraphQL API will live.

mkdir backend
cd backend
yarn add express graphql  express-graphql cors

We installed express as a node framework. It has a nice package to work with graphql with is called express-graphql. We also installed cors package to do request between two application as our backend application will be running on different port.

Let's create backend/server.js and require all modules

const express = require('express')
const {graphql, buildSchema} = require('graphql')
const graphqlHTTP = require('express-graphql')
const cors = require('cors')

Now we should define GraphQL schema with our first query.

const schema = buildSchema(`
  type Query {
    hello: String
  }
`)

We just wrote here that we have a Query with name hello and it returns string. If we request later from client hello with different type, error will be thrown.

Now we should also add a root value. We describe there what data do we want to be returned from our query.

const rootValue = {
  hello: () => 'Hello GraphQL'
}

Now we should register new route from GraphQL and pass rootValue and schema in it.

const app = express()
app.use(cors())
app.use('/graphql', graphqlHTTP({
  rootValue, schema, graphiql: true
}))
app.listen(3001, () => console.log('Started GraphQL backend'))

To start our server it's enough to write

node server.js

Implementing frontend

Let's create new Vue project using Vue-cli.

vue init webpack frontend
cd frontend
yarn add axios
npm run dev

As you can see, we also installed axios to fetch data from server.

Now we want to clean our App.vue and add just a button which will fetch our data.

<template>
  <div id="app">
    <button @click="getGraphQL">Get GraphQL data</button>
    <div>{{message}}</div>
  </div>
</template>

When we click on button we want to fetch data and render result in message.

import axios from 'axios'
export default {
  data () {
    return {
      message: ''
    }
  }
}

We imported axios and create empty message variable. Now let's add method for fetching.

methods: {
  async getGraphQL() {
    try {
      const result = await axios.post(
        'http://localhost:3888/graphql',
        {query: '{hello}'}
      )
      this.message = result.data.data.hello
    } catch (err) {
      console.log('err', err)
    }
  }
}

We made async method to use await for fetching data. As we installed cors package in our server we can make request for our backend which is running on other port. As a body we are passing object with query property where we request hello query.

As you can see our message was updated after clicking on the button.

Conclusion

As you can see it's quite easy to use GraphQL with Vue and it fit really well as alternative for REST.