Gateway composition helps combine data from different sources into one simple API. It makes it easy to get all needed info in one place.
0
0
Gateway composition in GraphQL
Introduction
You have multiple services each with its own GraphQL API and want to combine them.
You want to hide complexity of many data sources behind one API for your app.
You need to join data from different teams' APIs without changing their code.
You want to improve performance by fetching related data in one request.
You want to add a single entry point for clients to access all backend data.
Syntax
GraphQL
const gateway = new ApolloGateway({ serviceList: [ { name: 'users', url: 'http://localhost:4001/graphql' }, { name: 'products', url: 'http://localhost:4002/graphql' } ] }); const server = new ApolloServer({ gateway, subscriptions: false });
The serviceList contains all GraphQL services to combine.
Subscriptions are usually disabled in gateway setup.
Examples
This example sets up a gateway combining accounts and reviews services.
GraphQL
const gateway = new ApolloGateway({ serviceList: [ { name: 'accounts', url: 'http://localhost:4001/graphql' }, { name: 'reviews', url: 'http://localhost:4002/graphql' } ] });
This creates the Apollo Server using the gateway and disables subscriptions.
GraphQL
const server = new ApolloServer({ gateway, subscriptions: false });
Sample Program
This program creates a gateway combining two services: users and products. It starts the server and logs the URL.
GraphQL
import { ApolloServer } from 'apollo-server'; import { ApolloGateway } from '@apollo/gateway'; const gateway = new ApolloGateway({ serviceList: [ { name: 'users', url: 'http://localhost:4001/graphql' }, { name: 'products', url: 'http://localhost:4002/graphql' } ] }); const server = new ApolloServer({ gateway, subscriptions: false }); server.listen().then(({ url }) => { console.log(`🚀 Gateway ready at ${url}`); });
OutputSuccess
Important Notes
Each service must have a GraphQL schema that supports federation.
Gateway merges schemas and resolves queries across services automatically.
Make sure services are running before starting the gateway.
Summary
Gateway composition combines multiple GraphQL services into one API.
It simplifies client requests by providing a single endpoint.
Use ApolloGateway with a list of services and disable subscriptions.