Introduction to GraphQL Federation

Tutorial 1 of 5

Introduction to GraphQL Federation

1. Introduction

This tutorial aims to give you an introduction to GraphQL Federation, a set of tools developed by Apollo that extends the power of GraphQL. GraphQL Federation allows you to create a unified, single schema from multiple, separate GraphQL services.

By the end of this tutorial, you will understand what GraphQL Federation is, why it's beneficial, and how to set up a federated architecture.

Prerequisites

Basic knowledge of GraphQL and Node.js are necessary to follow along with this tutorial. Familiarity with Apollo Server would also be beneficial.

2. Step-by-Step Guide

GraphQL Federation allows for a microservices architecture where each team can work on their own services without having to know the entire schema. It enables schema separation, while still allowing queries across multiple services.

The main concepts behind GraphQL Federation are:

  • Federation schema: This is the combined schema that clients interact with. It's made up of multiple individual service schemas, stitched together by the federation.
  • Service schemas: These are the individual microservice schemas. They are combined to form the federation schema.
  • Resolvers: These are functions that fetch data for a particular field in the schema. In a federated architecture, the resolvers can fetch data from their own local microservice or from another service in the federation.

3. Code Examples

Let's look at a basic example of setting up a federated schema. In this scenario, we have two services: one for users and one for reviews.

User Service

// Define the schema
const typeDefs = gql`
  type User @key(fields: "id") {
    id: ID!
    username: String
  }
`;

// Define the resolvers
const resolvers = {
  User: {
    __resolveReference(user, { dataSources }) {
      return dataSources.usersAPI.getUser(user.id);
    },
  },
};

// Create the Apollo Server
const server = new ApolloServer({
  schema: buildFederatedSchema([{ typeDefs, resolvers }]),
  dataSources: () => ({
    usersAPI: new UsersAPI(),
  }),
});

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

In this example, the User type has a @key directive which specifies the field that can be used to fetch a User object across services.

Review Service

// Define the schema
const typeDefs = gql`
  type Review @key(fields: "id") {
    id: ID!
    user: User
  }
  extend type User @key(fields: "id") {
    id: ID! @external
    reviews: [Review]
  }
`;

// Define the resolvers
const resolvers = {
  Review: {
    user(review) {
      return { __typename: "User", id: review.userId };
    },
  },
  User: {
    reviews(user) {
      return reviewsAPI.getReviewsForUser(user.id);
    },
  },
};

// Create the Apollo Server
const server = new ApolloServer({
  schema: buildFederatedSchema([{ typeDefs, resolvers }]),
  dataSources: () => ({
    reviewsAPI: new ReviewsAPI(),
  }),
});

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

In this example, the Review type extends the User type, meaning it can use the User's fields in its resolvers.

4. Summary

In this tutorial, we have covered the basics of GraphQL Federation, how to set it up and the benefits it provides in a microservices architecture. To continue your learning, consider exploring how to handle errors and set up authorization and authentication in a federated architecture.

5. Practice Exercises

  1. Exercise 1: Set up a federated schema with three services: Users, Reviews, and Products.

  2. Exercise 2: Extend the User type in the Reviews service to include a reviewsCount field that returns the number of reviews for a user.

  3. Exercise 3: Extend the User type in the Products service to include a productsCount field that returns the number of products a user has listed.

Remember, practice is critical in mastering any new subject. Keep exploring GraphQL Federation and experimenting with different schemas and services.