Nuxt.js Querying a GraphQL API

In this article, I am going to show you how to connect to a Graph-Ql API in your Nuxt.js Project.

Final Project & Github

Why Graph-QL? In a nutshell, GraphQL is a query language with an easy syntax that describes how to ask for data, and is generally used to load data from a server to a client. It lets the client specify exactly what data it needs. It makes it easier to aggregate data from multiple sources. It uses a type system to describe data. For a deep dive I recommend reading the official documentations.

To get started, we need to install a few things.

  1. Yarn or NPM install @nuxtjs/apollo
  2. Yarn or NPM install graphql-tag

Note: Graphql-tag allows us to write template literals as GraphQL queries.

We are going to use the Rick and Morty API to build a simple character card selector using the data received from the API. We will connect to this API using the Nuxt.js Apollo Module. Internally, the Apollo Module uses Vue-Apollo which uses the Apollo Client.

Configure Apollo Client

buildModules: [
// GraphQl Apollo Client
'@nuxtjs/apollo'
],
apollo: {
clientConfigs: {
default: {
httpEndpoint: 'https://rickandmortyapi.com/graphql',
}
}
},

Querying

  1. Copy and paste the code below in your index.vue page
<script>
import gql from 'graphql-tag'

export default {
apollo: {
characters: gql`
query getCharacters {
characters {
results {
id
name
status
}
}
}
`,
},
}
</script>

Open Vue.js devtools. You should see the queried data.

Apollo binds characters to the data() method, making it available in our template.

3. In your template copy and paste the code below.

Queries with arguments

Let’s create a <nuxt-child> component for index.vue

├── index
│ ├── _id.vue
├── index.vue

// Copy and paste the code below inside _id.vue
<script>
import gql from 'graphql-tag'

export default {
name: 'CharacterCard',
apollo: {
// Dynamic querying
character: {
query: gql`
query getCharacter($id: ID!) {
character(id: $id) {
id
name
status
species
gender
image
origin {
name
}
}
}
`,
variables() {
return {
// if the route.params.id is null make id = 1
id: this.$route.params.id || 1,
}
},
},
},
}
</script>

4. In your template copy and paste the code below.

That’s it. If you found this useful, feel free to follow me on Medium and Twitter.

Hi, my name is Alex. I’m a front-end engineer, passionate for the web, responsive design, & typography.