GraphQL

Working Draft – July 2015

Introduction

This is a Draft RFC Specification for GraphQL, a query language created by Facebook in 2012 for describing the capabilities and requirements of data models for client‐server applications. The development of this standard started in 2015. GraphQL
is a new and evolving language and is not complete. Significant enhancement will continue in future editions of this specification.

Copyright notice

Copyright (c) 2015, Facebook, Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

Neither the name Facebook nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

GraphQL is a query language designed to build client applications by providing an intuitive and flexible syntax and system for describing their data requirements and interactions.

For example, this GraphQL request will receive the name of the user with id 4 from the Facebook implementation of GraphQL.

{
user(id: 4) {
name
}
}

Which produces the resulting data (in JSON):

{
"user": {
"name": "Mark Zuckerberg"
}
}

GraphQL is not a programming language capable of arbitrary computation, but is instead a language used to query application servers that have capabilities defined in this specification. GraphQL does not mandate a particular programming language or
storage system for application servers that implement it. Instead, application servers take their capabilities and map them to a uniform language, type system, and philosophy that GraphQL encodes. This provides a unified interface friendly to product
development and a powerful platform for tool‐building.

GraphQL has a number of design principles:

Hierarchal: Most product development today involves the creation and manipulation of view hierarchies. To achieve congruence with the structure of these applications, a GraphQL query itself is structured hierarchically. The query
is shaped just like the data it returns. It is a natural way for clients to describe data requirements.

Product‐centric: GraphQL is unapologetically driven by the requirements of views and the front‐end engineers that write them. GraphQL starts with their way of thinking and requirements and build the language and runtime
necessary to enable that.

Strong‐typing: Every GraphQL server defines an application‐specific type system. Queries are executed within the context of that type system. Given a query, tools can ensure that the query is both syntactically correct
and valid within the GraphQL type system before execution, i.e. at development time, and the server can make certain guarantees about the shape and nature of the response.

Client‐specified queries: Through its type system, a GraphQL server publishes the capabilities that its clients are allowed to consume. It is the client that is responsible for specifying exactly how it will consume those
published capabilities. These queries are specified at field‐level granularity. In the majority of client‐server applications written without GraphQL, the server determines the data returned in its various scripted endpoints. A GraphQL
query, on the other hand, returns exactly what a client asks for and no more.

Introspective: GraphQL is introspective. A GraphQL server’s type system must be queryable by the GraphQL language itself, as will be described in this specification. GraphQL introspection serves as a powerful platform for
building common tools and client software libraries.

Because of these principles, GraphQL is a powerful and productive environment for building client applications. Product developers and designers building applications against working GraphQL servers -- supported with quality tools -- can quickly become
productive without reading extensive documentation and with little or no formal training. To enable that experience, there must be those that build those servers and tools.

The following formal specification serves as a reference for those builders. It describes the language and its grammar; the type system and the introspection system used to query it; and the execution and validation engines with the algorithms to
power them. The goal of this specification is to provide a foundation and framework for an ecosystem of GraphQL tools, client libraries, and server implementations -- spanning both organizations and platforms -- that has yet to be built. We look
forward to working with the community in order to do that.

Clients use the GraphQL language to make requests from a GraphQL server. We refer to these requests as documents. A document may contain operations (queries and mutations are both operations) and fragments, a common unit of composition allowing for
query reuse.

GraphQL documents are only executable by a server if they contain an operation. However documents which do not contain operations may still be parsed and validated to allow client to represent a single request across many documents.

GraphQL documents may contain multiple operations, as long as they are named. When submitting a document with multiple operations to a GraphQL server, the name of the desired operation must also be provided.

If a document contains only one query operation, that operation may be represented in the shorthand form, which omits the query keyword and query name.

Both field arguments and directives accept input values. Input values can be specified as a variable or respresented inline as literals. Input values can be scalars, enumerations, or input objects. List and inputs objects may also contain variables.

Int

Int is a number specified without a decimal point (ex. 1).

Float

A Float numbers always includes a decimal point (ex. 1.0) and may optionally also include an exponent (ex. 6.0221413e23).

Boolean

The two keywords true and false represent the two boolean values.

String

Strings are lists of characters wrapped in double‐quotes ". (ex. "Hello World"). Whitespace is significant within a string.

Enum Value

