Running GraphQL with Express sever

Create the project with all dependencies.

Create new node project -y will answer yes to all questions during setting up the project to save us some time.

yarn init -y

add the libraries:

yarn add graphql express express-graphql

what we just did:
– created new npm project (-y answering yes on all questions)
– installed graphQL (–save locally in project’s node_modules folder)
– installed Expless server with Express-graphQL module locally

Create server.js

Create ./server.js in the root folder with the following contents:

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

// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
  type Query {
    hello: String
  }
`);
// The root provides a resolver function for each API endpoint

var root = {
  hello: () => {
    return 'Hello world!';
  },
};

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

app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');

what we just did:
– we created a schema (lines 6-10)
– created a resolver function for our schema (lines 13-17)
– created Express http server (line 19)
– tell Express http server to use graphQL library (lines 20-24)

Now everything is almost ready. Let’s create a start script and run our server.

Create the start script.

Open ./package.json and add the highlighted lines:

{
  "name": "graphql-test",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "start": "node server.js"
  },  
  "dependencies": {
    "express": "^4.16.4",
    "express-graphql": "^0.7.1",
    "graphql": "^14.0.2"
  }
}

Run GraphQL server.

Open terminal, navigate to the root folder and execute the start script:

yarn start

Since we configured graphqlHTTP with graphiql: true (line 23) we can access GraphQL UI tool and execute queries.
Navigate the browser to http://localhost:4000/graphql and run { hello } and the result should look like the one in the image below:

Congratulations! You just ran your first GraphQL server!

Leave a Reply