GraphQL

Building Hello World Application using Express and GraphQL – GraphQL Tutorial

January 25, 2018

author:

Building Hello World Application using Express and GraphQL – GraphQL Tutorial

As we discussed in earlier posts, GraphQL, built for APIs, is a Query Language and facilitates declarative data fetching. It lets the client decide what data it wants instead of the server. We already saw its advantages and core syntax in detail previously. Today, we will build a working Node.js server (with Express) to illustrate a working GraphQL model.

To begin with, we will build a simple node.js server with express.js And then add GraphQL schema to display static Hello World data message.

# Node Project Setup

First things first. Make sure you have the latest version of Node.js installed on your system.

node -v

Next, setup a new project directory and run following command to create a package.json file. (Note: you can keep the default settings by pressing ENTER)

npm init

Since we will be building express server, go fetch express library:

npm install express --save

(--save flag is for future installs of your project directory)

# Express Server Setup

It’s now time to kick up the server. To do so, create a new file server.js in the root directory of the project:

# server.js

const express = require('express');

let port = process.env.PORT || 8080;

const app = express();

app.listen(port);
console.log('GraphQL API Server up and running at localhost:' + port);

Most of the code here is self-explanatory. All we are doing is import express library in our file, allocate a distinct port and create an express server to listen on that port. We can test the server by:

node server.js
GraphQL Hello World Server

# GraphQL Setup

To integrate GraphQL in our node server, we must first install its package. GraphQL has an amazing client-server library named Apollo, but for the sake of setting up the base, we will use graphql-express library. The common thing both libraries do is set up a middleware for GraphQL configurations.

npm install graphql express-graphql --save

Let us also import them in our server file:

const { buildSchema } = require('graphql');
const graphqlHTTP = require('express-graphql');

# GraphQL Schema and Resolver

We will build the schema with GraphQL Schema Language. We can use buildSchema object of graphql.

//import ...
let port = process.env.PORT || 8080;

let schema = buildSchema(`
    type Query {
        msg: String
    }
`);

A resolver is an ultimate bridge between GraphQL and the data. It resolves graphql queries and returns the relevant data. It doesn’t really have to be named resolver though:

...
let schema = ...
let root = {
    msg: () => {
        return 'Hello World!';
    }
};

As you would have guessed, merely defining query and resolver doesn’t really do the job for us. If we want to interact with it, we can create a visual API editor named GraphiQL which is shipped by default with the library.

...
const app = express();
app.use('/', graphqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true
}));

If you feel a little messed with your code, here is the full server.js file for your reference:

const express = require('express');
const { buildSchema } = require('graphql');
const graphqlHTTP = require('express-graphql');
let port = process.env.PORT || 8080;

let schema = buildSchema(`
    type Query {
        msg: String
    }
`);

let root = {
    msg: () => {
        return 'Hello World!';
    }
};

const app = express();
app.use('/', graphqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true
}));

app.listen(port);
console.log('GraphQL API Server up and running at localhost:' + port);

# Test in GraphiQL

As mentioned earlier, we will interact with API directly from the browser, but before that, boot the server with new changes:

node server.js

And hit a request with your favorite browser:

http://localhost:8080

Try testing the endpoint:

{
  msg
}

Also, did you notice autocomplete? That’s one of the blessings of GraphiQL!
GraphiQL Hello World - Auto Complete

And here’s the actual output in GraphiQL:

GraphiQL Hello World Message

Conclusion:

It was a good practical guide to get started with GraphQL. We created a minimal application that renders a Hello World message. And for that we created a GraphQL API server in Node.js and Express.

Leave a comment

Your email address will not be published. Required fields are marked *