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:
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.
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
booksresolver returns a hardcoded array of book objects. - The
externalBooksresolver performs an asynchronous operation usingfetchto 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.
This code initializes Apollo Server with our defined schema and resolvers and then starts the server using startStandaloneServer. Once running, you should see:
