GraphQL Composite Schemas Spec
Introduction
The GraphQL Composite Schemas introduces a comprehensive specification for creating distributed GraphQL systems that seamlessly merges multiple GraphQL schemas. This specification describes the process of composing a federated GraphQL schema and outlines algorithms for executing GraphQL queries on the federated schema effectively by using query plans. This specification was originally created by ChilliCream and was transferred to the GraphQL foundation.
The GraphQL Foundation was formed in 2019 as a neutral focal point for organizations who support the GraphQL ecosystem, and the GraphQL Specification Project was established also in 2019 as the Joint Development Foundation Projects, LLC, GraphQL Series.
If your organization benefits from GraphQL, please consider becoming a member and helping us to sustain the activities that support the health of our neutral ecosystem.
The GraphQL Specification Project has evolved and may continue to evolve in future editions of this specification. Previous editions of the GraphQL specification can be found at permalinks that match their release tag. The latest working draft release can be found at https://spec.graphql.org/draft.
Copyright notice
Copyright © 2023-present, GraphQL contributors
THESE MATERIALS ARE PROVIDED “AS IS”. The parties expressly disclaim any warranties (express, implied, or otherwise), including implied warranties of merchantability, non-infringement, fitness for a particular purpose, or title, related to the materials. The entire risk as to implementing or otherwise using the materials is assumed by the implementer and user. IN NO EVENT WILL THE PARTIES BE LIABLE TO ANY OTHER PARTY FOR LOST PROFITS OR ANY FORM OF INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER FROM ANY CAUSES OF ACTION OF ANY KIND WITH RESPECT TO THIS DELIVERABLE OR ITS GOVERNING AGREEMENT, WHETHER BASED ON BREACH OF CONTRACT, TORT (INCLUDING NEGLIGENCE), OR OTHERWISE, AND WHETHER OR NOT THE OTHER MEMBER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Conformance
A conforming implementation of GraphQL over HTTP must fulfill all normative requirements. Conformance requirements are described in this document via both descriptive assertions and key words with clearly defined meanings.
The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in the normative portions of this document are to be interpreted as described in IETF RFC 2119. These key words may appear in lowercase and still retain their meaning unless explicitly declared as non-normative.
A conforming implementation of GraphQL over HTTP may provide additional functionality, but must not where explicitly disallowed or would otherwise result in non-conformance.
Non-Normative Portions
All contents of this document are normative except portions explicitly declared as non-normative.
Examples in this document are non-normative, and are presented to aid understanding of introduced concepts and the behavior of normative portions of the specification. Examples are either introduced explicitly in prose (e.g. “for example”) or are set apart in example or counter-example blocks, like this:
Example № 1This is an example of a non-normative example.
Counter Example № 2This is an example of a non-normative counter-example.
Notes in this document are non-normative, and are presented to clarify intent, draw attention to potential edge-cases and pit-falls, and answer common questions that arise during implementation. Notes are either introduced explicitly in prose (e.g. “Note: “) or are set apart in a note block, like this:
1Overview
The GraphQL Composite Schemas specification describes how to construct a single unified GraphQL schema, the composite schema, from multiple GraphQL schemas, each termed a source schema.
The composite schema presents itself as a regular GraphQL schema; the implementation details and complexities of the underlying distributed systems are not visible to clients, all observable behavior is the same as described by the GraphQL specification.
The GraphQL Composite Schemas specification has a number of design principles:
- Composable: Rather than defining each source schema in isolation and reshaping it to fit the composite schema later, this specification encourages developers to design the source schemas as part of a larger whole from the start. Each source schema defines the types and fields it is responsible for serving within the context of the larger schema, referencing and extending that which is provided by other source schemas. The GraphQL Composite Schemas specification does not describe how to combine arbitrary schemas.
- Collaborative: The GraphQL Composite Schemas specification is explicitly designed around team collaboration. By building on a principled composition model, it ensures that conflicts and inconsistencies are surfaced early and can be resolved before deployment. This allows many teams to contribute to a single schema without the danger of breaking it. The GraphQL Composite Schemas specification facilitates the coordinated effort of combining collaboratively designed source schemas into a single coherent composite schema.
- Evolvable: A composite schema enables offering an integrated, product-centric API interface to clients; source schema boundaries are an implementation detail, a detail that is not exposed to clients. As each underlying GraphQL service evolves, the same functionality may be provided from a different combination of services. This specification helps to ensure that changes to underlying services can be made whilst maintaining support for existing requests from all clients to the composite schema interface.
- Explicitness: To make the composition process easier to understand and to avoid ambiguities that can lead to confusing failures as the system grows, the GraphQL Composite Schemas specification prefers to be explicit about intentions and minimize reliance on inference and convention.
To enable greater interoperability between different implementations of tooling and gateways, this specification focuses on two core components: schema composition and distributed execution.
- Schema Composition: Schema composition describes the process of merging multiple source schema into a single GraphQL schema, the composite schema. During this process, an intermediary schema, the composite execution schema, is generated. This composite execution schema is annotated with directives to describe execution, and may have additional internal fields or arguments that won’t be exposed in the client-facing composite schema.
- Distributed Execution: The distributed GraphQL executor specifies the core execution behavior and algorithms that enable fulfillment of a GraphQL request performed against the composite schema.
2Source Schema
A source schema is a GraphQL schema that is part of a larger composite schema. Source schemas use directives to express intent and requirements for the composition process. In the following chapters, we will describe the directives that are used to annotate a source schema.
2.1Directives
2.1.1@lookup
directive @lookup on FIELD_DEFINITION
The @lookup
directive is used within a source schema to specify output fields that can be used by the distributed GraphQL executor to resolve an entity by a stable key.
The stable key is defined by the arguments of the field. Each argument must match a field on the return type of the lookup field.
Source schemas can provide multiple lookup fields for the same entity that resolve the entity by different keys.
In this example, the source schema specifies that the Product
entity can be resolved with the productById
field or the productByName
field. Both lookup fields are able to resolve the Product
entity but do so with different keys.
Example № 3type Query {
version: Int # NOT a lookup field.
productById(id: ID!): Product @lookup
productByName(name: String!): Product @lookup
}
type Product @key(fields: "id") @key(fields: "name") {
id: ID!
name: String!
}
The arguments of a lookup field must correspond to fields specified as an entity key with the @key
directive on the entity type.
Example № 4type Query {
node(id: ID!): Node @lookup
}
interface Node @key(fields: "id") {
id: ID!
}
Lookup fields may return object, interface, or union types. In case a lookup field returns an abstract type (interface type or union type), all possible object types are considered entities and must have keys that correspond with the field’s argument signature.
Example № 5type Query {
product(id: ID!, categoryId: Int): Product @lookup
}
union Product = Electronics | Clothing
type Electronics @key(fields: "id categoryId") {
id: ID!
categoryId: Int
name: String
brand: String
price: Float
}
type Clothing @key(fields: "id categoryId") {
id: ID!
categoryId: Int
name: String
size: String
price: Float
}
The following example shows an invalid lookup field as the Clothing
type does not declare a key that corresponds with the lookup field’s argument signature.
Counter Example № 6type Query {
product(id: ID!, categoryId: Int): Product @lookup
}
union Product = Electronics | Clothing
type Electronics @key(fields: "id categoryId") {
id: ID!
categoryId: Int
name: String
brand: String
price: Float
}
# Clothing does not have a key that corresponds
# with the lookup field's argument signature.
type Clothing @key(fields: "id") {
id: ID!
categoryId: Int
name: String
size: String
price: Float
}
If the lookup returns an interface, the interface must also be annotated with a @key
directive and declare its keys.
Example № 7interface Node @key(fields: "id") {
id: ID!
}
Lookup fields must be accessible from the Query type. If not directly on the Query type, they must be accessible via fields that do not require arguments, starting from the Query root type.
Example № 8type Query {
lookups: Lookups!
}
type Lookups {
productById(id: ID!): Product @lookup
}
type Product @key(fields: "id") {
id: ID!
}
Lookups can also be nested within other lookups and allow resolving nested entities that are part of an aggregate. In the following example the Product
can be resolved by its ID but also the ProductPrice
can be resolved by passing in a composite key containing the product ID and region name of the product price.
Example № 9type Query {
productById(id: ID!): Product @lookup
}
type Product @key(fields: "id") {
id: ID!
price(regionName: String!): ProductPrice @lookup
}
type ProductPrice @key(fields: "regionName product { id }") {
regionName: String!
product: Product
value: Float!
}
Nested lookups must immediately follow the parent lookup and cannot be nested with fields in between.
Counter Example № 10type Query {
productById(id: ID!): Product @lookup
}
type Product @key(fields: "id") {
id: ID!
details: ProductDetails
}
type ProductDetails {
price(regionName: String!): ProductPrice @lookup
}
type ProductPrice @key(fields: "regionName product { id }") {
regionName: String!
product: Product
value: Float!
}
2.1.2@internal
directive @internal on FIELD_DEFINITION
The @internal
directive is used to mark lookup fields as internal. Internal lookup fields are not used as entry points in the composite schema and can only be used by the distributed GraphQL executor to resolve additional data for an entity.
Example № 11type Query {
# lookup field and possible entry point
reviewById(id: ID!): Review @lookup
# internal lookup field
productById(id: ID!): Product @lookup @internal
}
The @internal
directive provides control over which source schemas are used to resolve entities and which source schemas merely contribute data to entities. Further, using @internal
allows hiding “technical” lookup fields that are not meant for the client-facing composite schema.
2.1.3@is
directive @is(field: FieldSelectionMap!) on ARGUMENT_DEFINITION
The @is
directive is utilized on lookup fields to describe how the arguments can be mapped from the entity type that the lookup field resolves. The mapping establishes semantic equivalence between disparate type system members across source schemas and is used in cases where the argument does not 1:1 align with a field on the entity type.
In the following example, the directive specifies that the id
argument on the field Query.personById
and the field Person.id
on the return type of the field are semantically the same.
@is
directive could also be omitted as the argument and field names match.Example № 12extend type Query {
personById(id: ID! @is(field: "id")): Person @lookup
}
The @is
directive also allows referring to nested fields relative to Person
.
Example № 13extend type Query {
personByAddressId(id: ID! @is(field: "address.id")): Person
}
The @is
directive is not limited to a single argument.
Example № 14extend type Query {
personByAddressId(
id: ID! @is(field: "address.id")
kind: PersonKind @is(field: "kind")
): Person
}
The @is
directive can also be used in combination with @oneOf
to specify lookup fields that can resolve entities by different keys.
Example № 15extend type Query {
person(
by: PersonByInput @is(field: "{ id } | { addressId: address.id } { name }")
): Person
}
input PersonByInput @oneOf {
id: ID
addressId: ID
name: String
}
Arguments:
field
: Represents a selection path map syntax.
2.1.4@require
directive @require(field: FieldSelectionMap!) on ARGUMENT_DEFINITION
The @require
directive is used to express data requirements with other source schemas. Arguments annotated with the @require
directive are removed from the composite schema and the value for these will be resolved by the distributed executor.
Example № 16type Product {
id: ID!
delivery(
zip: String!
size: Int! @require(field: "dimension.size")
weight: Int! @require(field: "dimension.weight")
): DeliveryEstimates
}
The upper example would translate to the following in the composite schema.
Example № 17type Product {
id: ID!
delivery(zip: String!): DeliveryEstimates
}
This can also be done by using input types. The selection path map specifies which data is required and needs to be resolved from other source schemas. If the input type is only used to express a requirements it is removed from the composite schema.
Example № 18type Product {
id: ID!
delivery(
zip: String!
dimension: ProductDimensionInput! @require(field: "{ size: dimension.size, weight: dimension.weight }"))
): DeliveryEstimates
}
If the input types do not match the output type structure the selection map syntax can be used to specify how requirements translate to the input object.
Example № 19type Product {
id: ID!
delivery(
zip: String!
dimension: ProductDimensionInput!
@require(field: "{ productSize: dimension.size, productWeight: dimension.weight }"))
): DeliveryEstimates
}
type ProductDimension {
size: Int!
weight: Int!
}
input ProductDimensionInput {
productSize: Int!
productWeight: Int!
}
Arguments:
field
: Represents a selection path map syntax.
2.1.5@key
directive @key(fields: SelectionSet!) repeatable on OBJECT | INTERFACE
The @key directive is used to designate an entity’s unique key, which identifies how to uniquely reference an instance of an entity across different source schemas. It allows a source schema to indicate which fields form a unique identifier, or key, for an entity.
Example № 20type Product @key(fields: "id") {
id: ID!
sku: String!
name: String!
price: Float!
}
Each occurrence of the @key directive on an object or interface type specifies one distinct unique key for that entity, which enables a gateway to perform lookups and resolve instances of the entity based on that key.
Example № 21type Product @key(fields: "id") @key(fields: "key") {
id: ID!
sku: String!
name: String!
price: Float!
}
While multiple keys define separate ways to reference the same entity based on different sets of fields, a composite key allows to uniquely identify an entity by using a combination of multiple fields.
Example № 22type Product @key(fields: "id sku") {
id: ID!
sku: String!
name: String!
price: Float!
}
The directive is applicable to both OBJECT and INTERFACE types. This allows entities that implement an interface to inherit the key(s) defined at the interface level, ensuring consistent identification across different implementations of that interface.
Arguments:
fields
: Represents a selection set syntax.
2.1.7@provides
directive @provides(fields: SelectionSet!) on FIELD_DEFINITION
The @provides
directive is an optimization hint specifying child fields that can be resolved locally at the given source schema through a particular query path. This allows for a variation of overlapping field to improve data fetching.
Arguments:
fields
: Represents a selection set syntax.
2.1.8@external
directive @external on OBJECT_DEFINITION | INTERFACE_DEFINITION | FIELD_DEFINITION
The @external
directive is used in combination with the @provides
directive and specifies data that is not owned ba a particular source schema.
2.1.9@override
directive @override(from: String!) on FIELD_DEFINITION
The @override
directive allows to migrate fields from one source schema to another.
3Schema Composition
The schema composition describes the process of merging multiple source schemas into a single GraphQL schema, known as the composite execution schema, which is a valid GraphQL schema annotated with execution directives. This composite execution schema is the output of the schema composition process. The schema composition process is divided into four major algorithms: Validate Source Schema, Merge Source Schema, and Validate Satisfiability, which are run in sequence to produce the composite execution schema.
3.1Validate Source Schema
3.2Merge Source Schemas
3.2.1Pre Merge Validation
3.2.2Merge
3.2.3Post Merge Validation
3.3Validate Satisfiability
4Executor
A distributed GraphQL executor acts as an orchestrator that uses schema metadata to rewrite a GraphQL request into a query plan. This plan resolves the required data from subgraphs and coerces this data into the result of the GraphQL request.
4.1Configuration
The supergraph is a GraphQL IDL document that contains metadata for the query planner that describes the relationship between type system members and the type system members on subgraphs.
6Appendix A: Specification of FieldSelectionMap Scalar
6.1Introduction
This appendix focuses on the specification of the FieldSelectionMap scalar type. FieldSelectionMap is designed to express semantic equivalence between arguments of a field and fields within the result type. Specifically, it allows defining complex relationships between input arguments and fields in the output object by encapsulating these relationships within a parsable string format. It is used in the @is
and @require
directives.
To illustrate, consider a simple example from a GraphQL schema:
type Query {
userById(userId: ID! @is(field: "id")): User! @lookup
}
In this schema, the userById
query uses the @is
directive with FieldSelectionMap to declare that the userId
argument is semantically equivalent to the User.id
field.
An example query might look like this:
query {
userById(userId: "123") {
id
}
}
Here, it is expected that the userId
“123” corresponds directly to User.id
, resulting in the following response if correctly implemented:
{
"data": {
"userById": {
"id": "123"
}
}
}
The FieldSelectionMap scalar is represented as a string that, when parsed, produces a SelectedValue.
A SelectedValue must exactly match the shape of the argument value to be considered valid. For non-scalar arguments, you must specify each field of the input type in SelectedObjectValue.
Example № 24extend type Query {
findUserByName(user: UserInput! @is(field: "{ firstName: firstName }")): User
@lookup
}
Counter Example № 25extend type Query {
findUserByName(user: UserInput! @is(field: "firstName")): User @lookup
}
6.1.1Scope
The FieldSelectionMap scalar type is used to establish semantic equivalence between an argument and fields within a specific output type. This output type is always a composite type, but the way it’s determined can vary depending on the directive and context in which the FieldSelectionMap is used.
For example, when used with the @is
directive, the FieldSelectionMap maps between the argument and fields in the return type of the field. However, when used with the @require
directive, it maps between the argument and fields in the object type on which the field is defined.
Consider this example:
type Product {
id: ID!
delivery(
zip: String!
size: Int! @require(field: "dimension.size")
weight: Int! @require(field: "dimension.weight")
): DeliveryEstimates
}
In this case, "dimension.size"
and "dimension.weight"
refer to fields of the Product
type, not the DeliveryEstimates
return type.
Consequently, a FieldSelectionMap must be interpreted in the context of a specific argument, its associated directive, and the relevant output type as determined by that directive’s behavior.
Examples
Scalar fields can be mapped directly to arguments.
This example maps the Product.weight
field to the weight
argument:
Example № 26type Product {
shippingCost(weight: Float @require(field: "weight")): Currency
}
This example maps the Product.shippingWeight
field to the weight
argument:
Example № 27type Product {
shippingCost(weight: Float @require(field: "shippingWeight")): Currency
}
Nested fields can be mapped to arguments by specifying the path. This example maps the nested field Product.packaging.weight
to the weight
argument:
Example № 28type Product {
shippingCost(weight: Float @require(field: "packaging.weight")): Currency
}
Complex objects can be mapped to arguments by specifying each field.
This example maps the Product.width
and Product.height
fields to the dimension
argument:
Example № 29type Product {
shippingCost(
dimension: DimensionInput @require(field: "{ width: width height: height }")
): Currency
}
The shorthand equivalent is:
Example № 30type Product {
shippingCost(
dimension: DimensionInput @require(field: "{ width height }")
): Currency
}
In case the input field names do not match the output field names, explicit mapping is required.
Example № 31type Product {
shippingCost(
dimension: DimensionInput @require(field: "{ w: width h: height }")
): Currency
}
Even if Product.dimension
has all the fields needed for the input object, an explicit mapping is always required.
This example is NOT allowed because it lacks explicit mapping:
Counter Example № 32type Product {
shippingCost(dimension: DimensionInput @require(field: "dimension")): Currency
}
Instead, you can traverse into output fields by specifying the path.
This example shows how to map nested fields explicitly:
Example № 33type Product {
shippingCost(
dimension: DimensionInput
@require(field: "{ width: dimension.width height: dimension.height }")
): Currency
}
The path does NOT affect the structure of the input object. It is only used to traverse the output object:
Example № 34type Product {
shippingCost(
dimension: DimensionInput
@require(field: "{ width: size.width height: size.height }")
): Currency
}
To avoid repeating yourself, you can prefix the selection with a path that ends in a dot to traverse INTO the output type.
This affects how fields get interpreted but does NOT affect the structure of the input object:
Example № 35type Product {
shippingCost(
dimension: DimensionInput @require(field: "dimension.{ width height }")
): Currency
}
This example is equivalent to the previous one:
Example № 36type Product {
shippingCost(
dimension: DimensionInput @require(field: "size.{ width height }")
): Currency
}
The path syntax is required for lists because list-valued path expressions would be ambiguous otherwise.
This example is NOT allowed because it lacks the dot syntax for lists:
Counter Example № 37type Product {
shippingCost(
dimensions: [DimensionInput]
@require(field: "{ width: dimensions.width height: dimensions.height }")
): Currency
}
Instead, use the path syntax and brackets to specify the list elements:
Example № 38type Product {
shippingCost(
dimensions: [DimensionInput] @require(field: "dimensions[{ width height }]")
): Currency
}
With the path syntax it is possible to also select fields from a list of nested objects:
Example № 39type Product {
shippingCost(partIds: @require(field: "parts[id]")): Currency
}
For more complex input objects, all these constructs can be nested. This allows for detailed and precise mappings.
This example nests the weight
field and the dimension
object with its width
and height
fields:
Example № 40type Product {
shippingCost(
package: PackageInput
@require(field: "{ weight, dimension: dimension.{ width height } }")
): Currency
}
This example nests the weight
field and the size
object with its width
and height
fields:
Example № 41type Product {
shippingCost(
package: PackageInput
@require(field: "{ weight, size: dimension.{ width height } }")
): Currency
}
The label can be used to nest values that aren’t nested in the output.
This example nests Product.width
and Product.height
under dimension
:
Example № 42type Product {
shippingCost(
package: PackageInput
@require(field: "{ weight, dimension: { width height } }")
): Currency
}
In the following example, dimensions are nested under dimension
in the output:
Example № 43type Product {
shippingCost(
package: PackageInput
@require(field: "{ weight, dimension: dimension.{ width height } }")
): Currency
}
6.2Language
According to the GraphQL specification, an argument is a key-value pair in which the key is the name of the argument and the value is a Value
.
The Value
of an argument can take various forms: it might be a scalar value (such as Int
, Float
, String
, Boolean
, Null
, or Enum
), a list (ListValue
), an input object (ObjectValue
), or a Variable
.
Within the scope of the FieldSelectionMap, the relationship between input and output is established by defining the Value
of the argument as a selection of fields from the output object.
Yet only certain types of Value
have a semantic meaning. ObjectValue
and ListValue
are used to define the structure of the value. Scalar values, on the other hand, do not carry semantic importance in this context.
While variables may have legitimate use cases, they are considered out of scope for the current discussion.
However, it’s worth noting that there could be potential applications for allowing them in the future.
Given that these potential values do not align with the standard literals defined in the GraphQL specification, a new literal called SelectedValue is introduced, along with SelectedObjectValue.
Beyond these literals, an additional literal called Path is necessary.
6.2.1Name
Is equivalent to the Name defined in the GraphQL specification
6.2.2Path
The Path literal is a string used to select a single output value from the return type by specifying a path to that value. This path is defined as a sequence of field names, each separated by a period (.
) to create segments.
Example № 44book.title
Each segment specifies a field in the context of the parent, with the root segment referencing a field in the return type of the query. Arguments are not allowed in a Path.
To select a field when dealing with abstract types, the segment selecting the parent field must specify the concrete type of the field using angle brackets after the field name if the field is not defined on an interface.
In the following example, the path mediaById<Book>.isbn
specifies that mediaById
returns a Book
, and the isbn
field is selected from that Book
.
Example № 45mediaById<Book>.isbn
6.2.3SelectedValue
A SelectedValue is defined as either a Path or a SelectedObjectValue
A Path is designed to point to only a single value, although it may reference multiple fields depending on the return type. To allow selection from different paths based on type, a Path can include multiple paths separated by a pipe (|
).
In the following example, the value could be title
when referring to a Book
and movieTitle
when referring to a Movie
.
Example № 46mediaById<Book>.title | mediaById<Movie>.movieTitle
The |
operator can be used to match multiple possible SelectedValue. This operator is applied when mapping an abstract output type to a @oneOf
input type.
Example № 47{ movieId: <Movie>.id } | { productId: <Product>.id }
Example № 48{ nested: { movieId: <Movie>.id } | { productId: <Product>.id }}
6.2.4SelectedObjectValue
SelectedObjectValue are unordered lists of keyed input values wrapped in curly-braces {}
. It has to be used when the expected input type is an object type.
This structure is similar to the ObjectValue
defined in the GraphQL specification, but it differs by allowing the inclusion of Path values within a SelectedValue, thus extending the traditional ObjectValue
capabilities to support direct path selections.
A SelectedObjectValue following a Path is scoped to the type of the field selected by the Path. This means that the root of all SelectedValue inside the selection is no longer scoped to the root (defined by @is
or @require
) but to the field selected by the Path. The Path does not affect the structure of the input type.
This allows for reducing repetition in the selection.
The following example is valid:
Example № 49type Product {
dimension: Dimension!
shippingCost(
dimension: DimensionInput! @require(field: "dimension.{ size weight }")
): Int!
}
The following example is equivalent to the previous one:
Example № 50type Product {
dimensions: Dimension!
shippingCost(
dimensions: DimensionInput!
@require(field: "{ size: dimensions.size weight: dimensions.weight }")
): Int! @lookup
}
6.2.5SelectedListValue
A SelectedListValue is an ordered list of SelectedValue wrapped in square brackets []
. It is used to express semantic equivalence between an argument expecting a list of values and the values of a list field within the output object.
The SelectedListValue differs from the ListValue
defined in the GraphQL specification by only allowing one SelectedValue as an element.
The following example is valid:
Example № 51type Product {
parts: [Part!]!
partIds(partIds: [ID!]! @require(field: "parts[id]")): [ID!]!
}
In this example, the partIds
argument is semantically equivalent to the id
fields of the parts
list.
The following example is invalid because it uses multiple SelectedValue as elements:
Counter Example № 52type Product {
parts: [Part!]!
partIds(parts: [PartInput!]! @require(field: "parts[id name]")): [ID!]!
}
input PartInput {
id: ID!
name: String!
}
A SelectedObjectValue can be used as an element of a SelectedListValue to select multiple object fields as long as the input type is a list of structurally equivalent objects.
Similar to SelectedObjectValue, a SelectedListValue following a Path is scoped to the type of the field selected by the Path. This means that the root of all SelectedValue inside the selection is no longer scoped to the root (defined by @is
or @require
) but to the field selected by the Path. The Path does not affect the structure of the input type.
The following example is valid:
Example № 53type Product {
parts: [Part!]!
partIds(parts: [PartInput!]! @require(field: "parts[{ id name }]")): [ID!]!
}
input PartInput {
id: ID!
name: String!
}
In case the input type is a nested list, the shape of the input object must match the shape of the output object.
Example № 54type Product {
parts: [[Part!]]!
partIds(
parts: [[PartInput!]]! @require(field: "parts[[{ id name }]]")
): [ID!]!
}
input PartInput {
id: ID!
name: String!
}
The following example is valid:
Example № 55type Query {
findLocation(
location: LocationInput!
@is(field: "{ coordinates: coordinates[{lat: x lon: y}]}")
): Location @lookup
}
type Coordinate {
x: Int!
y: Int!
}
type Location {
coordinates: [Coordinate!]!
}
input PositionInput {
lat: Int!
lon: Int!
}
input LocationInput {
coordinates: [PositionInput!]!
}
6.3Validation
Validation ensures that FieldSelectionMap scalars are semantically correct within the given context.
Validation of FieldSelectionMap scalars occurs during the composition phase, ensuring that all FieldSelectionMap entries are syntactically correct and semantically meaningful relative to the context.
Composition is only possible if the FieldSelectionMap is validated successfully. An invalid FieldSelectionMap results in undefined behavior, making composition impossible.
In this section, we will assume the following type system in order to demonstrate examples:
type Query {
mediaById(mediaId: ID!): Media
findMedia(input: FindMediaInput): Media
searchStore(search: SearchStoreInput): [Store]!
storeById(id: ID!): Store
}
type Store {
id: ID!
city: String!
media: [Media!]!
}
interface Media {
id: ID!
}
type Book implements Media {
id: ID!
title: String!
isbn: String!
author: Author!
}
type Movie implements Media {
id: ID!
movieTitle: String!
releaseDate: String!
}
type Author {
id: ID!
books: [Book!]!
}
input FindMediaInput @oneOf {
bookId: ID
movieId: ID
}
type SearchStoreInput {
city: String
hasInStock: FindMediaInput
}
6.3.1Path Field Selections
Each segment of a Path must correspond to a valid field defined on the current type context.
Formal Specification
- For each segment in the Path:
- If the segment is a field
- Let fieldName be the field name in the current segment.
- fieldName must be defined on the current type in scope.
Explanatory Text
The Path literal is used to reference a specific output field from a input field. Each segment in the Path must correspond to a field that is valid within the current type scope.
For example, the following Path is valid in the context of Book
:
Example № 56title
Example № 57<Book>.title
Incorrect paths where the field does not exist on the specified type is not valid result in validation errors. For instance, if <Book>.movieId
is referenced but movieId
is not a field of Book
, will result in an invalid Path.
Counter Example № 58movieId
Counter Example № 59<Book>.movieId
6.3.2Path Terminal Field Selections
Each terminal segment of a Path must follow the rules regarding whether the selected field is a leaf node.
Formal Specification
Explanatory Text
A Path that refers to scalar or enum fields must end at those fields. No further field selections are allowed after a scalar or enum. On the other hand, fields returning objects, interfaces, or unions must continue to specify further selections until you reach a scalar or enum field.
For example, the following Path is valid if title
is a scalar field on the Book
type:
Example № 60book.title
The following Path is invalid because title
should not have subselections:
Counter Example № 61book.title.something
For non-leaf fields, the Path must continue to specify subselections until a leaf field is reached:
Example № 62book.author.id
Invalid Path where non-leaf fields do not have further selections:
Counter Example № 63book.author
6.3.3Type Reference Is Possible
Each segment of a Path that references a type, must be a type that is valid in the current context.
Formal Specification
- For each segment in a Path:
- If segment is a type reference:
- Let type be the type referenced in the segment.
- Let parentType be the type of the parent of the segment.
- Let applicableTypes be the intersection of GetPossibleTypes(type) and GetPossibleTypes(parentType).
- applicableTypes must not be empty.
- If type is an object type, return a set containing type.
- If type is an interface type, return the set of types implementing type.
- If type is a union type, return the set of possible types of type.
Explanatory Text
Type references inside a Path must be valid within the context of the surrounding type. A type reference is only valid if the referenced type could logically apply within the parent type.
6.3.4Values of Correct Type
Formal Specification
- For each SelectedValue value:
- Let type be the type expected in the position value is found.
- value must be coercible to type.
Explanatory Text
Literal values must be compatible with the type expected in the position they are found.
The following examples are valid use of value literals in the context of FieldSelectionMap scalar:
Example № 64type Query {
storeById(id: ID! @is(field: "id")): Store! @lookup
}
type Store {
id: ID
city: String!
}
Non-coercible values are invalid. The following examples are invalid:
Counter Example № 65type Query {
storeById(id: ID! @is(field: "id")): Store! @lookup
}
type Store {
id: Int
city: String!
}
6.3.5Selected Object Field Names
Formal Specification
- For each Selected Object Field field in the document:
- Let fieldName be the Name of field.
- Let fieldDefinition be the field definition provided by the parent selected object type named fieldName.
- fieldDefinition must exist.
Explanatory Text
Every field provided in an selected object value must be defined in the set of possible fields of that input object’s expected type.
For example, the following is valid:
Example № 66type Query {
storeById(id: ID! @is(field: "id")): Store! @lookup
}
type Store {
id: ID
city: String!
}
In contrast, the following is invalid because it uses a field “address” which is not defined on the expected type:
Counter Example № 67extend type Query {
storeById(id: ID! @is(field: "address")): Store! @lookup
}
type Store {
id: ID
city: String!
}
6.3.6Selected Object Field Uniqueness
Formal Specification
- For each selected object value selectedObject:
- For every field in selectedObject:
- Let name be the Name of field.
- Let fields be all Selected Object Fields named name in selectedObject.
- fields must be the set containing only field.
Explanatory Text
Selected objects must not contain more than one field with the same name, as it would create ambiguity and potential conflicts.
For example, the following is invalid:
Counter Example № 68extend type Query {
storeById(id: ID! @is(field: "id id")): Store! @lookup
}
type Store {
id: ID
city: String!
}
6.3.7Required Selected Object Fields
Formal Specification
- For each Selected Object:
- Let fields be the fields provided by that Selected Object.
- Let fieldDefinitions be the set of input object field definitions of that Selected Object.
- For each fieldDefinition in fieldDefinitions:
- Let type be the expected type of fieldDefinition.
- Let defaultValue be the default value of fieldDefinition.
- If type is Non-Null and defaultValue does not exist:
- Let fieldName be the name of fieldDefinition.
- Let field be the input object field in fields named fieldName.
- field must exist.
Explanatory Text
Input object fields may be required. This means that a selected object field is required if the corresponding input field is required. Otherwise, the selected object field is optional.
For instance, if the UserInput
type requires the id
field:
Example № 69input UserInput {
id: ID!
name: String!
}
Then, an invalid selection would be missing the required id
field:
Counter Example № 70extend type Query {
userById(user: UserInput! @is(field: "{ name: name }")): User! @lookup
}
If the UserInput
type requires the name
field, but the User
type has an optional name
field, the following selection would be valid.
Example № 71extend type Query {
findUser(input: UserInput! @is(field: "{ name: name }")): User! @lookup
}
type User {
id: ID
name: String
}
input UserInput {
id: ID
name: String!
}
But if the UserInput
type requires the name
field but it’s not defined in the User
type, the selection would be invalid.
Counter Example № 72extend type Query {
findUser(input: UserInput! @is(field: "{ id: id }")): User! @lookup
}
type User {
id: ID
}
input UserInput {
id: ID
name: String!
}