Build unified GraphQL APIs across microservices with Apollo Federation
# GraphQL Federation for Microservices
Master distributed GraphQL with Apollo Federation using Google Antigravity IDE. This guide covers subgraph design, entity resolution, and gateway configuration.
## Why GraphQL Federation?
Federation enables composing multiple GraphQL services into a unified API. Google Antigravity IDE's Gemini 3 engine suggests optimal schema design patterns.
## Subgraph: Users Service
```typescript
// services/users/src/schema.ts
import { gql } from "graphql-tag";
import { buildSubgraphSchema } from "@apollo/subgraph";
const typeDefs = gql`
extend schema
@link(url: "https://specs.apollo.dev/federation/v2.0",
import: ["@key", "@shareable", "@external", "@provides", "@requires"])
type Query {
user(id: ID!): User
users(limit: Int, offset: Int): [User!]!
me: User
}
type Mutation {
createUser(input: CreateUserInput!): User!
updateUser(id: ID!, input: UpdateUserInput!): User!
}
type User @key(fields: "id") {
id: ID!
email: String!
name: String!
avatar: String
role: UserRole!
createdAt: DateTime!
updatedAt: DateTime!
}
enum UserRole {
ADMIN
USER
GUEST
}
input CreateUserInput {
email: String!
name: String!
password: String!
}
input UpdateUserInput {
name: String
avatar: String
}
scalar DateTime
`;
const resolvers = {
Query: {
user: async (_, { id }, { dataSources }) => {
return dataSources.userAPI.getUser(id);
},
users: async (_, { limit, offset }, { dataSources }) => {
return dataSources.userAPI.getUsers({ limit, offset });
},
me: async (_, __, { user, dataSources }) => {
if (!user) return null;
return dataSources.userAPI.getUser(user.id);
},
},
Mutation: {
createUser: async (_, { input }, { dataSources }) => {
return dataSources.userAPI.createUser(input);
},
updateUser: async (_, { id, input }, { dataSources }) => {
return dataSources.userAPI.updateUser(id, input);
},
},
User: {
__resolveReference: async (user, { dataSources }) => {
return dataSources.userAPI.getUser(user.id);
},
},
};
export const schema = buildSubgraphSchema([{ typeDefs, resolvers }]);
```
## Subgraph: Orders Service
```typescript
// services/orders/src/schema.ts
import { gql } from "graphql-tag";
import { buildSubgraphSchema } from "@apollo/subgraph";
const typeDefs = gql`
extend schema
@link(url: "https://specs.apollo.dev/federation/v2.0",
import: ["@key", "@shareable", "@external", "@provides", "@requires"])
type Query {
order(id: ID!): Order
orders(userId: ID, status: OrderStatus, limit: Int): [Order!]!
}
type Mutation {
createOrder(input: CreateOrderInput!): Order!
updateOrderStatus(id: ID!, status: OrderStatus!): Order!
}
type Order @key(fields: "id") {
id: ID!
user: User!
items: [OrderItem!]!
status: OrderStatus!
total: Float!
shippingAddress: Address!
createdAt: DateTime!
updatedAt: DateTime!
}
type OrderItem {
product: Product!
quantity: Int!
price: Float!
}
type Address {
street: String!
city: String!
state: String!
zipCode: String!
country: String!
}
enum OrderStatus {
PENDING
CONFIRMED
SHIPPED
DELIVERED
CANCELLED
}
input CreateOrderInput {
items: [OrderItemInput!]!
shippingAddress: AddressInput!
}
input OrderItemInput {
productId: ID!
quantity: Int!
}
input AddressInput {
street: String!
city: String!
state: String!
zipCode: String!
country: String!
}
# Extend User from users service
extend type User @key(fields: "id") {
id: ID! @external
orders: [Order!]!
}
# Reference Product from products service
extend type Product @key(fields: "id") {
id: ID! @external
}
scalar DateTime
`;
const resolvers = {
Query: {
order: async (_, { id }, { dataSources }) => {
return dataSources.orderAPI.getOrder(id);
},
orders: async (_, args, { dataSources }) => {
return dataSources.orderAPI.getOrders(args);
},
},
Mutation: {
createOrder: async (_, { input }, { user, dataSources }) => {
return dataSources.orderAPI.createOrder(user.id, input);
},
updateOrderStatus: async (_, { id, status }, { dataSources }) => {
return dataSources.orderAPI.updateStatus(id, status);
},
},
Order: {
__resolveReference: async (order, { dataSources }) => {
return dataSources.orderAPI.getOrder(order.id);
},
user: (order) => ({ __typename: "User", id: order.userId }),
items: (order) => order.items.map(item => ({
...item,
product: { __typename: "Product", id: item.productId },
})),
},
User: {
orders: async (user, _, { dataSources }) => {
return dataSources.orderAPI.getOrdersByUser(user.id);
},
},
};
export const schema = buildSubgraphSchema([{ typeDefs, resolvers }]);
```
## Gateway Configuration
```typescript
// gateway/src/index.ts
import { ApolloServer } from "@apollo/server";
import { expressMiddleware } from "@apollo/server/express4";
import { ApolloGateway, IntrospectAndCompose } from "@apollo/gateway";
import express from "express";
const gateway = new ApolloGateway({
supergraphSdl: new IntrospectAndCompose({
subgraphs: [
{ name: "users", url: process.env.USERS_SERVICE_URL },
{ name: "orders", url: process.env.ORDERS_SERVICE_URL },
{ name: "products", url: process.env.PRODUCTS_SERVICE_URL },
],
}),
});
const server = new ApolloServer({
gateway,
plugins: [
{
async requestDidStart() {
return {
async didEncounterErrors({ errors }) {
errors.forEach(error => {
console.error("GraphQL Error:", error);
});
},
};
},
},
],
});
await server.start();
const app = express();
app.use(
"/graphql",
express.json(),
expressMiddleware(server, {
context: async ({ req }) => ({
user: await getUserFromToken(req.headers.authorization),
}),
})
);
app.listen(4000, () => {
console.log("Gateway running at http://localhost:4000/graphql");
});
```
## Best Practices
- Design entities with clear ownership
- Use @key for entity references
- Implement __resolveReference for lookups
- Apply DataLoader for batching
- Version schemas carefully
- Monitor subgraph health
Google Antigravity IDE provides Federation templates and automatically validates schema composition across your microservices.This GraphQL prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their graphql implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For GraphQL projects, consider mentioning your framework version, coding style, and any specific libraries you're using.