Enum values are respresented as unquoted names (ex. MOBILE_WEB). It is recommended that Enum values be “all caps”. Enum values are only used in contexts where the precise enumeration type is known. Therefore it’s not
necessary to use the enumeration type name in the literal.

List

Lists are an ordered sequence of values wrapped in square‐brackets [ ]. The values of an Array literal may be any value literal or variable (ex. [1, 2, 3]).

Commas are optional throughout GraphQL so trailing commas are allowed and repeated commas do not represent missing values.

Values for those variables are provided along with a GraphQL query, so they may be substituted during execution. If providing JSON for the variables values, we could run this query and request profilePic of size 60 with:

In some cases, you need to provide options to alter GraphQL’s execution behavior in ways field arguments will not suffice, such as conditionally skipping a field. Directives provide this with a @name and can be specified to be
used without an argument or with a value argument.

Directives can be used to conditionally include fields in a query based on a provided boolean value. In this contrived example experimentalField will be queried and controlField will not.

Fragments are consumed by using the spread operator (...). All fields selected by the fragment will be added to the query field selection at the same level as the fragment invocation. This happens through multiple levels of fragment
spreads.

The profiles root field returns a list where each element could be a Page or a User. When the object in the profiles result is a User, friends will be present and likers will not. Conversely when the result is a Page, likers will be present and friends will not.

Query variables can be used within fragments. Query variables have global scope with a given operation, so a variable used within a fragment must be declared in any top‐level operation that transitively consumes that fragment. If variable
is referenced in a fragment and is included by an operation that does not define that variable, the operation cannot be executed.

Fragments can be defined inline to query. This is done to conditionally execute fields based on their runtime type. This feature of standard fragment inclusion was demonstrated in the query FragmentTyping example. We could accomplish
the same thing using inline fragments.

The GraphQL Type system describes the capabilities of a GraphQL server and is used to determine if a query is valid. The type system also describes the input types of query variables to determine if values provided at runtime are valid.

A GraphQL server’s capabilities are referred to as that server’s “schema”. A schema is defined in terms of the types and directives it supports.

A given GraphQL schema must itself be internally valid. This section describes the rules for this validation process where relevant.

A GraphQL schema is represented by a root type for each kind of operation: query and mutation; this determines the place in the type system where those operations begin.

All types within a GraphQL schema must have unique names. No two provided types may have the same name. No provided type may have a name which conflicts with any built in types (including Scalar and Introspection types).

All directives within a GraphQL schema must have unique names. A directive and a type may share the same name, since there is no ambiguity between them.

The fundamental unit of any GraphQL Schema is the type. There are eight kinds of types in GraphQL.

The most basic type is a Scalar. A scalar represents a primitive value, like a string or an integer. Oftentimes, the possible responses for a scalar field are enumerable. GraphQL offers an Enum type in those cases, where
the type specifies the space of valid responses.

Scalars and Enums form the leaves in response trees; the intermediate levels are Object types, which define a set of fields, where each field is another type in the system, allowing the definition of arbitrary type hierarchies.

GraphQL supports two abstract types: interfaces and unions.

An Interface defines a list of fields; Object types that implement that interface are guaranteed to implement those fields. Whenever the type system claims it will return an interface, it will return a valid implementating
type.

A Union defines a list of possible types; similar to interfaces, whenever the type system claims a union will be returned, one of the possible types will be returned.

All of the types so far are assumed to be both nullable and singular: e.g. a scalar string returns either null or a singular string. The type system might want to define that it returns a list of other types; the List type is provided
for this reason, and wraps another type. Similarly, the Non-Null type wraps another type, and denotes that the result will never be null. These two types are refered to as “wrapping types”; non‐wrapping types are
refered to as “base types”. A wrapping type has an underlying “base type”, found by continually unwrapping the type until a base type is found.

Finally, oftentimes it is useful to provide complex structs as inputs to GraphQL queries; the Input Object type allows the schema to define exactly what data is expected from the client in these queries.

As expected by the name, a scalar represents a primitive value in GraphQL. GraphQL responses take the form of a hierarchal tree; the leaves on these trees are GraphQL scalars.

All GraphQL scalars are representable as strings, though depending on the response format being used, there may be a more appropriate primitive for the given scalar type, and server should use those types when appropriate.

GraphQL provides a number of built‐in scalars, but type systems can add additional scalars with semantic meaning. For example, a GraphQL system could define a scalar called Time which, while serialized as a string, promises
to conform to ISO‐8601. When querying a field of type Time, you can then rely on the ability to parse the result with an ISO‐8601 parser and use a client‐specific primitive for time. Another example of a potentially
useful custom scalar is Url, which serializes as a string, but is guaranteed by the server to be a valid URL.

Result Coercion

A GraphQL server, when preparing a field of a given scalar type, must uphold the contract the scalar type describes, either by coercing the value or producing an error.

For example, a GraphQL server could be preparing a field with the scalar type Int and encounter a floating‐point number. Since the server must not break the contract by yielding a non‐integer, the server should truncate
the fractional value and only yield the integer value. If the server encountered a boolean true value, it should return 1. If the server encountered a string, it may attempt to parse the string for a base‐10 integer
value. If the server encounters some value that cannot be reasonably coerced to an Int, then it must raise an field error.

Since this coercion behavior is not observable to clients of the GraphQL server, the precise rules of coercion are left to the implementation. The only requirement is that the server must yield values which adhere to the expected Scalar type.

Input Coercion

If a GraphQL server expects a scalar type as input to a field argument, coercion is observable and the rules must be well defined. If an input value does not match a coercion rule, a query error must be raised.

GraphQL has different constant literals to represent integer and floating‐point input values, and coercion rules may apply differently depending on which type of input value is encountered. GraphQL may be parameterized by query variables,
the values of which are often serialized when sent over a transport like HTTP. Since some common serializations (ex. JSON) do not discriminate between integer and floating‐point values, they are interpretted as an integer input value if
they have an empty fractional part (ex. 1.0) and otherwise as floating‐point input value.

GraphQL provides a basic set of well‐defined Scalar types. A GraphQL server should support all of these types, and a GraphQL server which provide a type by these names must adhere to the behavior described below.

The Int scalar type represents a signed 32‐bit numeric non‐fractional values. Response formats that support a 32‐bit integer or a number type should use that type to represent this scalar.

Result Coercion

GraphQL servers should coerce non‐int raw values to Int when possible otherwise they must raise a field error. Examples of this may include returning 1 for the floating‐point number 1.0, or 2 for the string "2".

Input Coercion

When expected as an input type, only integer input values are accepted. All other input values, including strings with numeric content, must raise a query error indicating an incorrect type. If the integer input value represents a value less
than -231 or greater than or equal to 231, a query error should be raised.

Numeric integer values larger than 32‐bit should either use String or a custom‐defined Scalar type, as not all platforms and transports support encoding integer numbers larger than 32‐bit.

The Float scalar type represents signed double‐precision fractional values as specified by IEEE 754. Response formats that support an appropriate double‐precision number
type should use that type to represent this scalar.

Result Coercion

GraphQL servers should coerce non‐floating‐point raw values to Float when possible otherwise they must raise a field error. Examples of this may include returning 1.0 for the integer number 1, or 2.0 for the string "2".

Input Coercion

When expected as an input type, both integer and float input values are accepted. Integer input values are coerced to Float by adding an empty fractional part, for example 1.0 for the integer input value 1. All other
input values, including strings with numeric content, must raise a query error indicating an incorrect type. If the integer input value represents a value not representable by IEEE 754, a query error should be raised.

The String scalar type represents textual data, represented as UTF‐8 character sequences. The String type is most often used by GraphQL to represent free‐form human‐readable text. All response formats must support string
representations, and that representation must be used here.

Result Coercion

GraphQL servers should coerce non‐string raw values to String when possible otherwise they must raise a field error. Examples of this may include returning the string "true" for a boolean true value, or the string
"1" for the integer 1.

Input Coercion

When expected as an input type, only valid UTF‐8 string input values are accepted. All other input values must raise a query error indicating an incorrect type.

The ID scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type is serialized in the same way as a String; however, it is not intended to be human‐readable. While it
is often numeric, it should always serialize as a String.

Result Coercion

GraphQL is agnostic to ID format, and serializes to string to ensure consistency across many formats ID could represent, from small auto‐increment numbers, to large 128‐bit random numbers, to base64 encoded values, or string values
of a format like GUID.

GraphQL servers should coerce as appropriate given the ID formats they expect, when coercion is not possible they must raise a field error.

Input Coercion

When expected as an input type, any string (such as "4") or integer (such as 4) input value should be coerced to ID as appropriate for the ID formats a given GraphQL server expects. Any other input value,
including float input values (such as 4.0), must raise a query error indicating an incorrect type.

GraphQL queries are hierarchal and composed, describing a tree of information. While Scalar types describe the leaf values of these hierarchal queries, Objects describe the intermediate levels.

GraphQL Objects represent a list of named fields, each of which yield a value of a specific type. Object values are serialized as unordered maps, where the queried field names (or aliases) are the keys and the result of evaluating the field is
the value.

For example, a type Person could be described as:

type Person {
name: String
age: Int
picture: Url
}

Where name is a field that will yield a String value, and age is a field that will yield an Int value, and picture a field that will yield a Url value.

A query of an object value must select at least one field. This selection of fields will yield an unordered map containing exactly the subset of the object queried. Only fields that are declared on the object type may validly be queried on that
object.

Object fields are conceptually functions which yield values. Occasionally object fields can accept arguments to further specify the return value. Field arguments are defined as a list of all possible argument names and their expected input types.

For example, a Person type with a picture field could accept an argument to determine what size of an image to return.

type Person {
name: String
picture(size: Int): Url
}

GraphQL queries can optionally specify arguments to their fields to provide these arguments.

The type of a field argument can be a Scalar, as it was in this example, or an Enum. It can also be an Input Object, covered later in this document, or it can be any wrapping type whose underlying base type is one of those three.

Fields in an object may be marked as deprecated as deemed necessary by the application. It is still legal to query for these fields (to ensure existing clients are not broken by the change), but the fields should be appropriately treated in
documentation and tooling.

This allows us to write a query for a Contact that can select the common fields.

{
entity {
name
},
phoneNumber
}

When querying for fields on an interface type, only those fields declared on the interface may be queried. In the above example, entity returns a NamedEntity, and name is defined on NamedEntity,
so it is valid. However, the following would not be a valid query:

{
entity {
name,
age
},
phoneNumber
}

because entity refers to a NamedEntity, and age is not defined on that interface. Querying for age is only valid when the result of entity is a Person; the query can
express this using a fragment or an inline fragment:

{
entity {
name,
... on User {
age
}
},
phoneNumber
}

Result Coercion

The interface type should have some way of determining which object a given result corresponds to. Once it has done so, the result coercion of the interface is the same as the result coercion of the object.

GraphQL Unions represent an object that could be one of a list of GraphQL Object types, but provides for no guaranteed fields between those types. They also differ from interfaces in that Object types declare what interfaces they implement, but
are not aware of what unions contain them.

With interfaces and objects, only those fields defined on the type can be queried directly; to query other fields on an interface, typed fragments must be used. This is the same as for unions, but unions do not define any fields, so no fields may be queried on this type without the use of typed fragments.

When querying the firstSearchResult field of type SearchQuery, the query would ask for all fields inside of a fragment indicating the appropriate type. If the query wanted the name if the result was a Person, and the
height if it was a photo, the following query is invalid, because the union itself defines not fields:

The member types of an Union type must all be Object base types; Scalar, Interface and Union types may not be member types of a Union. Similarly, wrapping types may not be member types of a Union.

A Union type must define two or more member types.

When expected as an input type, array input values are accepted only when each item in the input array can be accepted by the item type. If the input value is not an array but can be accepted by the item type, it is coerced by creating an array
with the input value as the sole item. Other input values must raise a query error indicating an incorrect type.

GraphQL Enums are a variant on the Scalar type, which represents one of a finite set of possible values.

GraphQL Enums are not references for a numeric value, but are unique values in their own right. They serialize as a string: the name of the represented value.

Result Coercion

GraphQL servers must return one of the defined set of possible values, if a reasonable coercion is not possible they must raise a field error.

Input Coercion

GraphQL has a constant literal to represent enum input values. GraphQL string literals must not be accepted as an enum input and instead raise a query error.

Query variable transport serializations which have a different representation for non‐string symbolic values (for example, EDN) should only allow such values as enum input values. Otherwise,
for most transport serializations that do not, strings may be interpretted as the enum input value with the same name.

Fields can define arguments that the client passes up with the query, to configure their behavior. These inputs can be Strings or Enums, but they sometimes need to be more complex than this.

