Fetching and Integrating External API Data with Apollo Server 4

Introduction

In this lesson, we will learn how to fetch data from external APIs and integrate it with our GraphQL server. This skill is crucial when building real-world applications, as data often resides in different places. By combining GraphQL with external APIs, you can create a more robust and comprehensive data layer in your applications.

Previously, you learned how to handle GraphQL mutations, manage complex queries, and set up real-time subscriptions. This lesson will build on those skills, focusing on fetching external data.

Defining the Schema

A GraphQL schema defines the types and structure of queries. Here’s the schema we’ll use in this lesson:

const typeDefs = `#graphql
  type Book {
    id: ID!
    title: String!
    author: String!
  }

  type Query {
    books: [Book]
    externalBooks: [Book]
  }
`;

Here, we define a Book type with fields id, title, and author. We also define books and externalBooks queries to fetch books from local and external sources, respectively.

Creating Resolvers

Resolvers define how to fetch data for each type in the schema. We've learned about resolvers in previous lessons, but here's a quick reminder of their purpose.

import fetch from 'node-fetch';

const resolvers = {
  Query: {
    books: () => [
      { id: '1', title: 'The Hobbit', author: 'J.R.R. Tolkien' },
      { id: '2', title: 'Harry Potter', author: 'J.K. Rowling' }
    ],
    externalBooks: async () => {
      const response = await fetch('https://api.example.com/books');
      return response.json();
    }
  }
};

In the books resolver, we return a static list of books. For externalBooks, we use node-fetch to get book data from an external API.

  • The books resolver returns a hardcoded array of book objects.
  • The externalBooks resolver performs an asynchronous operation using fetch to get data from an external URL and then returns the JSON response.

Setting Up Apollo Server

Next, we will set up Apollo Server to use our schema and resolvers.

import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';

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

const { url } = await startStandaloneServer(server, {
  listen: { port: 4000 },
});

console.log(`🚀 Server ready at ${url}`);

This code initializes Apollo Server with our defined schema and resolvers and then starts the server using startStandaloneServer. Once running, you should see:

🚀 Server ready at http://localhost:4000/
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal