How to Use @external Directive in GraphQL for Federation
Use the
@external directive in GraphQL federation to mark fields that are defined in another service but referenced in your local schema. It allows you to extend types by indicating which fields come from external schemas, enabling schema stitching across services.Syntax
The @external directive is used on fields inside an extend type to mark them as coming from another service. This tells the GraphQL gateway that the field is not resolved locally but exists in a different federated service.
Basic syntax:
extend type TypeName {
fieldName: FieldType @external
}Here, TypeName is the type you want to extend, fieldName is the field from another service, and @external marks it as external.
graphql
extend type Product {
upc: String! @external
}Example
This example shows how to extend a Product type by referencing an external field upc from another service. The @external directive marks upc as defined elsewhere, allowing you to add a new local field price.
graphql
extend type Product { upc: String! @external price: Int } # This schema assumes 'upc' is defined in another federated service. # 'price' is resolved locally here.
Common Pitfalls
- Not using
@externalon fields that come from other services causes schema validation errors. - Forgetting to use
extend typewhen adding external fields leads to conflicts with original type definitions. - Using
@externalon fields that are actually resolved locally can cause unexpected behavior.
Correct usage requires marking only fields from other services and extending the type properly.
graphql
type Product { upc: String! # Wrong: should be @external and use extend price: Int } # Correct: extend type Product { upc: String! @external price: Int }
Quick Reference
| Directive | Purpose | Usage Context |
|---|---|---|
| @external | Marks a field as defined in another federated service | Used on fields inside extend type |
| extend type | Adds fields to an existing type from another service | Used to extend types with external fields |
| @key | Defines the primary key for a federated type | Used on base types to identify entities |
Key Takeaways
Use @external only on fields defined in other federated services.
Always use extend type when adding external fields to a type.
Do not mark locally resolved fields with @external.
@external helps GraphQL federation stitch schemas across services.
Combine @external with @key and other federation directives for full schema federation.