Build a GraphQL API with Apollo or Express: A Complete Guide

Muhaymin Bin Mehmood

Muhaymin Bin Mehmood

· 8 min read
Build a GraphQL API with Apollo or Express: A Complete Guide Banner Image
Build a GraphQL API with Apollo or Express: A Complete Guide Banner Image

GraphQL has become one of the most powerful and efficient ways to build APIs, offering greater flexibility, precision, and scalability compared to traditional REST APIs. Developed by Facebook in 2012, GraphQL allows clients to request only the data they need, reducing the over-fetching and under-fetching of data, thus improving performance. In this comprehensive tutorial, we will walk you through the process of creating a GraphQL server using Apollo Server. We’ll cover every detail from defining a schema to writing resolvers, and testing the API with popular tools like GraphQL Playground and Postman.

Whether you’re a beginner or an experienced developer, this step-by-step guide will equip you with the knowledge and skills to build a GraphQL API from scratch and implement advanced features.

Table of Contents:

  1. What is GraphQL?
  2. Why Use GraphQL?
  3. Setting Up Your Project for GraphQL API
    • Initializing the Node.js Project
    • Installing Dependencies
  4. Defining the GraphQL Schema
    • Types and Queries in GraphQL
    • Mutations in GraphQL
  5. Creating Resolvers for Your API
  6. Setting Up the Apollo Server
    • Configuring the Apollo Server
    • Integrating with Express (Optional)
  7. Testing the GraphQL API
    • Testing with GraphQL Playground
    • Using Postman to Test GraphQL Queries
  8. Best Practices for Building a GraphQL API
  9. Conclusion

1. What is GraphQL?

GraphQL is an open-source data query language and runtime for executing queries with your existing data. Unlike REST, which exposes multiple endpoints for different resources, GraphQL allows you to interact with a single endpoint. With GraphQL, you specify exactly what data you want, and the server returns that data in the exact format you requested. This eliminates redundant data and makes the API more efficient.

GraphQL allows developers to work with data in a more intuitive way, enabling features like real-time updates, flexible queries, and simplified integration with various back-end systems.

2. Why Use GraphQL?

Here are some key reasons why developers are turning to GraphQL:

  • Precise Data Fetching: Clients can request only the data they need, reducing data transfer and improving app performance.
  • Single Endpoint: Unlike REST, where each resource typically has its own endpoint, GraphQL uses a single endpoint for all interactions.
  • Strongly Typed Schema: GraphQL provides a strongly typed schema, ensuring that the structure and shape of your data are defined upfront.
  • Real-time Updates: Using subscriptions, GraphQL allows for real-time updates, which is perfect for applications that require live data.
  • Ease of Versioning: With GraphQL, you don't need to manage multiple API versions, as you can request different shapes of data with the same endpoint.

3. Setting Up Your Project for GraphQL API

Initializing the Node.js Project

Before we start building the GraphQL API, we need to set up our project directory and install the necessary dependencies.

Create a new project directory:

mkdir graphql-api-tutorial
cd graphql-api-tutorial

Initialize a new Node.js project:

npm init -y

Install Apollo Server and GraphQL:

npm install apollo-server graphql

(Optional) Install Express if you want to integrate Apollo Server with Express:

npm install express

4. Defining the GraphQL Schema

The GraphQL schema defines the structure of your data and operations. It is the core of any GraphQL API. The schema defines types (models of data), queries (data retrieval), and mutations (data modifications).

Types and Queries in GraphQL

A typical GraphQL schema starts with defining types. In this example, we’ll define a Post type for a blog API.

Example Schema (schema.js):

const { gql } = require('apollo-server');

const typeDefs = gql`
  type Post {
    id: ID!
    title: String!
    content: String!
  }

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

  type Mutation {
    createPost(title: String!, content: String!): Post
  }
`;

module.exports = typeDefs;
  • Post type: Defines the structure of the data for a blog post.
  • Query type: Defines the data retrieval operations (posts for fetching all posts, post(id) for fetching a single post by ID).
  • Mutation type: Defines the createPost mutation to allow the creation of new blog posts.

Mutations in GraphQL

Mutations are used for creating, updating, or deleting data. The createPost mutation accepts title and content as input and returns the newly created post.

