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.
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.
- Install a new Nuxt.js Project
npx create-nuxt-app <project-name>
- Yarn or NPM install
@nuxtjs/apollo
- 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
nuxt.config.js
buildModules: [
// GraphQl Apollo Client
'@nuxtjs/apollo'
],
apollo: {
clientConfigs: {
default: {
httpEndpoint: 'https://rickandmortyapi.com/graphql',
}
}
},
Querying
yarn run dev
ornpm run dev
to spin up your project.- 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
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.
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.