The Object type defined above is inappropriate for re‐use here, because Objects can contain fields that express circular references or references to interfaces and unions, neither of which is appropriate for use
as an input argument. For this reason, input objects have a separate type in the system.

An Input Object defines a set of input fields; the input fields are either scalars, enums, or other input objects. This allows arguments to accept arbitrarily complex structs.

Result Coercion

An input object is never a valid result.

Input Coercion

The input to an input object should be an unordered map, otherwise an error should be thrown. The result of the coercion is an unordered map, with an entry for each input field, whose key is the name of the input field. The value of an entry in
the coerced map is the result of input coercing the value of the entry in the input with the same key; if the input does not have a corresponding entry, the value is the result of coercing null. The input coercion above should be performed according
to the input coercion rules of the type declared by the input field.

A GraphQL list is a special collection type which declares the type of each item in the List (referred to as the item type of the list). List values are serialized as ordered lists, where each item in the array is serialized as per the
item type.

Result Coercion

GraphQL servers must return an ordered list as the result of a list type. Each item in the list must be the result of a result coercion of the item type. If a reasonable coercion is not possible they must raise a field error. In particular, if
a non‐list is returned, the coercion should fail, as this indicates a mismatch in expectations between the type system and the implementation.

Input Coercion

When accepted as an input, each item in the list should be coerced as per the input coercion of the item type.

If the value passed as an input to a list type is not as list, it should be coerced as though the input was a list of size one, where the value passed is the only item in the list. This is to allow inputs that accept a “var args”
to declare their input type as a list; if only one argument is passed (a common case), the client can just pass that value rather than constructing the list.

By default, all types in GraphQL are nullable; the null value is a valid response for all of the above types. To declare a type that disallows null, the GraphQL Non‐Null type can be used. This type declares
an underlying type, and this type acts identically to that underlying type, with the exception that null is not a valid response for the wrapping type.

Result Coercion

In all of the above result coercion, null was considered a valid value. To coerce the result of a Non Null type, the result coercion of the underlying type should be performed. If that result was not null, then the result
of coercing the Non Null type is that result. If that result was null, then an error should be raised.

Input Coercion

When accepted as an input, each item in the list should be coerced as per the input coercion of the item type.

If the value passed as an input to a list type is not as list, it should be coerced as though the input was a list of size one, where the value passed is the only item in the list. This is to allow inputs that accept a “var args”
to declare their input type as a list; if only one argument is passed (a common case), the client can just pass that value rather than constructing the list.

A GraphQL schema includes a list of supported directives, each of which has a name. Directives can apply to operations, fragments, or fields; each directive indicates which of those it applies to.

Directives can optionally take an argument. The type of the argument to a directive has the same restrictions as the type of an argument to a field. It can be a Scalar, an Enum, an Input Object, or any wrapping type whose underlying base type is
one of those three.

A GraphQL schema includes types, indicating where query and mutation operations start. This provides the initial entry points into the type system. The query type must always be provided, and is an Object base type. The mutation type is optional;
if it is null, that means the system does not support mutations. If it is provided, it must be an object base type.

The fields on the query type indicate what fields are available at the top level of a GraphQL query. For example, a basic GraphQL query like this one:

query getMe {
me
}

Is valid when the type provided for the query starting type has a field named “me”. Similarly

mutation setName {
setName(name: "Zuck") {
newName
}
}

Is valid when the type provided for the mutation starting type is not null, and has a field named “setName” with a string argument named “name”.

Types and fields required by the GraphQL introspection system that are used in the same context as user‐defined type and fields are prefixed with two underscores. This in order to avoid naming collisions with user‐defined GraphQL types.
Conversely, GraphQL type system authors must not define any types, fields, arguments, or any other type system artifact with two leading underscores.

All types in the introspection system provide a description field of type String to allow type designers to publish documentation in addition to capabilities. A GraphQL server may return the description field
using Markdown syntax. Therefore it is recommended that any tool that displays description use a Markdown renderer.

To support the management of backwards compatibility, GraphQL fields and enum values can indicate whether or not they are deprecated (isDeprecated: Boolean) and a description of why it is deprecated (deprecationReason: String).

Tools built using GraphQL introspection should respect deprecation by discouraging deprecated use through information hiding or developer‐facing warnings.

GraphQL supports type name introspection within at any point in a query by the meta field __typename: String! when querying against any Object, Interface, or Union. It returns the name of the object type currently being queryied.

