How to build a GraphQL API in Node.js

Building GraphQL APIs in Node.js enables clients to request exactly the data they need, reducing over-fetching and providing flexible, efficient data access. As the creator of CoreUI with over 25 years of backend development experience, I’ve implemented GraphQL APIs for complex data requirements in enterprise applications. The most effective approach is using Apollo Server with well-defined schemas and resolvers for type-safe, performant API development. This provides powerful query capabilities and excellent developer experience with built-in documentation and introspection.

Use Apollo Server with GraphQL schema definitions and resolvers to create flexible, type-safe APIs with efficient data fetching.

const { ApolloServer, gql } = require('apollo-server-express')
const express = require('express')

// Sample data (use database in production)
const users = [
  { id: 1, name: 'John Doe', email: '[email protected]', age: 30 },
  { id: 2, name: 'Jane Smith', email: '[email protected]', age: 25 }
]

const posts = [
  { id: 1, title: 'GraphQL Basics', content: 'Learning GraphQL...', authorId: 1 },
  { id: 2, title: 'Node.js Tips', content: 'Node.js best practices...', authorId: 2 }
]

// GraphQL schema definition
const typeDefs = gql`
  type User {
    id: ID!
    name: String!
    email: String!
    age: Int
    posts: [Post]
  }

  type Post {
    id: ID!
    title: String!
    content: String!
    author: User
  }

  type Query {
    users: [User]
    user(id: ID!): User
    posts: [Post]
    post(id: ID!): Post
  }

  type Mutation {
    createUser(name: String!, email: String!, age: Int): User
    updateUser(id: ID!, name: String, email: String, age: Int): User
    deleteUser(id: ID!): Boolean
  }
`

// Resolvers
const resolvers = {
  Query: {
    users: () => users,
    user: (_, { id }) => users.find(user => user.id == id),
    posts: () => posts,
    post: (_, { id }) => posts.find(post => post.id == id)
  },
  Mutation: {
    createUser: (_, { name, email, age }) => {
      const newUser = {
        id: users.length + 1,
        name,
        email,
        age
      }
      users.push(newUser)
      return newUser
    },
    updateUser: (_, { id, ...updates }) => {
      const userIndex = users.findIndex(u => u.id == id)
      if (userIndex === -1) throw new Error('User not found')
      users[userIndex] = { ...users[userIndex], ...updates }
      return users[userIndex]
    },
    deleteUser: (_, { id }) => {
      const userIndex = users.findIndex(u => u.id == id)
      if (userIndex === -1) return false
      users.splice(userIndex, 1)
      return true
    }
  },
  User: {
    posts: (user) => posts.filter(post => post.authorId === user.id)
  },
  Post: {
    author: (post) => users.find(user => user.id === post.authorId)
  }
}

async function startServer() {
  const app = express()
  const server = new ApolloServer({ typeDefs, resolvers })

  await server.start()
  server.applyMiddleware({ app })

  app.listen(4000, () => {
    console.log(`GraphQL server ready at http://localhost:4000${server.graphqlPath}`)
  })
}

startServer()

This GraphQL API defines types for User and Post with relationships, queries for fetching data, and mutations for modifying data. Resolvers handle the business logic for each field, and Apollo Server provides introspection and GraphQL Playground for testing. The schema enforces type safety while allowing flexible queries.

Best Practice Note:

This GraphQL pattern is used in CoreUI’s advanced backend templates for complex data requirements. Always implement proper authentication, add input validation, and consider using DataLoader for efficient database queries to prevent N+1 problems in production applications.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to Get Unique Values from a JavaScript Array
How to Get Unique Values from a JavaScript Array

How to Hide Scrollbar with CSS
How to Hide Scrollbar with CSS

How to loop inside React JSX
How to loop inside React JSX

How to replace all occurrences of a string in JavaScript?
How to replace all occurrences of a string in JavaScript?

Answers by CoreUI Core Team