0
0
GraphqlHow-ToIntermediate · 4 min read

How to Extend Type Across Services in GraphQL

In GraphQL, you can extend a type across services using the extend type syntax, which allows you to add fields to an existing type defined in another service. This is commonly used in Apollo Federation to compose a unified schema from multiple microservices.
📐

Syntax

The extend type keyword is used to add new fields to an existing GraphQL type defined in another service. It must match the original type name exactly. This helps combine schemas from different services into one.

  • extend type TypeName: Declares that you are adding fields to TypeName.
  • New fields: Define the additional fields you want to add.
graphql
extend type User {
  reviews: [Review]
}
💻

Example

This example shows two services: User Service defines a User type, and Review Service extends User to add a reviews field. Apollo Federation composes these into one schema.

graphql
# User Service schema
"""
type User @key(fields: "id") {
  id: ID!
  name: String
}
"""

# Review Service schema
"""
extend type User @key(fields: "id") {
  id: ID! @external
  reviews: [Review]
}

type Review {
  id: ID!
  content: String
}
"""
Output
Combined schema includes User with id, name, and reviews fields.
⚠️

Common Pitfalls

Common mistakes when extending types across services include:

  • Not using @key directive on the original and extended types, which is required for Apollo Federation to identify entities.
  • Forgetting to mark fields from the original service as @external in the extending service.
  • Mismatch in type names or field types between services.

Always ensure the extended type matches the original exactly and use federation directives properly.

graphql
## Wrong way (missing @external):
extend type User {
  id: ID!
  reviews: [Review]
}

## Right way:
extend type User @key(fields: "id") {
  id: ID! @external
  reviews: [Review]
}
📊

Quick Reference

Directive/KeywordPurpose
extend typeAdd fields to an existing type from another service
@key(fields: "id")Marks the primary key field for entity resolution
@externalMarks fields owned by another service
@requiresSpecifies fields needed from base type to resolve extended fields
@providesIndicates fields provided to other services

Key Takeaways

Use extend type to add fields to types defined in other GraphQL services.
Always include @key directive on types to enable federation entity resolution.
Mark fields from the original service as @external in the extending service.
Ensure type names and field types match exactly across services to avoid schema conflicts.
Apollo Federation uses these patterns to compose a unified schema from multiple microservices.