This is most often used when querying against Interface or Union types to identify which actual type of the possible types has been returned.

This field is implicit and does not appear in the fields list in any defined type.

Unions are an abstract types where no common fields are declared. The possible types of a union are explicitly listed out in possibleTypes. Types can be made parts of unions without modification of that type.

Fields

kind must return __TypeKind.UNION.

name must return a String.

description may return a String or null.

possibleTypes returns the list of types that can be represented within this union. They must be object types.

Interfaces is an abstract type where there are common fields declared. Any type that implements an interface must define all the fields with names and types exactly matching. The implementations of this interface are explicitly listed out in
possibleTypes.

Fields

kind must return __TypeKind.INTERFACE.

name must return a String.

description may return a String or null.

fields: The set of fields required by this interface.

Accepts the argument includeDeprecated which defaults to false. If true, deprecated fields are also returned.

possibleTypes returns the list of types that can be represented within this union. They must be object types.

GraphQL types are nullable. The value null is a valid response for field type.

A Non‐null type is a type modifier: it wraps another type instance in the ofType field. Non‐null types do not allow null as a response, and indicate required inputs for arguments and
input object fields.

Prior to execution, it can also verify that a request is valid within the context of a given GraphQL schema. Validation is primarily targeted at development‐time tooling. Any client‐side tooling should returns errors and not allow the
formulation of queries known to violate the type system at a given point in time.

Total request validation on the server‐side during execution is optional. As schemas and systems change over time existing clients may end up emitting queries that are no longer valid given the current type system. Servers (as described in the
Execution section of this spec) attempt to satisfy as much as the request as possible and continue to execute in the presence of type system errors rather than cease execution completely.

For this section of this schema, we will assume the following type system in order to demonstrate examples:

Let setForKey be the set of selections with a given response key in set

All members of setForKey must:

Have identical target fields

Have identical sets of arguments name‐value pairs.

Have identical sets of directive name‐value pairs.

Explanatory Text

Selection names are de‐duplicated and merged for validation, but the target field, arguments, and directives must all be identical.

For human‐curated GraphQL, this rules seem a bit counterintuitive since it appears to be clear developer error. However in the presence of nested fragments or machine‐generated GraphQL, requiring unique selections is a burdensome limitation
on tool authors.

The following selections correctly merge:

fragment mergeIdenticalFields on Dog {
name
name
}
fragment mergeIdenticalAliasesAndFields on Dog {
otherName : name
otherName : name
}

The following is not able to merge:

fragment conflictingBecauseAlias on Dog {
name : nickname
name
}

Identical field arguments are also merged if they have identical arguments. Both values and variables can be correctly merged.

Let argumentDefinitions be the set of argument definitions of targetField

Each argumentName in arguments must have a corresponding argument defintion in the targetField with the same name

Explanatory Text

Field selections may take arguments. Each field selection corresponds to a field definition on the enclosing type, which specifies a set of possible arguments. Every argument provided to the selection must be defined in the set of possible arguments.

Field selection is also determined by spreading fragments into one another. The selection set of the target fragment is unioned with the selection set at the level at which the target fragment is referenced.

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

Fragments are declared on a type and will only apply when the runtime object type matches the type condition. They also are spread within the context of a parent type. A fragment spread is only valid if its type condition could ever apply within
the parent type.

is valid because Dog is a member of the CatOrDog union. It is worth noting that if one inspected the contents of the CatOrDogNameFragment you could note
that the no valid results would ever be returned. However we do not specify this as invalid because we only consider the fragment declaration, not its body.

Dog does not implement the interface Sentient and therefore sentientFragment can never return meaningful results. Therefore the fragment is invalid. Likewise Cat is not a member of the union HumanOrAlien, and it can also never return meaningful results, making it invalid.

Union or interfaces fragments can be used within eachother. As long as there exists at least one object type that exists in the intersection of the possible types of the scope and the spread, the spread is considered valid.

Let directiveType be the input type of the corresponding directive defined on the server.

If directiveType is not defined:

The directive is meant to be used only as flag, and no argument should be provided.

If directiveType is defined and non‐null:

directiveUse must have an argument

Let argumentType be the type of argument supplied to directiveUse

argumentType and directiveType must be the same or argumentType must be coercable to directiveType

Explanatory Text

