BeginnerCoder
advanced#Node.js#GraphQL

Using Node.js with GraphQL

This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.

Learn how to use Node.js with GraphQL to create a simple API.

Introduction to GraphQL

GraphQL is a query language for APIs that allows clients to specify exactly what data they need.

Step 1: Install GraphQL

Install GraphQL using npm.

npm install graphql

Step 2: Create a New GraphQL Schema

Create a new GraphQL schema.

const { GraphQLSchema, GraphQLObjectType, GraphQLString } = require('graphql');
const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'Query',
    fields: () => ({
      hello: {
        type: GraphQLString,
        resolve: () => 'Hello World!'
      }
    })
  })
});

Step 3: Create a GraphQL Server

Create a GraphQL server using Express.

const express = require('express');
const app = express();
const { graphqlHTTP } = require('express-graphql');
app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true
}));

Step 4: Run the Server

Run the server.

node server.js

Open a web browser and navigate to http://localhost:3000/graphql to see the GraphQL API in action.

Keep going with Node.js

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.