Skip to content

Latest commit

 

History

History
87 lines (66 loc) · 2.87 KB

File metadata and controls

87 lines (66 loc) · 2.87 KB
title Running an Express GraphQL Server
sidebarTitle Running Express + GraphQL

The simplest way to run a GraphQL API server is to use Express, a popular web application framework for Node.js. You will need to install two additional dependencies:

npm install express graphql-http graphql --save

Let's modify our “hello world” example so that it's an API server rather than a script that runs a single query. We can use the 'express' module to run a webserver, and instead of executing a query directly with the graphql function, we can use the graphql-http library to mount a GraphQL API server on the “/graphql” HTTP endpoint:

import express from "express";
import { createHandler } from "graphql-http/lib/use/express";
import { buildSchema } from "graphql";

// Construct a schema using GraphQL schema language
const schema = buildSchema(`
  type Query {
    hello: String
  }
`);

// The root provides a resolver function for each API endpoint
const root = {
  hello() {
    return "Hello world!";
  },
};

const app = express();

// Create and use the GraphQL handler
app.all(
  "/graphql",
  createHandler({
    schema,
    rootValue: root,
  })
);

// Start the server at port 4000
app.listen(4000, () => {
  console.log("Running a GraphQL API server at http://localhost:4000/graphql");
});

Also, check your package.json file and ensure that type is set to module:

{
  "type": "module",
}

You can run this GraphQL server with:

node server.js

At this point you will have a running GraphQL API; but you can't just visit it in your web browser to use it - you need a GraphQL client to issue GraphQL queries to the API. Let's take a look at how to add the GraphiQL (GraphQL with an i in the middle) integrated development environment to your server.

Using GraphiQL

GraphiQL is GraphQL's IDE; a great way of querying and exploring your GraphQL API. One easy way to add it to your server is via the MIT-licensed ruru package which bundles a prebuilt GraphiQL with some popular enhancements. To do so, install the ruru module with npm install --save ruru and then add the following to your server.js file:

import { ruruHTML } from "ruru/server";

// Serve the GraphiQL IDE
app.get("/", (_req, res) => {
  res.type("html");
  res.end(ruruHTML({ endpoint: "/graphql" }));
});

Now restart the node server.js command.

If you navigate to http://localhost:4000, you should see an interface that lets you enter queries; now you can use the GraphiQL IDE tool to issue GraphQL queries directly in the browser.

At this point you have learned how to run a GraphQL server. The next step is to learn how to issue GraphQL queries from client code.