Directive arguments follow similar rules to arguments on fields. Much like field arguments, arguments to directives must be of the same type or coercable to input type of the directive type.

Directives arguments differ from field arguments insofar as they can be used without a provided argument. If the type of directive is not non‐null, the directive can be optionally used without an argument. If the type of a directive is not
defined, it is a flag directive: it cannot have an argument, If a value is provided to a flag directive, this is a validation error.

Fragments complicate this rule. Any fragment transitively included by an operation has access to the variables defined by that operation. Fragments can appear within multiple operations and therefore variable usages must correspond to variable
definitions in all of those operations.

For list types, the same rules around nullability apply to both outer types and inner types. A nullable list cannot be passed to a non‐null list, and a lists of nullable values cannot be passed to a list of non‐null values.

To evaluate a request, the executor will have a parsed Document (as defined in the “Query Language” part of this spec) and a selected operation name to run.

The executor should find the Operation in the Document with the given operation name. If no such operation exists, the executor should throw an error. If the operation is found, then the result of evaluating the request
should be the result of evaluating the operation according to the “Evaluating operations” section.

The type system, as described in the “Type System” part of the spec, must provide a “Query Root” and a “Mutation Root” object.

If the operation is a mutation, the result of the operation is the result of evaluating the mutation’s top level selection set on the “Mutation Root” object. This selection set should be evaluated serially.

If the operation is a query, the result of the operation is the result of evaluating the query’s top level selection set on the “Query Root” object.

If fragmentType is an Object Type, return true if objectType is fragmentType, otherwise return false.

If fragmentType is an Interface Type, return true if objectType is an implementation of fragmentType, otherwise return false.

If fragmentType is a Union, return true if objectType is a possible type of fragmentType, otherwise return false.

The result of evaluating the selection set is the result of evaluating the corresponding grouped field set. The corresponding grouped field set should be evaluated serially if the selection set is being evaluated serially, otherwise it should be
evaluated normally.

Each item in the grouped field set can potentially create an entry in the result map. That entry in the result map is the result is the result of calling GetFieldEntry on the corresponding item in the grouped field set. GetFieldEntry can return null, which indicates that there should be no entry in the result map for this item. Note that this is distinct from returning an entry with a string key and a null value, which indicates that an entry in the result should
be added for that key, and its value should be null.

GetFieldEntry assumes the existence of two functions that are not defined in this section of the spec. It is expected that the type system provides these methods:

ResolveFieldOnObject, which takes an object type, a field, and an object, and returns the result of resolving that field on the object.

GetFieldTypeFromObjectType, which takes an object type and a field, and returns that field’s type on the object type, or null if the field is not valid on the object type.

When evaluating a grouped field set without a serial execution order requirement, the executor can determine the entries in the result map in whatever order it chooses. Because the resolution of fields other than top‐level mutation fields
is always side effect–free and idempotent, the execution order must not affect the result, and hence the server has the freedom to evaluate the field entries in whatever order it deems optimal.

For example, given the following grouped field set to be evaluated normally:

{
birthday {
month
},
address {
street
}
}

A valid GraphQL executor can resolve the four fields in whatever order it chose.

Observe that based on the above sections, the only time an executor will run in serial execution order is on the top level selection set of a mutation operation and on its corresponding grouped field set.

When evaluating a grouped field set serially, the executor must consider each entry from the grouped field set in the order provided in the grouped field set. It must determine the corresponding entry in the result map for each item to completion
before it continues on to the next item in the grouped field set:

For example, given the following selection set to be evaluated serially:

If the result of resolving a field is null (either because the function to resolve the field returned null or because an error occurred), and that field is marked as being non‐null in the type system, then the result of evaluating the entire
field set that contains this field is now null.

If the field was null because of an error, then the error has already been logged, and the “errors” list in the response must not be affected.

If the field resolution function returned null, and the field was non‐null, then no error has been logged, so an appropriate error must be added to the “errors” list.

When a GraphQL server receives a request, it must return a well‐formed response. The server’s response describes the result of executing the requested operation if successful, and describes any errors encountered during the request.

A response may contain both a partial response as well as encountered errors in the case that an error occured on a field which was replaced with null.

GraphQL does not require a specific serialization format. However, clients should use a serialization format that supports the major primitives in the GraphQL response. In particular, the serialization format must support representations of the
following four primitives:

Map

