0
0
GraphQLquery~5 mins

Express integration in GraphQL

Choose your learning style9 modes available
Introduction

Express integration helps you connect GraphQL with a web server so you can handle requests easily.

You want to create a web API that clients can query with GraphQL.
You need to serve GraphQL queries over HTTP using Express.
You want to combine REST routes and GraphQL in one Express app.
You want to test GraphQL queries locally with a simple server.
You want to add middleware like authentication before GraphQL runs.
Syntax
GraphQL
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');

const app = express();

const schema = buildSchema(`
  type Query {
    hello: String
  }
`);

const root = {
  hello: () => 'Hello world!'
};

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

app.listen(4000, () => console.log('Server running on http://localhost:4000/graphql'));

Use express-graphql middleware to connect GraphQL with Express.

Enable graphiql: true to get a web interface for testing queries.

Examples
Basic setup to serve GraphQL at the '/graphql' path with a schema and root resolver.
GraphQL
app.use('/graphql', graphqlHTTP({ schema, rootValue, graphiql: true }));
Serve GraphQL at '/api' without the GraphiQL interface for production.
GraphQL
app.use('/api', graphqlHTTP({ schema, rootValue, graphiql: false }));
Use a function to customize options per request, like adding user info.
GraphQL
app.use('/graphql', graphqlHTTP(req => ({
  schema,
  rootValue,
  context: { user: req.user },
  graphiql: true
})));
Sample Program

This program creates a GraphQL server with Express. It defines a query greet that takes a name and returns a greeting. You can test it by visiting the GraphiQL interface.

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

const app = express();

const schema = buildSchema(`
  type Query {
    greet(name: String!): String
  }
`);

const root = {
  greet: ({ name }) => `Hello, ${name}!`
};

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

app.listen(4000, () => console.log('Server running on http://localhost:4000/graphql'));
OutputSuccess
Important Notes

Remember to install express, graphql, and express-graphql packages before running.

GraphiQL is a helpful tool for beginners to try queries in the browser.

Express integration lets you add other middleware like logging or authentication easily.

Summary

Express integration connects GraphQL to a web server for easy HTTP handling.

Use express-graphql middleware with a schema and root resolver.

Enable GraphiQL for a friendly query interface during development.