GraphQL / GraphQL with Node.js

Setting Up Apollo Server for GraphQL

In this tutorial, we will guide you through setting up Apollo Server, a community-driven, open-source GraphQL server. You'll learn how to integrate it with your existing Express.j…

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Teaches how to build GraphQL APIs using Node.js and Express.

Tutorial: Setting Up Apollo Server for GraphQL

1. Introduction

In this tutorial, we will guide you through the process of setting up an Apollo Server, an open-source GraphQL server that is driven by the community. We will also teach you how to integrate it with your existing Express.js server. By the end of this tutorial, you should have a fully functional Apollo Server running and connected with your Express.js server.

What You Will Learn

  • How to set up an Apollo Server
  • How to integrate the Apollo Server with an Express.js server

Prerequisites

  • Basic understanding of JavaScript
  • Node.js and npm installed on your system
  • Basic understanding of Express.js and GraphQL

2. Step-by-Step Guide

Setting Up Apollo Server

To start, we need to install the necessary packages. Run the following command in your terminal:

npm install apollo-server express graphql

Next, create a new file named server.js and add the following code:

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

// Create an express server
const app = express();

// A schema is a collection of type definitions (hence "typeDefs")
// that together define the "shape" of queries that are executed against
// your data.
const typeDefs = gql`
  type Query {
    hello: String
  }
`;

// Resolvers define the technique for fetching the types defined in the
// schema. This resolver retrieves the "hello" type from the "Query" type.
const resolvers = {
  Query: {
    hello: () => 'Hello world!',
  },
};

// The ApolloServer constructor requires two parameters: your schema
// definition and your set of resolvers.
const server = new ApolloServer({ typeDefs, resolvers });

// The `listen` method launches a web server.
server.applyMiddleware({ app });

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

With the server set up, you can now run it by entering the following command in your terminal:

node server.js

If everything is set up correctly, your server should be running at http://localhost:4000.

3. Code Examples

Example 1: Adding a New Type and Resolver

Let's add a new type Book and its resolver. Update your typeDefs and resolvers as follows:

const typeDefs = gql`
  type Query {
    hello: String
    books: [Book]
  }

  type Book {
    title: String
    author: String
  }
`;

const resolvers = {
  Query: {
    hello: () => 'Hello world!',
    books: () => [
      {
        title: 'Harry Potter and the Chamber of Secrets',
        author: 'J.K. Rowling',
      },
      {
        title: 'Jurassic Park',
        author: 'Michael Crichton',
      },
    ],
  },
};

Here, we've added a new type Book with fields title and author, and added a new field books to our Query type that returns an array of Book.

Example 2: Making Use of Arguments in Resolvers

GraphQL allows us to pass arguments to our queries. Let's add a new query book that takes an argument title:

const typeDefs = gql`
  type Query {
    hello: String
    books: [Book]
    book(title: String!): Book
  }

  type Book {
    title: String
    author: String
  }
`;

const books = [
  {
    title: 'Harry Potter and the Chamber of Secrets',
    author: 'J.K. Rowling',
  },
  {
    title: 'Jurassic Park',
    author: 'Michael Crichton',
  },
];

const resolvers = {
  Query: {
    hello: () => 'Hello world!',
    books: () => books,
    book: (_, { title }) => books.find(book => book.title === title),
  },
};

Now, we can query a book by its title.

4. Summary

In this tutorial, we have learned how to set up an Apollo Server and integrate it with an Express.js server. We've also learned how to define GraphQL schemas, how to create resolvers, and how to use arguments in our queries.

Next Steps

Consider exploring more complex types, mutations (to modify server-side data), and subscriptions (for real-time updates).

Additional Resources

5. Practice Exercises

  1. Exercise 1: Create a new type Author with fields name and books. books should be an array of Book. Modify the books array and the resolvers accordingly.

  2. Exercise 2: Add a mutation addBook that takes in a title and an author and adds a new book to the books array.

  3. Exercise 3: Add error handling to the book query. If a book with the given title doesn't exist, it should return an error.

Try these exercises to solidify your understanding of Apollo Server and GraphQL. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Image Converter

Convert between different image formats.

Use tool

CSV to JSON Converter

Convert CSV files to JSON format and vice versa.

Use tool

CSS Minifier & Formatter

Clean and compress CSS files.

Use tool

PDF Splitter & Merger

Split, merge, or rearrange PDF files.

Use tool

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help