GraphQL LogoGraphQL

Running an Express GraphQL Server

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 ruru --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:

var express = require("express")
var { createHandler } = require("graphql-http/lib/use/express")
var { buildSchema } = require("graphql")
var { ruruHTML } = require("ruru/server")
// 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()
// Create and use the GraphQL handler.
app.all(
"/graphql",
createHandler({
schema: schema,
rootValue: root,
})
)
// Serve the GraphiQL IDE.
app.get("/", (_req, res) => {
res.type("html")
res.end(ruruHTML({ endpoint: "/graphql" }))
})
// Start the server at port
app.listen(4000)
console.log("Running a GraphQL API server at http://localhost:4000/graphql")

You can run this GraphQL server with:

node server.js

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

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.

Continue Reading →GraphQL Clients