Skip to main content

implementing graphql api in nodejs

Implementing a GraphQL API in Node.js typically involves setting up an Express server and integrating GraphQL middleware.
1. Project Setup and Dependencies:
Initialize a Node.js project.
Code
  mkdir my-graphql-api
  cd my-graphql-api
  npm init -y
  • Install necessary packages: expressgraphql, and express-graphql.
Code
  npm install express graphql express-graphql
2. Create an Entry Point (e.g., server.js):
Import the installed dependencies.
JavaScript
  const express = require('express');
  const { graphqlHTTP } = require('express-graphql');
  const { buildSchema } = require('graphql');
3. Define the GraphQL Schema:
  • Use the GraphQL Schema Language to define your data types, queries (for fetching data), and mutations (for modifying data).
  • Example schema:
JavaScript
  const schema = buildSchema(`
    type User {
      id: ID!
      name: String!
      email: String
    }

    type Query {
      hello: String
      user(id: ID!): User
      users: [User]
    }

    type Mutation {
      createUser(name: String!, email: String): User
    }
  `);
4. Define Resolvers:
  • Resolvers are functions that tell GraphQL how to fetch the data for each field in your schema.
  • Example resolvers: 
JavaScript
  const root = {
    hello: () => 'Hello world!',
    user: ({ id }) => {
      // Logic to fetch user by ID from a database or data source
      return { id: id, name: 'John Doe', email: 'john@example.com' };
    },
    users: () => {
      // Logic to fetch all users
      return [
        { id: '1', name: 'Alice', email: 'alice@example.com' },
        { id: '2', name: 'Bob', email: 'bob@example.com' },
      ];
    },
    createUser: ({ name, email }) => {
      // Logic to create a new user in a database
      const newUser = { id: String(Date.now()), name, email };
      // Save newUser to your data source
      return newUser;
    },
  };
5. Set up the Express Server with GraphQL Middleware:
  • Create an Express app and use the graphqlHTTP middleware, providing your schema and resolvers.
  • Optionally, enable GraphiQL for a web-based IDE to test your API.
JavaScript
  const app = express();
  app.use('/graphql', graphqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true, // Enable GraphiQL for testing
  }));

  app.listen(4000, () => {
    console.log('GraphQL server running on http://localhost:4000/graphql');
  });
6. Run and Test:
start the server.
Code
  node server.js
  • Access http://localhost:4000/graphql in your browser to use GraphiQL and test your queries and mutation