5. Creating Resolvers for Your API

Resolvers are functions that resolve a GraphQL query or mutation. They contain the logic to fetch the data and return it to the client.

Example Resolvers (resolvers.js):

let posts = [
  { id: '1', title: 'GraphQL Basics', content: 'Learn GraphQL step by step.' },
  { id: '2', title: 'Apollo Server Setup', content: 'How to set up Apollo Server for GraphQL.' },
];

const resolvers = {
  Query: {
    posts: () => posts,
    post: (_, { id }) => posts.find(post => post.id === id),
  },
  Mutation: {
    createPost: (_, { title, content }) => {
      const newPost = { id: `${posts.length + 1}`, title, content };
      posts.push(newPost);
      return newPost;
    },
  },
};

module.exports = resolvers;

In the above code:

  • The posts query fetches all blog posts.
  • The post(id) query fetches a single post based on the provided ID.
  • The createPost mutation adds a new post to the posts array.

6. Setting Up the Apollo Server

Now, let’s integrate the schema and resolvers into Apollo Server to handle GraphQL requests.

Example Apollo Server Setup (index.js):

const { ApolloServer } = require('apollo-server');
const typeDefs = require('./schema');
const resolvers = require('./resolvers');

const server = new ApolloServer({
  typeDefs,
  resolvers,
});

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});

This will start the Apollo Server on http://localhost:4000. The server is now ready to accept GraphQL queries and mutations.

(Optional) Integrating with Express

If you want to use Apollo Server with Express, you can integrate it as follows:

const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const typeDefs = require('./schema');
const resolvers = require('./resolvers');

const app = express();
const server = new ApolloServer({
  typeDefs,
  resolvers,
});

server.applyMiddleware({ app });

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

7. Testing the GraphQL API

Using GraphQL Playground

GraphQL Playground is an interactive tool to query and test your GraphQL API.

  • Start the Apollo Server by running:
node index.js
  • Navigate to http://localhost:4000/graphql in your browser.
  • You can now execute queries and mutations directly in the Playground.

Example Query in Playground:

query {
  posts {
    id
    title
  }
}

Example Mutation in Playground:

mutation {
  createPost(title: "New Post", content: "This is a new post.") {
    id
    title
  }
}

Using Postman

Postman allows you to test GraphQL APIs by sending requests to your server.

  • Open Postman and create a new POST request.
  • Set the URL to http://localhost:4000/graphql.
  • In the request body, choose the GraphQL option.
  • Add your query or mutation.

8. Best Practices for Building a GraphQL API

Here are some best practices for building and maintaining a GraphQL API:

  • Use DataLoader: To avoid N+1 query problems, use DataLoader to batch and cache database requests.
  • Versionless APIs: With GraphQL, you can evolve your API without breaking clients. This eliminates the need for versioning.
  • Optimize Performance: Use query complexity analysis and depth-limiting to prevent overly expensive queries.
  • Use Middleware for Authentication: Apollo Server allows middleware integration for authentication and authorization.

9. Conclusion

Building a GraphQL API from scratch has never been easier, thanks to Apollo Server and its powerful set of tools. In this tutorial, we covered everything from defining schemas and writing resolvers to setting up Apollo Server and testing the API with GraphQL Playground and Postman. With GraphQL’s flexibility and powerful features, you can create highly efficient and scalable APIs that meet the needs of modern web applications.

By mastering GraphQL and implementing best practices, you can build APIs that deliver superior performance and offer a seamless experience to your users.

Now that you have the complete knowledge of creating a GraphQL API, you can start building your own projects and explore even more advanced concepts such as subscriptions, error handling, and security measures for production environments.

By integrating GraphQL, Apollo Server, and Node.js, this guide will help you optimize your web applications for scalability, performance, and flexibility, while also providing a foundation for integrating other technologies such as React and GraphQL subscriptions.

Related Blogs

Muhaymin Bin Mehmood

About Muhaymin Bin Mehmood

Front-end Developer skilled in the MERN stack, experienced in web and mobile development. Proficient in React.js, Node.js, and Express.js, with a focus on client interactions, sales support, and high-performance applications.

Join our newsletter

Subscribe now to our newsletter for regular updates.

Copyright © 2025 Mbloging. All rights reserved.