Suppose you have three separate services, each with their own GraphQL API: users
, products
, and orders
. Each service has its own data schema and data sources. You want to create a unified GraphQL API that allows clients to query across all three services, and get back a single result.
To do this, you can use GraphQL federation. Here's an example:
type User @key(fields: "id") { id: ID! name: String! email: String! } type Query { user(id: ID!): User }
The @key
directive tells GraphQL federation that the User
type is a federated type, and that the id
field is the primary key for this type.
You would define similar schemas for the products
and orders
services.
Next, you set up the federation gateway. This is the unified GraphQL API that clients will query. Here's an example of how to set up the gateway:
const { ApolloServer } = require('apollo-server'); const { ApolloGateway } = require('@apollo/gateway'); const gateway = new ApolloGateway({ serviceList: [ { name: 'users', url: 'http://localhost:4001' }, { name: 'products', url: 'http://localhost:4002' }, { name: 'orders', url: 'http://localhost:4003' }, ], }); const server = new ApolloServer({ gateway, subscriptions: false, }); server.listen().then(({ url }) => { console.log(`Gateway server ready at ${url}`); });
The ApolloGateway
constructor takes a list of services, each with a name
and a url
. These are the URLs of the individual GraphQL APIs for each service. When a client queries the gateway, it will forward the query to the appropriate service based on the @key
directives in the schema.
Now you can query the federation gateway just like any other GraphQL API. Here's an example of how to query the User
type:
query { user(id: "1") { id name email } }
When the federation gateway receives this query, it will forward it to the users
service, which will return the User
object with the corresponding id
. If the query had requested fields from the products
or orders
services as well, the gateway would forward the appropriate parts of the query to those services as well, and combine the results into a single response.
This is just a simple example, but GraphQL federation can be used for much more complex scenarios as well, where you have multiple services with complex data schemas and data sources, and you want to create a unified API for clients to query across all of them.