w3resource

Composable networking for GraphQL


Apollo Link is a standard interface for modifying control flow of GraphQL requests and fetching GraphQL results.

This is the official guide for getting started with Apollo Link in your application. Apollo Link is a simple yet powerful way to describe how you want to get the result of a GraphQL operation, and what you want to do with the results. You've probably come across "middleware" that might transform a request and its result: Apollo Link is an abstraction that's meant to solve similar problems in a much more flexible and elegant way.

You can use Apollo Link with Apollo Client, graphql-tools schema stitching, GraphiQL, and even as a standalone client, allowing you to reuse the same authorization, error handling, and control flow across all of your GraphQL fetching.

Introduction

In a few words, Apollo Links are chainable "units" that you can snap together to define how each GraphQL request is handled by your GraphQL client. When you fire a GraphQL request, each Link's functionality is applied one after another. This allows you to control the request lifecycle in a way that makes sense for your application.

If you're new to Apollo Link, you should read the concepts guide which explains the motivation behind the package and its different pieces.

Installation

npm install apollo-link

Apollo Link has two main exports, the ApolloLink interface and the execute function. The ApolloLink interface is used to create custom links, compose multiple links together, and can be extended to support more powerful use cases. The execute function allows you to create a request with a link and an operation. For a deeper dive on how to use links in your application, check out our Apollo Link concepts guide.

Usage

Apollo Link is easy to use with a variety of GraphQL libraries. It's designed to go anywhere you need to fetch GraphQL results.

Apollo Client

Apollo Client works seamlessly with Apollo Link. A Link is one of the required items when creating an Apollo Client instance. For simple HTTP requests, we recommend using apollo-link-http:

import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { createHttpLink } from 'apollo-link-http';

const client = new ApolloClient({
  link: createHttpLink({ uri: 'http://localhost:4000/graphql' }),
  cache: new InMemoryCache()
});

graphql-tools

You can also use Apollo Link with graphql-tools to facilitate schema stitching by using node-fetch as your request link's fetcher function and passing it to makeRemoteExecutableSchema.

import { HttpLink } from 'apollo-link-http';
import fetch from 'node-fetch';
const link = new HttpLink({ uri: 'http://localhost:4000/graphql', fetch });
const schema = await introspectSchema(link);
const executableSchema = makeRemoteExecutableSchema({
  schema,
  link,
});

GraphiQL

GraphiQL is a great way to document and explore your GraphQL API. In this example, we're setting up GraphiQL's fetcher function by using the execute function exported from Apollo Link. This function takes a link and an operation to create a GraphQL request.

import React from 'react';
import ReactDOM from 'react-dom';
import '../node_modules/graphiql/graphiql.css'
import GraphiQL from 'graphiql';
import { parse } from 'graphql';
import { execute } from 'apollo-link';
import { HttpLink } from 'apollo-link-http';

const link = new HttpLink({
  uri: 'http://localhost:4000/graphql'
});

const fetcher = (operation) => {
  operation.query = parse(operation.query);
  return execute(link, operation);
};

ReactDOM.render(
  <GraphiQL fetcher={fetcher}/>,
  document.body,
);

With this setup, we're able to construct an arbitrarily complicated set of links (e.g. with polling, batching, etc.) and test it out using GraphiQL. This is incredibly useful for debugging as you're building a Link-based application.

Relay Modern

You can use Apollo Link as a network layer with Relay Modern.

import {Environment, Network, RecordSource, Store} from 'relay-runtime';
import {execute, makePromise} from 'apollo-link';
import {HttpLink} from 'apollo-link-http';
import {parse} from 'graphql';

const link = new HttpLink({
  uri: 'http://localhost:4000/graphql'
});

const source = new RecordSource();
const store = new Store(source);
const network = Network.create(
  (operation, variables) => makePromise(
    execute(link, {
      query: parse(operation.text),
      variables
    })
  )
);
const environment = new Environment({
    network,
    store
});

Standalone

You can also use Apollo Link as a standalone client. That is, you can use it to fire requests and receive responses from a GraphQL server. However, unlike a full client implementation such as Apollo Client, Apollo Link doesn't come with a reactive cache, UI bindings, etc. To use Apollo Link as a standalone client, we're using the execute function exported by Apollo Link in the following code sample:

import { execute, makePromise } from 'apollo-link';
import { HttpLink } from 'apollo-link-http';
import gql from 'graphql-tag';
const uri ='http://localhost:4000/graphql';
const link = new HttpLink({ uri });

const operation = {
  query: gql`query { hello }`,
  variables: {} //optional
  operationName: {} //optional
  context: {} //optional
  extensions: {} //optional
};

// execute returns an Observable so it can be subscribed to
execute(link, operation).subscribe({
  next: data => console.log(`received data: ${JSON.stringify(data, null, 2)}`),
  error: error => console.log(`received error ${error}`),
  complete: () => console.log(`complete`),
})

// For single execution operations, a Promise can be used
makePromise(execute(link, operation))
  .then(data => console.log(`received data ${JSON.stringify(data, null, 2)}`))
  .catch(error => console.log(`received error ${error}`))

Note: to run Apollo Link on the server, ensure that you install node-fetch and pass its default export to as the fetch parameter to HttpLink

execute accepts a standard GraphQL request and returns an Observable that allows subscribing. A GraphQL request is an object with a query which is a GraphQL document AST, variables which is an object to be sent to the server, an optional operationName string to make it easy to debug a query on the server, and a context object to send data directly to a link in the chain. Links use observables to support GraphQL subscriptions, live queries, and polling, in addition to single response queries and mutations.

makePromise is similar to execute, except it returns a Promise. You can use makePromise for single response operations such as queries and mutations.

If you want to control how you handle errors, next will receive GraphQL errors, while error be called on a network error. We recommend using apollo-link-error instead.

Previous: Swift scripting
Next: Swift Scripting: Downloading a schema