Consuming GraphQL APIs

Learn to use Apollo Client with React and Next.js and how to write GraphQL queries.

GraphQL has been a game changer in the API world, and it’s increasing its popularity thanks to its ease of use, modularity, and flexibility. For those who are not very familiar with GraphQL, it’s basically a query language for APIs first invented by Facebook back in 2012. It improves many key aspects of data fetching and manipulation compared to other web service architectures, such as REST or SOAP. In fact, it allows us to avoid data overfetching (we can simply query the data fields we need), get multiple resources within a single request, obtain a strongly and statically typed interface for our data, avoid API versioning, and so on.

Setting up Apollo Client with Next.js

In this lesson, we’ll be using Apollo Client, a very popular GraphQL client with built-in support for both React and Next.js for building a very simple online signbook.

Let’s start with a new project:

# cd /usercode/signbook && npm install 
# npm run dev

export PORT=5000
ln -s /app/node_modules/ /usercode/signbook 
cd /usercode/signbook
npm run dev
Starting template for GraphQL project

We’ll now need to create an Apollo client for our Next.js application. For that, we add a new file, lib/apollo/index.js, and the following function:

Press + to interact
import { useMemo } from "react";
import { ApolloClient, HttpLink, InMemoryCache } from "@apollo/client";
let uri = "{{EDUCATIVE_LIVE_VM_URL}}/v1/graphql";
let apolloClient;
function createApolloClient() {
return new ApolloClient({
ssrMode: typeof window === "undefined",
link: new HttpLink({ uri }),
cache: new InMemoryCache(),
});
}

As we can assume, by setting ssrMode: typeof window === "undefined" on line 10, we’ll use the same Apollo instance for both client and server. Also, ApolloClient uses the browser fetch API to make HTTP requests, so we’ll need to import a polyfill to make it work on the server side; in that case, we’ll be using ...