List

String

Null

A serialization format may support the following primitives, however, strings may be used as a substitute for those primitives.

JSON is the preferred serialization format for GraphQL, though as noted above, GraphQL does not require a specific serialization format. For consistency and ease of notation, examples of the response are given in JSON throughout the spec. In particular,
in our JSON examples, we will represent primitives using the following JSON concepts:

If the operation included execution, the response map must contain the an entry with key “data”. The value of this entry is described in the “Data” section. If the operation failed before execution, due to a syntax error,
missing information, or validation error, this entry must not be present.

If the operation encountered any errors, the response map must contain an entry with key “errors”. The value of this entry is described in the “Errors” section. If the operation completed without encountering any errors,
this entry must not be present.

The response map may also contain an entry with key extensions. This entry, if set, must have a map as its value. This entry is reserved for implementors to extend the protocol however they see fit, and hence there are no additional
restrictions on its contents.

To ensure future changes to the protocol do not break existing servers and clients, the top level response map must not contain any entries other than the three described above.

The data entry in the response will be the result of the execution of the requested operation. If the operation was a query, this output will be an object of the schema’s query root type; if the operation was a mutation, this
output will be an object of the schema’s mutation root type.

If an error was encountered before execution begins, the data entry should not be present in the result.

If an error was encountered during the execution that prevented a valid response, the data entry in the response should be null.

The errors entry in the response is a non‐empty list of errors, where each error is a map.

If no errors were encountered during the requested operation, the errors entry should not be present in the result.

Every error must contain an entry with the key message with a string description of the error intended for the developer as a guide to understand and correct the error.

If an error can be associated to a particular point in the requested GraphQL document, it should contain an entry with the key locations with a list of locations, where each location is a map with the keys line and column,
both positive numbers starting from 1 which describe the beginning of an associated syntax element.

GraphQL servers may provide additional entries to error as they choose to produce more helpful or machine‐readable errors, however future versions of the spec may describe additional entries to errors.

If the data entry in the response is null or not present, the errors entry in the response must not be empty. It must contain at least one error. The errors it contains should indicate why no data was able
to be returned.

If the data entry in the response is not null, the errors entry in the response may contain any errors that occurred during execution. If errors occurred during execution, it should contain those errors.

A GraphQL document is defined in a syntactic grammar where terminal symbols are tokens. Tokens are defined in a lexical grammar which matches patterns of source characters. The result of parsing a sequence of source UTF‐8 characters produces
a GraphQL AST.

Symbols are defined (ex. Symbol :) as either one sequence of symbols or a list of possible sequences of symbols, either as a bulleted list or using the “one of” short hand.

A subscript suffix “Symbolopt” is shorthand for two possible sequences, one including that symbol and one excluding it.

A symbol definition subscript suffix parameter in braces “SymbolParam” is shorthand for two symbol definitions, one appended with that parameter name, the other without. The same subscript suffix on a symbol is shorthand for that variant of the definition. If the parameter starts with “?”, that
form of the symbol is used if in a symbol definition with the same parameter. Some possible sequences can be included or excluded conditionally when respectively prefixed with “[+Param]” and “[~Param]”.

A GraphQL document is comprised of several kinds of source tokens defined here in a lexical grammar and used as terminal symbols in GraphQL’s syntactic grammar. This lexical grammar defines patterns of source characters by specifing character
patterns in monospace or as /regular_expressions/. Non‐terminal patterns are defined as Italics.

The GraphQL document syntactic grammar is defined in terms of these lexical tokens:

Before every lexical token may be any amount of ignored source characters such as whitespace and comments. Whitespace, other than within strings, is not significant.

GraphQL treats comma , similarly to whitespace. This ensures that the absense or presence of a comma does not meaningfully alter the interpretted syntax of the document which is a common user‐error in other languages. It also
allows for the stylistic use of trailing commas or line‐breaks as delimiters which are often desired for legibility and maintainability of source code. The use of commas and other whitespace is suggested when it improves legibility.

A GraphQL document is defined in a syntactic grammar where terminal symbols are expressed as either an italicized token (ex. Document) or as monospaced short‐hand for a Punctuator (ex. :) or Name (ex. query).

Fragments allow for the reuse of common selections of fields, reducing duplicated text in the document. Inline fragments can be used directly inline a selection to apply a type condition when querying against an interface or union.