Using Apollo Federation for Microservices

Tutorial 2 of 5

Introduction

In this tutorial, we'll delve into the world of microservices architecture, focusing on Apollo Federation—an integral tool for combining schemas and executing federated queries. Our goal is to learn how to effectively use Apollo Federation in a microservices environment.

By the end of this tutorial, you will be able to:

  • Understand the basics of Apollo Federation
  • Implement Apollo Federation in a microservices architecture
  • Execute federated queries

Prerequisites:

  • A basic understanding of JavaScript and Node.js
  • Familiarity with GraphQL concepts

Step-by-Step Guide

Apollo Federation is a way of building a data graph composed of multiple services, each represented by a different part of your graph's schema. Here's how to use it:

1. Define your services

Each service represents a part of your graph's schema. Each service runs as a standalone GraphQL server and implements part of the schema.

2. Compose a supergraph schema

Apollo Router combines each service's partial schema into a single federated schema, also known as the supergraph schema.

3. Query your graph

Clients send queries to Apollo Router as if it were a standard GraphQL server. The router distributes each incoming query across your services, fetches the combined data, and returns it to the client.

Code Examples

Defining Services

// Define a product service
const { ApolloServer, gql } = require('apollo-server');
const { buildFederatedSchema } = require('@apollo/federation');

const typeDefs = gql`
  type Product @key(fields: "upc") {
    upc: String!
    name: String
    price: Int
  }
`;

const resolvers = {
  Product: {
    __resolveReference(object) {
      return {
        upc: object.upc,
        name: 'Table',
        price: 899,
      };
    },
  },
};

const server = new ApolloServer({
  schema: buildFederatedSchema([{ typeDefs, resolvers }]),
});

server.listen({ port: 4001 }).then(({ url }) => {
  console.log(`Product service ready at ${url}`);
});

This code defines a product service and attaches it to the Apollo server.

Running Federated Queries

// ApolloClient setup
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';

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

// Running a federated query
const GET_PRODUCTS = gql`
  query GetProducts {
    products {
      upc
      name
      price
    }
  }
`;

client.query({ query: GET_PRODUCTS }).then(result => console.log(result));

Here, we use ApolloClient to send a federated GraphQL query to the Apollo server. The result will print the response from the server.

Summary

In this tutorial, we learned about Apollo Federation and how to use it in a microservices architecture. We defined services, composed a supergraph schema, and executed federated queries.

For further learning, you can delve into advanced features of Apollo Federation like managed federation, schema checks, and usage reporting.

Practice Exercises

  1. Define a new service for user information containing fields such as id, name, and email.
  2. Extend the product type to include a new field user that fetches data from the user service.
  3. Write a federated GraphQL query to fetch products along with the user's information.

Remember, practice makes perfect. Keep experimenting with different schemas and federated queries to get a good grasp of Apollo Federation.

Additional Resources