API Reference: @apollo/subgraph

Build a federation-ready subgraph schema for Apollo Server


This API reference documents the exports from the @apollo/subgraph package. Use this package to run Apollo Server as a subgraph in a federated supergraph. For a walkthrough, see Implementing a subgraph with Apollo Server.

note
Apollo recommends @apollo/subgraph with Apollo Server. The package also works with any GraphQL server built on graphql-js. Version 2.15 and later require Node.js 24+ and graphql 16.11+.

buildSubgraphSchema

A function that takes federation SDL (as a DocumentNode or an array of schema modules) and returns an executable subgraph schema. The schema includes the federation directives your document imports with @link, plus the _service and _entities root fields the router uses to inspect the subgraph and resolve entities.

TypeScript
1const server = new ApolloServer({
2  schema: buildSubgraphSchema([{ typeDefs, resolvers }]),
3});

Use buildSubgraphSchema when defining a subgraph in a federated graph.

Each schema module has the following shape:

TypeScript
1{
2  typeDefs: DocumentNode,
3  resolvers?: GraphQLResolverMap
4}
note
As of @apollo/subgraph v2.15, pass an array of schema modules (or a DocumentNode) to buildSubgraphSchema. A single { typeDefs, resolvers } object is no longer valid. The deprecated buildFederatedSchema alias is also removed.

Parameters

Name /
Type
Description
modulesOrSDL
BuildSubgraphSchemaInput
Required. One of the following:
  • An array of schema modules ({ typeDefs, resolvers? }) and/or DocumentNodes
  • A single DocumentNode
Pass typeDefs as a DocumentNode (for example, the result of the gql tag from graphql-tag). Don't pass a raw SDL string.If the assembled schema isn't a valid GraphQL schema, buildSubgraphSchema throws a GraphQLSchemaValidationError.

Example

TypeScript
1import gql from 'graphql-tag';
2import { ApolloServer } from '@apollo/server';
3import { buildSubgraphSchema } from '@apollo/subgraph';
4
5const typeDefs = gql`
6  extend schema
7    @link(
8      url: "https://specs.apollo.dev/federation/v2.9"
9      import: ["@key"]
10    )
11
12  type Query {
13    me: User
14  }
15
16  type User @key(fields: "id") {
17    id: ID!
18    username: String
19  }
20`;
21
22const resolvers = {
23  Query: {
24    me() {
25      return { id: '1', username: '@ava' };
26    },
27  },
28  User: {
29    __resolveReference(reference) {
30      return fetchUserById(reference.id);
31    },
32  },
33};
34
35const server = new ApolloServer({
36  schema: buildSubgraphSchema([{ typeDefs, resolvers }]),
37});

Without an extend schema @link(...) definition, buildSubgraphSchema treats the document as a Federation 1 subgraph.

printSubgraphSchema

Prints a subgraph GraphQLSchema back to SDL, including federation directive applications, federation types, and the _service / _entities root fields.

TypeScript
1import { printSubgraphSchema } from '@apollo/subgraph';
2
3const sdl = printSubgraphSchema(schema);

Use printSubgraphSchema to inspect the schema your subgraph actually executes. As of @apollo/subgraph v2.15, the printed SDL includes the complete schema (federation directives, types, and root fields). Use printSubgraphSchema instead of GraphQL.js printSchema when you need federation @key (and similar) annotations in the printed SDL.

Parameters

Name /
Type
Description
schema
GraphQLSchema
Required. The executable schema to print, usually the result of buildSubgraphSchema.

addResolversToSchema

Requires ≥ @apollo/subgraph v2.15

Attaches a resolver map to an existing GraphQLSchema in place. In addition to field resolvers, this function recognizes:

  • __resolveReference (stored on the type as extensions.apollo.subgraph.resolveReference)

  • __resolveType

  • __isTypeOf

TypeScript
1import { addResolversToSchema } from '@apollo/subgraph';
2
3addResolversToSchema(schema, {
4  User: {
5    __resolveReference(reference) {
6      return fetchUserById(reference.id);
7    },
8  },
9});

buildSubgraphSchema calls addResolversToSchema for you when you pass resolvers on a schema module. Call it yourself when you build or transform a schema outside that flow.

Parameters

Name /
Type
Description
schema
GraphQLSchema
Required. The schema to attach resolvers to. This function mutates the schema.
resolvers
GraphQLResolverMap
Required. A map of type names to field resolvers, reference resolvers, scalars, or enum value maps.

entitiesResolver

Requires ≥ @apollo/subgraph v2.15

The resolver for Query._entities. The router sends a list of entity representations—objects with __typename plus the fields of one of the entity's @keys—and this function returns the corresponding entities in the same order.

TypeScript
1import { entitiesResolver } from '@apollo/subgraph';
2
3const resolvers = {
4  Query: {
5    _entities(_source, { representations }, context, info) {
6      return entitiesResolver({ representations, context, info });
7    },
8  },
9};

buildSubgraphSchema installs this resolver on Query._entities when the schema has entities. Call entitiesResolver only when you assemble _entities yourself (for example, in a subgraph library that doesn't use buildSubgraphSchema).

Each representation is resolved through that type's __resolveReference function. If a type has no __resolveReference, the representation is returned unchanged (with __typename applied).

Parameters

Name /
Type
Description
representations
Array
Required. Entity representations from the router's _entities argument.
context
Object
Required. The GraphQL context value for the operation. Passed through to each __resolveReference call.
info
GraphQLResolveInfo
Required. The GraphQL.js resolve info for the _entities field. Used to look up types in the schema and, when you run under Apollo Server with cache control enabled, to apply @cacheControl hints from the selected type.

__resolveReference

The name of a special reference resolver you define for each entity in a subgraph schema's resolver map.

__resolveReference enables the router to resolve an entity by the unique identifier other subgraphs use to reference it. For details, see Defining an entity.

If the entity can be resolved, __resolveReference returns the entity. Otherwise, it returns null.

You can also set a reference resolver on a type with extensions.apollo.subgraph.resolveReference. addResolversToSchema stores __resolveReference that way for you.

Parameters

Name /
Type
Description
reference
Object
The representation of the entity that's passed from another subgraph.This object includes a __typename field, along with whichever fields the subgraph uses for the entity's @key.
context
Object
An object that's passed to every resolver that executes for a particular operation, so resolvers can share helpful context.Within resolvers and plugins, this object is named contextValue. For details, see The context argument.
info
GraphQLResolveInfo
Contains information about the operation's execution state, including the field name, the path to the field from the root, and more.This object's core fields are listed in the GraphQL.js GraphQLResolveInfo type.

Example

TypeScript
1const typeDefs = gql`
2  type User @key(fields: "id") {
3    id: ID!
4    username: String
5  }
6`;
7
8const resolvers = {
9  User: {
10    __resolveReference(reference) {
11      // reference always includes `id` and `__typename`
12      return fetchUserById(reference.id);
13    },
14  },
15};

Error classes

@apollo/subgraph throws the following errors when it can't build or interpret a subgraph schema:

Name Description
GraphQLSchemaValidationError
Thrown when the assembled subgraph schema fails GraphQL.js validateSchema. The errors property holds the underlying GraphQLError list.
FederationError
Base class for federation-specific failures.
MultipleFederationLinksError
Thrown when a document @links the federation specification more than once.
UnsupportedFederationVersionError
Thrown when a @link URL names a federation version this package doesn't support. @apollo/subgraph v2.15 supports federation specification versions through v2.15.
UnsupportedLinkImportError
Thrown when a @link(import: [...]) entry is malformed or names a directive or type that isn't in the linked federation version.