Nuxt.js Querying a GraphQL API

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

  1. Install a new Nuxt.js Project npx create-nuxt-app <project-name>
  2. Yarn or NPM install @nuxtjs/apollo
  3. Yarn or NPM install graphql-tag

Configure Apollo Client

nuxt.config.js

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

Querying

  1. yarn run dev or npm run devto spin up your project.
  2. 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>

Queries with arguments

Passing arguments to queries and getting results is easy with GraphQl. Let’s use the character query which requires a capital “ID!” A capital ID! in a GraphQl API means that this ID! is unique. To make the query dynamic we need to use a variable that starts with a “$” sign, the variable name can be anything. To pass dynamic values using “this” to the variable we need to make the variable a function.

├── 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>

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store