How to create a basic GraphQL Server with Express

Mathias Uhlitzsch
Sep 3, 2018 · 5 min read

Working with new technologies is always an exiting task. One technology that came up to me very often in the last 6 months has caught my attention more than I expected. Developed by Facebook, used by Paypal, Github and many others (https://graphql.org/users/). Wow. These are some really big names. So I had to check it out. The name of the technology is GraphQL.

As always when I want to learn a new technology the best way for me is to learn it with a very basic and simple example.

But first things first…

What is GraphQL?

GraphQL is not a framework or a library. Its more like a standard or a specification. GraphQL is a query language that offers you a lot possibilities that are very different from using a REST API. You can find implementations for many different common programming languages. Look here to find a reference to those implementations (https://graphql.org/code/).

You can find more general information about GraphQL in the official documenation here: http://graphql.github.io/learn/

Basic Example with Bands

In the following example I will show only a few basic concepts of GraphQL. Of course there are other concepts which you can also find in the official documenation (https://graphql.org/learn/).

My example here is inspired by this documentation for GraphQL together with express: https://graphql.org/graphql-js/running-an-express-graphql-server/

The example shows how you can easily specify how an API response can look like by defining types and fields on those types. Depending on which fields you ask for in your request, GraphQL will give you exactly those fields you have asked for.

The code in this article will show how to create a basic API that is built with Node.js, express and express-graphql. The API will provide information (name, members, albums) about some famous bands that I like.

Precondition

Please make sure you have installed Node.js. Create a new directory with your project name. Change to that directory and hit npm init to create a package.json file.

Install following dependencies:

npm install express express-graphql graphql --save

Create a JSON File called bands.json in the same directory and fill it with following (or some other bands you like). I created this file from my memory, so there can be some mistakes and its obviously not complete. :)

[
{
"id": 1,
"name": "Metallica",
"founded": 1981,
"members": [
"James Hetfield",
"Kirk Hammett",
"Lars Ulrich",
"Robert Trujilo"],
"albums": [
"Kill em all",
"Ride the Lightning",
"Master of Puppets",
"...and Justice for all",
"Metallica",
"Load",
"Reload",
"Garage Inc.",
"St. Anger",
"Death Magnetic",
"Hardwired…to Self-Destruct"
]
},
{
"id": 2,
"name": "Pearl Jam",
"founded": 1990,
"members": [
"Eddie Vedder",
"Stone Gossard",
"Mike McCready",
"Jeff Ament",
"Boom Casper"
],
"albums": [
"Ten",
"Vs.",
"Vitalogy",
"No Code",
"..."
]
},
{
"id": 3,
"name": "Weezer",
"founded": 1990,
"members": [
"Rivers Cuomo",
"Patrick Wilson",
"Brian Bell",
"Scott Schreiner"
],
"albums": [
"Weezer (The Blue Album)",
"Pinkerton",
"Weezer (The Green Album)",
"..."
]
}
]

Create a file server.js and add the following code.

var express = require('express');
var graphql = require('express-graphql');
var {buildSchema} = require('graphql');
var bands = require('./bands.json')

// Declaration of the GraphQL schema and types
var schema = buildSchema(`
type Query {
band(id: Int!): Band
},
type Band {
id: Int
name: String
founded: Int
members: [String]
albums: [String]
}
`);

// Resolver function to get information about one band
var getBand = function (args) {
return bands.filter(band => {return band.id == args.id;})[0];
}

var root = {
band: getBand
};
// Create an express server and a GraphQL endpoint
var app = express();
app.use('/graphql', graphql({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');

So what is going on here?

First you import all the libraries you need to create an express server and the modules to work with GraphQL. Also the JSON File with all the bands needs to be imported.

In the next step you create a schema how a query has to look like and which types this query contains or returns. In this example only one query is defined. The query needs an ID as an argument and gives you a band with that ID. Of course you can define another query which returns e. g. a list of all bands or filters all bands by its name or other properties.

After that you need to create a resolver function for your query and connect this resolver function to the query. The rest of the code sets up a GraphQL express server which will produce a route on localhost:4000/graphql.

Start the node server by typing node server.js

Open up GraphiQL UI through localhost:4000/graphql. You will receive the start screen of GraphiQL (since we set graphiql: true), which is a very useful tool to actually test your queries and see the result immediately.

GraphiQL start screen

GraphiQL with basic Query to get the band with ID 1.

Get name and members for the band with Id 1

So what happens here? In the left upper corner you define which query from the server code you want to use and which properties you want to have in the response. GetSingleBandById ist just a so called operation name. For this example I only want to know what is the name of the band with the ID 1 and who are the band members. The argument bandID is provided through an object on the bottom of the left side. Hit the play Button to see the result.

So if I also want to know when this band was founded and which albums they released I can just add those properties to the request and get this information in the response. I also changed the order of the fields I want to know.

Get members, name, albums and when the band was founded

Conclusion

In this tutorial I showed how to implement a very basic GraphQL server with Node.js, Express and express-graphql that provides data from a static JSON File to give you a fast entry point to GraphQL. Thank you for reading!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade