-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathSection 3 -- Type System.md
More file actions
2323 lines (1782 loc) · 79.4 KB
/
Section 3 -- Type System.md
File metadata and controls
2323 lines (1782 loc) · 79.4 KB
Edit and raw actions
OlderNewer
1
# Type System
2
3
The GraphQL Type system describes the capabilities of a GraphQL service and is
4
used to determine if a requested operation is valid, to guarantee the type of
5
response results, and describes the input types of variables to determine if
6
values provided at request time are valid.
7
8
TypeSystemDocument : TypeSystemDefinition+
9
10
TypeSystemDefinition :
11
12
- SchemaDefinition
13
- TypeDefinition
14
- DirectiveDefinition
15
16
The GraphQL language includes an
17
[IDL](https://en.wikipedia.org/wiki/Interface_description_language) used to
18
describe a GraphQL service's type system. Tools may use this definition language
19
to provide utilities such as client code generation or service bootstrapping.
20
21
GraphQL tools or services which only seek to execute GraphQL requests and not
22
construct a new GraphQL schema may choose not to allow {TypeSystemDefinition}.
23
Tools which only seek to produce schema and not execute requests may choose to
24
only allow {TypeSystemDocument} and not allow {ExecutableDefinition} or
25
{TypeSystemExtension} but should provide a descriptive error if present.
26
27
Note: The type system definition language is used throughout the remainder of
28
this specification document when illustrating example type systems.
29
30
## Type System Extensions
31
32
TypeSystemExtensionDocument : TypeSystemDefinitionOrExtension+
33
34
TypeSystemDefinitionOrExtension :
35
36
- TypeSystemDefinition
37
- TypeSystemExtension
38
39
TypeSystemExtension :
40
41
- SchemaExtension
42
- TypeExtension
43
44
Type system extensions are used to represent a GraphQL type system which has
45
been extended from some previous type system. For example, this might be used by
46
a local service to represent data a GraphQL client only accesses locally, or by
47
a GraphQL service which is itself an extension of another GraphQL service.
48
49
Tools which only seek to produce and extend schema and not execute requests may
50
choose to only allow {TypeSystemExtensionDocument} and not allow
51
{ExecutableDefinition} but should provide a descriptive error if present.
52
53
## Type System Descriptions
54
55
Documentation is a first-class feature of GraphQL type systems, written
56
immediately alongside definitions in a {TypeSystemDocument} and made available
57
via introspection.
58
59
[Descriptions](#sec-Descriptions) allow GraphQL service designers to easily
60
provide documentation which remains consistent with the capabilities of a
61
GraphQL service. Descriptions should be provided as Markdown (as specified by
62
[CommonMark](https://commonmark.org/)) for every definition in a type system.
63
64
GraphQL schema and all other definitions (e.g. types, fields, arguments, etc.)
65
which can be described should provide a {Description} unless they are considered
66
self descriptive.
67
68
As an example, this simple GraphQL schema is well described:
69
70
```raw graphql example
71
"""
72
A simple GraphQL schema which is well described.
73
"""
74
schema {
75
query: Query
76
}
77
78
"""
79
Root type for all your query operations
80
"""
81
type Query {
82
"""
83
Translates a string from a given language into a different language.
84
"""
85
translate(
86
"The original language that `text` is provided in."
87
fromLanguage: Language
88
89
"The translated language to be returned."
90
toLanguage: Language
91
92
"The text to be translated."
93
text: String
94
): String
95
}
96
97
"""
98
The set of languages supported by `translate`.
99
"""
100
enum Language {
101
"English"
102
EN
103
104
"French"
105
FR
106
107
"Chinese"
108
CH
109
}
110
```
111
112
## Schema
113
114
SchemaDefinition : Description? schema Directives[Const]? {
115
RootOperationTypeDefinition+ }
116
117
RootOperationTypeDefinition : OperationType : NamedType
118
119
A GraphQL service's collective type system capabilities are referred to as that
120
service's "schema". A schema is defined in terms of the types and directives it
121
supports as well as the _root operation type_ for each kind of operation: query,
122
mutation, and subscription; this determines the place in the type system where
123
those operations begin.
124
125
A GraphQL schema must itself be internally valid. This section describes the
126
rules for this validation process where relevant.
127
128
All types within a GraphQL schema must have unique names. No two provided types
129
may have the same name. No provided type may have a name which conflicts with
130
any built in types (including Scalar and Introspection types).
131
132
All directives within a GraphQL schema must have unique names.
133
134
All types and directives defined within a schema must not have a name which
135
begins with {"\_\_"} (two underscores), as this is used exclusively by GraphQL's
136
introspection system.
137
138
### Root Operation Types
139
140
:: A schema defines the initial _root operation type_ for each kind of operation
141
it supports: query, mutation, and subscription; this determines the place in the
142
type system where those operations begin.
143
144
The {`query`} _root operation type_ must be provided and must be an Object type.
145
146
The {`mutation`} _root operation type_ is optional; if it is not provided, the
147
service does not support mutations. If it is provided, it must be an Object
148
type.
149
150
Similarly, the {`subscription`} _root operation type_ is also optional; if it is
151
not provided, the service does not support subscriptions. If it is provided, it
152
must be an Object type.
153
154
The {`query`}, {`mutation`}, and {`subscription`} root types must all be
155
different types if provided.
156
157
The fields on the {`query`} _root operation type_ indicate what fields are
158
available at the top level of a GraphQL query operation.
159
160
For example, this example operation:
161
162
```graphql example
163
query {
164
myName
165
}
166
```
167
168
is only valid when the {`query`} _root operation type_ has a field named
169
"myName":
170
171
```graphql example
172
type Query {
173
myName: String
174
}
175
```
176
177
Similarly, the following mutation is only valid if the {`mutation`} _root
178
operation type_ has a field named "setName".
179
180
```graphql example
181
mutation {
182
setName(name: "Zuck") {
183
newName
184
}
185
}
186
```
187
188
When using the type system definition language, a document must include at most
189
one {`schema`} definition.
190
191
In this example, a GraphQL schema is defined with both a query and mutation
192
_root operation type_:
193
194
```graphql example
195
schema {
196
query: MyQueryRootType
197
mutation: MyMutationRootType
198
}
199
200
type MyQueryRootType {
201
someField: String
202
}
203
204
type MyMutationRootType {
205
setSomeField(to: String): String
206
}
207
```
208
209
**Default Root Operation Type Names**
210
211
:: The _default root type name_ for each {`query`}, {`mutation`}, and
212
{`subscription`} _root operation type_ are {"Query"}, {"Mutation"}, and
213
{"Subscription"} respectively.
214
215
The type system definition language can omit the schema definition when each
216
_root operation type_ uses its respective _default root type name_, no other
217
type uses any _default root type name_, and the schema does not have a
218
description.
219
220
Likewise, when representing a GraphQL schema using the type system definition
221
language, a schema definition should be omitted if each _root operation type_
222
uses its respective _default root type name_, no other type uses any _default
223
root type name_, and the schema does not have a description.
224
225
This example describes a valid complete GraphQL schema, despite not explicitly
226
including a {`schema`} definition. The {"Query"} type is presumed to be the
227
{`query`} _root operation type_ of the schema.
228
229
```graphql example
230
type Query {
231
someField: String
232
}
233
```
234
235
This example describes a valid GraphQL schema without a {`mutation`} _root
236
operation type_, even though it contains a type named {"Mutation"}. The schema
237
definition must be included, otherwise the {"Mutation"} type would be
238
incorrectly presumed to be the {`mutation`} _root operation type_ of the schema.
239
240
```graphql example
241
schema {
242
query: Query
243
}
244
245
type Query {
246
latestVirus: Virus
247
}
248
249
type Virus {
250
name: String
251
mutations: [Mutation]
252
}
253
254
type Mutation {
255
name: String
256
}
257
```
258
259
This example describes a valid GraphQL schema with a description and both a
260
{`query`} and {`mutation`} operation type:
261
262
```graphql example
263
"""
264
Example schema
265
"""
266
schema {
267
query: Query
268
mutation: Mutation
269
}
270
271
type Query {
272
someField: String
273
}
274
275
type Mutation {
276
someMutation: String
277
}
278
```
279
280
### Schema Extension
281
282
SchemaExtension :
283
284
- extend schema Directives[Const]? { RootOperationTypeDefinition+ }
285
- extend schema Directives[Const] [lookahead != `{`]
286
287
Schema extensions are used to represent a schema which has been extended from a
288
previous schema. For example, this might be used by a GraphQL service which adds
289
additional operation types, or additional directives to an existing schema.
290
291
Note: Schema extensions without additional operation type definitions must not
292
be followed by a {`{`} (such as a query shorthand) to avoid parsing ambiguity.
293
The same limitation applies to the type definitions and extensions below.
294
295
**Schema Validation**
296
297
Schema extensions have the potential to be invalid if incorrectly defined.
298
299
1. The Schema must already be defined.
300
2. Any non-repeatable directives provided must not already apply to the previous
301
Schema.
302
303
## Types
304
305
TypeDefinition :
306
307
- ScalarTypeDefinition
308
- ObjectTypeDefinition
309
- InterfaceTypeDefinition
310
- UnionTypeDefinition
311
- EnumTypeDefinition
312
- InputObjectTypeDefinition
313
314
The fundamental unit of any GraphQL Schema is the type. There are six kinds of
315
named type definitions in GraphQL, and two wrapping types.
316
317
The most basic type is a `Scalar`. A scalar represents a primitive value, like a
318
string or an integer. Oftentimes, the possible responses for a scalar field are
319
enumerable. GraphQL offers an `Enum` type in those cases, where the type
320
specifies the space of valid responses.
321
322
Scalars and Enums form the leaves in response trees; the intermediate levels are
323
`Object` types, which define a set of fields, where each field is another type
324
in the system, allowing the definition of arbitrary type hierarchies.
325
326
GraphQL supports two abstract types: interfaces and unions.
327
328
An `Interface` defines a list of fields; `Object` types and other Interface
329
types which implement this Interface are guaranteed to implement those fields.
330
Whenever a field claims it will return an Interface type, it will return a valid
331
implementing Object type during execution.
332
333
A `Union` defines a list of possible types; similar to interfaces, whenever the
334
type system claims a union will be returned, one of the possible types will be
335
returned.
336
337
Finally, oftentimes it is useful to provide complex structs as inputs to GraphQL
338
field arguments or variables; the `Input Object` type allows the schema to
339
define exactly what data is expected.
340
341
### Wrapping Types
342
343
All of the types so far are assumed to be both nullable and singular: e.g. a
344
scalar string returns either null or a singular string.
345
346
A GraphQL schema may describe that a field represents a list of another type;
347
the `List` type is provided for this reason, and wraps another type.
348
349
Similarly, the `Non-Null` type wraps another type, and denotes that the
350
resulting value will never be {null} (and that an _execution error_ cannot
351
result in a {null} value).
352
353
These two types are referred to as "wrapping types"; non-wrapping types are
354
referred to as "named types". A wrapping type has an underlying named type,
355
found by continually unwrapping the type until a named type is found.
356
357
### Input and Output Types
358
359
Types are used throughout GraphQL to describe both the values accepted as input
360
to arguments and variables as well as the values output by fields. These two
361
uses categorize types as _input types_ and _output types_. Some kinds of types,
362
like Scalar and Enum types, can be used as both input types and output types;
363
other kinds of types can only be used in one or the other. Input Object types
364
can only be used as input types. Object, Interface, and Union types can only be
365
used as output types. Lists and Non-Null types may be used as input types or
366
output types depending on how the wrapped type may be used.
367
368
IsInputType(type):
369
370
- If {type} is a List type or Non-Null type:
371
- Let {unwrappedType} be the unwrapped type of {type}.
372
- Return {IsInputType(unwrappedType)}.
373
- If {type} is a Scalar, Enum, or Input Object type:
374
- Return {true}.
375
- Return {false}.
376
377
IsOutputType(type):
378
379
- If {type} is a List type or Non-Null type:
380
- Let {unwrappedType} be the unwrapped type of {type}.
381
- Return {IsOutputType(unwrappedType)}.
382
- If {type} is a Scalar, Object, Interface, Union, or Enum type:
383
- Return {true}.
384
- Return {false}.
385
386
### Type Extensions
387
388
TypeExtension :
389
390
- ScalarTypeExtension
391
- ObjectTypeExtension
392
- InterfaceTypeExtension
393
- UnionTypeExtension
394
- EnumTypeExtension
395
- InputObjectTypeExtension
396
397
Type extensions are used to represent a GraphQL type which has been extended
398
from some previous type. For example, this might be used by a local service to
399
represent additional fields a GraphQL client only accesses locally.
400
401
## Scalars
402
403
ScalarTypeDefinition : Description? scalar Name Directives[Const]?
404
405
Scalar types represent primitive leaf values in a GraphQL type system. GraphQL
406
responses take the form of a hierarchical tree; the leaves of this tree are
407
typically GraphQL Scalar types (but may also be Enum types or {null} values).
408
409
GraphQL provides a number of built-in scalars which are fully defined in the
410
sections below, however type systems may also add additional custom scalars to
411
introduce additional semantic meaning.
412
413
**Built-in Scalars**
414
415
GraphQL specifies a basic set of well-defined Scalar types: {Int}, {Float},
416
{String}, {Boolean}, and {ID}. A GraphQL framework should support all of these
417
types, and a GraphQL service which provides a type by these names must adhere to
418
the behavior described for them in this document. As an example, a service must
419
not include a type called {Int} and use it to represent 64-bit numbers,
420
internationalization information, or anything other than what is defined in this
421
document.
422
423
When returning the set of types from the `__Schema` introspection type, all
424
referenced built-in scalars must be included. If a built-in scalar type is not
425
referenced anywhere in a schema (there is no field, argument, or input field of
426
that type) then it must not be included.
427
428
When representing a GraphQL schema using the type system definition language,
429
all built-in scalars must be omitted for brevity.
430
431
**Custom Scalars**
432
433
GraphQL services may use custom scalar types in addition to the built-in
434
scalars. For example, a GraphQL service could define a scalar called `UUID`
435
which, while serialized as a string, conforms to
436
[RFC 4122](https://tools.ietf.org/html/rfc4122). When querying a field of type
437
`UUID`, you can then rely on the ability to parse the result with an RFC 4122
438
compliant parser. Another example of a potentially useful custom scalar is
439
`URL`, which serializes as a string, but is guaranteed by the service to be a
440
valid URL.
441
442
:: When defining a custom scalar, GraphQL services should provide a _scalar
443
specification URL_ via the `@specifiedBy` directive or the `specifiedByURL`
444
introspection field. This URL must link to a human-readable specification of the
445
data format, serialization, and coercion rules for the scalar.
446
447
For example, a GraphQL service providing a `UUID` scalar may link to RFC 4122,
448
or some custom document defining a reasonable subset of that RFC. If a _scalar
449
specification URL_ is present, systems and tools that are aware of it should
450
conform to its described rules.
451
452
```graphql example
453
scalar UUID @specifiedBy(url: "https://tools.ietf.org/html/rfc4122")
454
scalar URL @specifiedBy(url: "https://tools.ietf.org/html/rfc3986")
455
scalar DateTime
456
@specifiedBy(url: "https://scalars.graphql.org/andimarek/date-time")
457
```
458
459
Custom *scalar specification URL*s should provide a single, stable format to
460
avoid ambiguity. If the linked specification is in flux, the service should link
461
to a fixed version rather than to a resource which might change.
462
463
Note: Some community-maintained custom scalar specifications are hosted at
464
[scalars.graphql.org](https://scalars.graphql.org/).
465
466
Custom *scalar specification URL*s should not be changed once defined. Doing so
467
would likely disrupt tooling or could introduce breaking changes within the
468
linked specification's contents.
469
470
Built-in scalar types must not provide a _scalar specification URL_ as they are
471
specified by this document.
472
473
Note: Custom scalars should also summarize the specified format and provide
474
examples in their description; see the GraphQL scalars
475
[implementation guide](https://scalars.graphql.org/implementation-guide) for
476
more guidance.
477
478
**Result Coercion and Serialization**
479
480
A GraphQL service, when preparing a field of a given scalar type, must uphold
481
the contract the scalar type describes, either by coercing the value or
482
producing an _execution error_ if a value cannot be coerced or if coercion may
483
result in data loss.
484
485
A GraphQL service may decide to allow coercing different internal types to the
486
expected return type. For example when coercing a field of type {Int} a boolean
487
{true} value may produce {1} or a string value {"123"} may be parsed as base-10
488
{123}. However if internal type coercion cannot be reasonably performed without
489
losing information, then it must raise an _execution error_.
490
491
Since this coercion behavior is not observable to clients of the GraphQL
492
service, the precise rules of coercion are left to the implementation. The only
493
requirement is that the service must yield values which adhere to the expected
494
Scalar type.
495
496
GraphQL scalars are serialized according to the serialization format being used.
497
There may be a most appropriate serialized primitive for each given scalar type,
498
and the service should produce each primitive where appropriate.
499
500
See [Serialization Format](#sec-Serialization-Format) for more detailed
501
information on the serialization of scalars in common JSON and other formats.
502
503
**Input Coercion**
504
505
If a GraphQL service expects a scalar type as input to an argument, coercion is
506
observable and the rules must be well defined. If an input value does not match
507
a coercion rule, a _request error_ must be raised (input values are validated
508
before execution begins).
509
510
GraphQL has different constant literals to represent integer and floating-point
511
input values, and coercion rules may apply differently depending on which type
512
of input value is encountered. GraphQL may be parameterized by variables, the
513
values of which are often serialized when sent over a transport like HTTP. Since
514
some common serializations (e.g. JSON) do not discriminate between integer and
515
floating-point values, they are interpreted as an integer input value if they
516
have an empty fractional part (e.g. `1.0`) and otherwise as floating-point input
517
value.
518
519
For all types below, with the exception of Non-Null, if the explicit value
520
{null} is provided, then the result of input coercion is {null}.
521
522
### Int
523
524
The Int scalar type represents a signed 32-bit numeric non-fractional value.
525
Response formats that support a 32-bit integer or a number type should use that
526
type to represent this scalar.
527
528
**Result Coercion**
529
530
Fields returning the type {Int} expect to encounter 32-bit integer internal
531
values.
532
533
GraphQL services may coerce non-integer internal values to integers when
534
reasonable without losing information, otherwise they must raise an _execution
535
error_. Examples of this may include returning `1` for the floating-point number
536
`1.0`, or returning `123` for the string `"123"`. In scenarios where coercion
537
may lose data, raising an execution error is more appropriate. For example, a
538
floating-point number `1.2` should raise an execution error instead of being
539
truncated to `1`.
540
541
If the integer internal value represents a value less than -2<sup>31</sup> or
542
greater than or equal to 2<sup>31</sup>, an _execution error_ should be raised.
543
544
**Input Coercion**
545
546
When expected as an input type, only integer input values are accepted. All
547
other input values, including strings with numeric content, must raise a request
548
error indicating an incorrect type. If the integer input value represents a
549
value less than -2<sup>31</sup> or greater than or equal to 2<sup>31</sup>, a
550
_request error_ should be raised.
551
552
Note: Numeric integer values larger than 32-bit should either use String or a
553
custom-defined Scalar type, as not all platforms and transports support encoding
554
integer numbers larger than 32-bit.
555
556
### Float
557
558
The Float scalar type represents signed double-precision finite values as
559
specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point).
560
Response formats that support an appropriate double-precision number type should
561
use that type to represent this scalar.
562
563
**Result Coercion**
564
565
Fields returning the type {Float} expect to encounter double-precision
566
floating-point internal values.
567
568
GraphQL services may coerce non-floating-point internal values to {Float} when
569
reasonable without losing information, otherwise they must raise an _execution
570
error_. Examples of this may include returning `1.0` for the integer number `1`,
571
or `123.0` for the string `"123"`.
572
573
Non-finite floating-point internal values ({NaN} and {Infinity}) cannot be
574
coerced to {Float} and must raise an _execution error_.
575
576
**Input Coercion**
577
578
When expected as an input type, both integer and float input values are
579
accepted. Integer input values are coerced to Float by adding an empty
580
fractional part, for example `1.0` for the integer input value `1`. All other
581
input values, including strings with numeric content, must raise a _request
582
error_ indicating an incorrect type. If the input value otherwise represents a
583
value not representable by finite IEEE 754 (e.g. {NaN}, {Infinity}, or a value
584
outside the available precision), a _request error_ must be raised.
585
586
### String
587
588
The String scalar type represents textual data, represented as a sequence of
589
Unicode code points. The String type is most often used by GraphQL to represent
590
free-form human-readable text. How the String is encoded internally (for example
591
UTF-8) is left to the service implementation. All response serialization formats
592
must support a string representation (for example, JSON Unicode strings), and
593
that representation must be used to serialize this type.
594
595
**Result Coercion**
596
597
Fields returning the type {String} expect to encounter Unicode string values.
598
599
GraphQL services may coerce non-string raw values to {String} when reasonable
600
without losing information, otherwise they must raise an _execution error_.
601
Examples of this may include returning the string `"true"` for a boolean true
602
value, or the string `"1"` for the integer `1`.
603
604
**Input Coercion**
605
606
When expected as an input type, only valid Unicode string input values are
607
accepted. All other input values must raise a _request error_ indicating an
608
incorrect type.
609
610
### Boolean
611
612
The Boolean scalar type represents `true` or `false`. Response formats should
613
use a built-in boolean type if supported; otherwise, they should use their
614
representation of the integers `1` and `0`.
615
616
**Result Coercion**
617
618
Fields returning the type {Boolean} expect to encounter boolean internal values.
619
620
GraphQL services may coerce non-boolean raw values to {Boolean} when reasonable
621
without losing information, otherwise they must raise an _execution error_.
622
Examples of this may include returning `true` for non-zero numbers.
623
624
**Input Coercion**
625
626
When expected as an input type, only boolean input values are accepted. All
627
other input values must raise a _request error_ indicating an incorrect type.
628
629
### ID
630
631
The ID scalar type represents a unique identifier, often used to refetch an
632
object or as the key for a cache. The ID type is serialized in the same way as a
633
{String}; however, it is not intended to be human-readable. While it is often
634
numeric, it must always serialize as a {String}.
635
636
**Result Coercion**
637
638
GraphQL is agnostic to ID format, and serializes to string to ensure consistency
639
across many formats ID could represent, from small auto-increment numbers, to
640
large 128-bit random numbers, to base64 encoded values, or string values of a
641
format like [GUID](https://en.wikipedia.org/wiki/Globally_unique_identifier).
642
643
GraphQL services should coerce as appropriate given the ID formats they expect.
644
When coercion is not possible they must raise an _execution error_.
645
646
**Input Coercion**
647
648
When expected as an input type, any string (such as `"4"`) or integer (such as
649
`4` or `-4`) input value should be coerced to ID as appropriate for the ID
650
formats a given GraphQL service expects. Any other input value, including float
651
input values (such as `4.0`), must raise a _request error_ indicating an
652
incorrect type.
653
654
### Scalar Extensions
655
656
ScalarTypeExtension :
657
658
- extend scalar Name Directives[Const]
659
660
Scalar type extensions are used to represent a scalar type which has been
661
extended from some previous scalar type. For example, this might be used by a
662
GraphQL tool or service which adds directives to an existing scalar.
663
664
**Type Validation**
665
666
Scalar type extensions have the potential to be invalid if incorrectly defined.
667
668
1. The named type must already be defined and must be a Scalar type.
669
2. Any non-repeatable directives provided must not already apply to the previous
670
Scalar type.
671
672
## Objects
673
674
ObjectTypeDefinition :
675
676
- Description? type Name ImplementsInterfaces? Directives[Const]?
677
FieldsDefinition
678
- Description? type Name ImplementsInterfaces? Directives[Const]? [lookahead !=
679
`{`]
680
681
ImplementsInterfaces :
682
683
- ImplementsInterfaces & NamedType
684
- implements `&`? NamedType
685
686
FieldsDefinition : { FieldDefinition+ }
687
688
FieldDefinition : Description? Name ArgumentsDefinition? : Type
689
Directives[Const]?
690
691
GraphQL operations are hierarchical and composed, describing a tree of
692
information. While Scalar types describe the leaf values of these hierarchical
693
operations, Objects describe the intermediate levels.
694
695
GraphQL Objects represent a list of named fields, each of which yields a value
696
of a specific type. Object values should be serialized as ordered maps, where
697
the selected field names (or aliases) are the keys and the result of evaluating
698
the field is the value, ordered by the order in which they appear in the
699
_selection set_.
700
701
All fields defined within an Object type must not have a name which begins with
702
{"\_\_"} (two underscores), as this is used exclusively by GraphQL's
703
introspection system.
704
705
For example, a type `Person` could be described as:
706
707
```graphql example
708
type Person {
709
name: String
710
age: Int
711
picture: Url
712
}
713
```
714
715
Where `name` is a field that will yield a {String} value, and `age` is a field
716
that will yield an {Int} value, and `picture` is a field that will yield a `Url`
717
value.
718
719
A query of an object value must select at least one field. This selection of
720
fields will yield an ordered map containing exactly the subset of the object
721
queried, which should be represented in the order in which they were queried.
722
Only fields that are declared on the object type may validly be queried on that
723
object.
724
725
For example, selecting all the fields of `Person`:
726
727
```graphql example
728
{
729
name
730
age
731
picture
732
}
733
```
734
735
Would yield the object:
736
737
```json example
738
{
739
"name": "Mark Zuckerberg",
740
"age": 30,
741
"picture": "http://some.cdn/picture.jpg"
742
}
743
```
744
745
While selecting a subset of fields:
746
747
```graphql example
748
{
749
age
750
name
751
}
752
```
753
754
Must only yield exactly that subset:
755
756
```json example
757
{
758
"age": 30,
759
"name": "Mark Zuckerberg"
760
}
761
```
762
763
A field of an Object type may be a Scalar, Enum, another Object type, an
764
Interface, or a Union. Additionally, it may be any wrapping type whose
765
underlying base type is one of those five.
766
767
For example, the `Person` type might include a `relationship`:
768
769
```graphql example
770
type Person {
771
name: String
772
age: Int
773
picture: Url
774
relationship: Person
775
}
776
```
777
778
Valid operations must supply a _selection set_ for every field whose return type
779
is an object type, so this operation is not valid:
780
781
```graphql counter-example
782
{
783
name
784
relationship
785
}
786
```
787
788
However, this example is valid:
789
790
```graphql example
791
{
792
name
793
relationship {
794
name
795
}
796
}
797
```
798
799
And will yield the subset of each object type queried:
800
801
```json example
802
{
803
"name": "Mark Zuckerberg",
804
"relationship": {
805
"name": "Priscilla Chan"
806
}
807
}
808
```
809
810
**Field Ordering**
811
812
When querying an Object, the resulting mapping of fields are conceptually
813
ordered in the same order in which they were encountered during execution,
814
excluding fragments for which the type does not apply and fields or fragments
815
that are skipped via `@skip` or `@include` directives. This ordering is
816
correctly produced when using the {CollectFields()} algorithm.
817
818
Response serialization formats capable of representing ordered maps should
819
maintain this ordering. Serialization formats which can only represent unordered
820
maps (such as JSON) should retain this order textually. That is, if two fields
821
`{foo, bar}` were queried in that order, the resulting JSON serialization should
822
contain `{"foo": "...", "bar": "..."}` in the same order.
823
824
Producing a response where fields are represented in the same order in which
825
they appear in the request improves human readability during debugging and
826
enables more efficient parsing of responses if the order of properties can be
827
anticipated.
828
829
If a fragment is spread before other fields, the fields that fragment specifies
830
occur in the response before the following fields.
831
832
```graphql example
833
{
834
foo
835
...Frag
836
qux
837
}
838
839
fragment Frag on Query {
840
bar
841
baz
842
}
843
```
844
845
Produces the ordered result:
846
847
```json example
848
{
849
"foo": 1,
850
"bar": 2,
851
"baz": 3,
852
"qux": 4
853
}
854
```
855
856
If a field is queried multiple times in a selection, it is ordered by the first
857
time it is encountered. However fragments for which the type does not apply do
858
not affect ordering.
859
860
```graphql example
861
{
862
foo
863
...Ignored
864
...Matching
865
bar
866
}
867
868
fragment Ignored on UnknownType {
869
qux
870
baz
871
}
872
873
fragment Matching on Query {
874
bar
875
qux
876
foo
877
}
878
```
879
880
Produces the ordered result:
881
882
```json example
883
{
884
"foo": 1,
885
"bar": 2,
886
"qux": 3
887
}
888
```
889
890
Also, if directives result in fields being excluded, they are not considered in
891
the ordering of fields.
892
893
```graphql example
894
{
895
foo @skip(if: true)
896
bar
897
foo
898
}
899
```
900
901
Produces the ordered result:
902
903
```json example
904
{
905
"bar": 1,
906
"foo": 2
907
}
908
```
909
910
**Result Coercion**
911
912
Determining the result of coercing an object is the heart of the GraphQL
913
executor, see [Value Completion](#sec-Value-Completion).
914
915
**Input Coercion**
916
917
Objects are never valid inputs.
918
919
**Type Validation**
920
921
Object types have the potential to be invalid if incorrectly defined. This set
922
of rules must be adhered to by every Object type in a GraphQL schema.
923
924
1. An Object type must define one or more fields.
925
2. For each field of an Object type:
926
1. The field must have a unique name within that Object type; no two fields
927
may share the same name.
928
2. The field must not have a name which begins with the characters {"\_\_"}
929
(two underscores).
930
3. The field must return a type where {IsOutputType(fieldType)} returns
931
{true}.
932
4. For each argument of the field:
933
1. The argument must not have a name which begins with the characters
934
{"\_\_"} (two underscores).
935
2. The argument must have a unique name within that field; no two
936
arguments may share the same name.
937
3. The argument must accept a type where {IsInputType(argumentType)}
938
returns {true}.
939
4. If argument type is Non-Null and a default value is not defined:
940
1. The `@deprecated` directive must not be applied to this argument.
941
5. If the argument has a default value it must be compatible with
942
{argumentType} as per the coercion rules for that type.
943
3. An object type may declare that it implements one or more unique interfaces.
944
4. An object type must be a super-set of all interfaces it implements:
945
1. Let this object type be {objectType}.
946
2. For each interface declared implemented as {interfaceType},
947
{IsValidImplementation(objectType, interfaceType)} must be {true}.
948
949
IsValidImplementation(type, implementedType):
950
951
1. If {implementedType} declares it implements any interfaces, {type} must also
952
declare it implements those interfaces.
953
2. {type} must include a field of the same name for every field defined in
954
{implementedType}.
955
1. Let {field} be that named field on {type}.
956
2. Let {implementedField} be that named field on {implementedType}.
957
3. {field} must include an argument of the same name for every argument
958
defined in {implementedField}.
959
1. That named argument on {field} must accept the same type (invariant)
960
as that named argument on {implementedField}.
961
4. {field} may include additional arguments not defined in
962
{implementedField}, but any additional argument must not be required,
963
e.g. must not be of a non-nullable type.
964
5. {field} must return a type which is equal to or a sub-type of (covariant)
965
the return type of {implementedField} field's return type:
966
1. Let {fieldType} be the return type of {field}.
967
2. Let {implementedFieldType} be the return type of {implementedField}.
968
3. {IsValidImplementationFieldType(fieldType, implementedFieldType)} must
969
be {true}.
970
6. If {field} is deprecated then {implementedField} must also be deprecated.
971
972
IsValidImplementationFieldType(fieldType, implementedFieldType):
973
974
1. If {fieldType} is a Non-Null type:
975
1. Let {nullableType} be the unwrapped nullable type of {fieldType}.
976
2. Let {implementedNullableType} be the unwrapped nullable type of
977
{implementedFieldType} if it is a Non-Null type, otherwise let it be
978
{implementedFieldType} directly.
979
3. Return {IsValidImplementationFieldType(nullableType,
980
implementedNullableType)}.
981
2. If {fieldType} is a List type and {implementedFieldType} is also a List type:
982
1. Let {itemType} be the unwrapped item type of {fieldType}.
983
2. Let {implementedItemType} be the unwrapped item type of
984
{implementedFieldType}.
985
3. Return {IsValidImplementationFieldType(itemType, implementedItemType)}.
986
3. Return {IsSubType(fieldType, implementedFieldType)}.
987
988
IsSubType(possibleSubType, superType):
989
990
1. If {possibleSubType} is the same type as {superType} then return {true}.
991
2. If {possibleSubType} is an Object type and {superType} is a Union type and
992
{possibleSubType} is a possible type of {superType} then return {true}.
993
3. If {possibleSubType} is an Object or Interface type and {superType} is an
994
Interface type and {possibleSubType} declares it implements {superType} then
995
return {true}.
996
4. Otherwise return {false}.
997
998
### Field Arguments
999
1000
ArgumentsDefinition : ( InputValueDefinition+ )