DEV Community

loading...

Using GraphQL in Express JS

Muhammad Yusuf
・3 min read

GraphQL is a useful query language for your API. But it can be intimidating because they bring the complexity upfront as there are a lot that has to be set up before we can create our first query. I hope this article will be useful and understandable. Let's get started!

First things first, we'll need to require our module to our file and put some basic express boilerplate, let's say it's called app.js:

const express = require('express')
const app = express()
const { graphqlHTTP } = require('express-graphql')
const port = 3000

// We'll put everything here later

// This code below must be on the last part of the file
app.listen(port, () => {
  console.log('Listening on port:', port)
})
Enter fullscreen mode Exit fullscreen mode

Then we'll create our first and (maybe) only route in this article:

app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true
}))
Enter fullscreen mode Exit fullscreen mode

Instead of using (req, res) => {} to the callback we put an invoked graphqlHTTP function, so we can let the graphql do its thing. Inside the graphqlHTTP, we put a object that contains option to switch the graphiQL interface on, and schema that we'll create later on.

So what's a schema?

Schema defines a hierarchy of types with fields that are populated from your back-end data stores. The most basic components of a GraphQL schema are object types for query and mutation (optional), which just represent a kind of object you can fetch from your service, and what fields it has.

In the simplest way, we might represent the object types like this:

{
  name: 'Book',
  fields: {
    title: { type: GraphQLString },
    author: { type: GraphQLString }
  }
}
Enter fullscreen mode Exit fullscreen mode

What's GraphQLString? It's a type that can only be recognized by graphQL instead of regular String in javascript. They have other types as well like GraphQLInt, GraphQLList, and GraphQLObjectType. And we can define them like this:

const {
  GraphQLSchema, // for base schema type
  GraphQLString,
  GraphQLInt,
  GraphQLList,
  GraphQLObjectType
} = require('graphql')
Enter fullscreen mode Exit fullscreen mode

Now before we make our schema, we can create our own type first by putting the book object from earlier.

const BookType = new GraphQLObjectType({
  name: 'Book',
  fields: {
    title: { type: GraphQLString },
    author: { type: GraphQLString }
  }
})
Enter fullscreen mode Exit fullscreen mode

Then we create our query object and prepare it with a small dummy data:

let dummyBooks = [
  { title: 'Harry Potter', author: 'JK Rowling' },
  { title: 'Lord of The Rings', author: 'JRR Tolkien' },
  { title: 'Sherlock Holmes', author: 'Arthur Conan Doyle' }
]

const queryType = new GraphQLObjectType({
  name: 'Book query',
  fields: function () {
    return {
      // we called it books so we can type 'books' later on
      books: {
        type: new GraphQLList(BookType),
        resolve: function () {
          return dummyBooks
        }
      }
    }
  }
})
Enter fullscreen mode Exit fullscreen mode

Query object requires fields function that returns an object. The object itself contains properties of what we want to find via the query later on. And each has to have type and resolve. type property defines the type returned to us users and resolve gives the actual data, which is dummyBooks.

Lastly, we can define our schema like this:

const schema = new GraphQLSchema({
  query: queryType
})
Enter fullscreen mode Exit fullscreen mode

Running the file

Now we can run this from terminal:

node app.js
Enter fullscreen mode Exit fullscreen mode

Type this in the browser:

localhost:3000/graphql
Enter fullscreen mode Exit fullscreen mode

Now you'll see this:
GraphiQL

There are two main parts in the screen, the white part on the left is the query editor, we can crate our query there. And the gray part on the right side will show the result of query done in the left.

Now we can create our first query:

query {
  books {
    title
  }
}
Enter fullscreen mode Exit fullscreen mode

Notice there's no author in the query, and we'll get the data exactly like our query format:

{
  "data": {
    "books": [
      {
        "title": "Harry Potter"
      },
      {
        "title": "Lord of The Rings"
      },
      {
        "title": "Sherlock Holmes"
      }
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

source: https://graphql.org/learn/

Discussion (8)

Collapse
retr0c0de profile image
Anguram Shanmugam

Waited for a article like this.

Honestly >90% articles I read uses Apollo. I tried searching for articles that uses only GraphQl to know the nuts and bolts of it.

Now here I'm 👍

Collapse
menard_codes profile image
Menard Maranan

You can use pure GraphQL and express for making API if you want (btw I tried that, and I don't want to do that again after learning about apollo), but that would be more boilerplate code. The reason why devs love apollo is how easy it is apollo made the process of making graphql api.

Collapse
mhmmdysf profile image
Muhammad Yusuf Author

I'm trying to learn apollo myself, but I guess you gotta start somewhere.

Collapse
psiho profile image
Mirko Vukušić

Exactly. Was searching for stuff like this before. But also, not doing it again after.... Not Apollo :) ... Postgraphile. If Postgres is your choice, check Postgraphile anf I dubt youll create schemas and API manually again

Collapse
mhmmdysf profile image
Muhammad Yusuf Author

Gonna try apollo soon. Thanks for the feedback! :)

Thread Thread
psiho profile image
Mirko Vukušić

try Postgraphile

Thread Thread
mhmmdysf profile image
Muhammad Yusuf Author

Just googled it and I think I'm gonna love it, thanks!

Collapse
mhmmdysf profile image
Muhammad Yusuf Author

Thanks for the feedback!