đ Transform CodeAssist into Production-Ready AI-Powered Mobile IDE
đŻ Project Vision
Transform the existing CodeAssist mobile code editor into a production-ready, full-featured AI-powered mobile IDE that supports modern development workflows, extensibility, and multi-agent AI assistance.
đ Core Requirements
đ§ AI-Powered Development
- [ ] AI-powered code completion (context-aware, project-wide)
- [ ] AI code review and refactoring suggestions
- [ ] Natural language command support (text and voice)
- [ ] Multi-model orchestration with error handling and model fallback
- [ ] AI agent memory for persistent context
- [ ] Agent marketplace and plugin system
âď¸ Rich Code Editor
- [ ] Enhanced syntax highlighting and linting
- [ ] Code snippets and intelligent autocomplete
- [ ] Error detection with inline feedback
- [ ] Language support extensibility (Java, Kotlin, Python, etc.)
- [ ] Code folding and minimap
đ Project Management
- [ ] Advanced file tree navigation with search
- [ ] Multi-tab editor with split view support
- [ ] Multi-project workspace support
- [ ] Project templates and build configurations
- [ ] File watchers and auto-save
đ§Ş Debugging and Build Tools
- [ ] Breakpoint management and step-through debugging
- [ ] Variable inspection and call stack visualization
- [ ] Emulator and real device deployment
- [ ] Build/run integration for multiple languages
- [ ] Test runner integration
đ Git Integration
- [ ] Full Git workflow (commit, push, pull, merge)
- [ ] Branch management and visualization
- [ ] Diff viewer with syntax highlighting
- [ ] Git history and blame view
- [ ] Stash management
đ§Š Extension System
- [ ] Plugin architecture with sandboxing
- [ ] Agent marketplace with downloadable extensions
- [ ] Plugin lifecycle management
- [ ] Sample agent/plugin templates
- [ ] API documentation for developers
đ¨ User Experience
- [ ] Modern Material Design 3 UI
- [ ] Dark/light/system theme support
- [ ] Comprehensive accessibility support
- [ ] Internationalization (i18n) support
- [ ] Interactive onboarding tutorial
đĄď¸ Security and Privacy
- [ ] Secure data storage and encryption
- [ ] Plugin sandboxing and permissions
- [ ] Privacy-first analytics (opt-in)
- [ ] Authentication framework
- [ ] Data backup and sync
đ CI/CD and Remote Development
- [ ] Git-based CI trigger integration
- [ ] Remote development support (SSH/API)
- [ ] Build pipeline visualization
- [ ] Cloud workspace synchronization
đ Profiling and Monitoring
- [ ] Memory, CPU, and network profiling
- [ ] Real-time logcat integration
- [ ] Crash reporting and diagnostics
- [ ] Performance analytics dashboard
đď¸ Architecture Requirements
Modern Android Development Stack
- Language: Kotlin-first development
- Architecture: MVVM/MVI with clear separation of concerns
- Concurrency: Coroutines and Flows for async operations
- DI: Dependency injection with Hilt
- UI: Jetpack Compose for modern, declarative UI
- Navigation: Navigation Component with type-safe arguments
- Storage: Room database with migrations
- Network: Retrofit with OkHttp for API calls
Modular Architecture
app/
âââ core/
â âââ common/ # Shared utilities and extensions
â âââ data/ # Data layer (repositories, data sources)
â âââ database/ # Room database and DAOs
â âââ network/ # Network layer and API definitions
â âââ ui/ # Shared UI components and themes
âââ features/
â âââ editor/ # Code editor functionality
â âââ project/ # Project management
â âââ git/ # Git integration
â âââ ai/ # AI services and agents
â âââ debug/ # Debugging tools
â âââ build/ # Build system integration
â âââ marketplace/ # Plugin marketplace
âââ shared/
âââ resources/ # Shared resources and assets
âââ testing/ # Test utilities and mocks
AI Integration Architecture
- AI Orchestrator Service: Central coordinator for AI operations
- Agent Framework: Pluggable AI agents with memory persistence
- Model Abstraction: Support for multiple AI providers (OpenAI, local models)
- Context Management: Project-wide code understanding and memory
- Voice Integration: Android Speech Recognition for voice commands
đ§Ş Quality Assurance
Testing Strategy
- [ ] Unit tests (90%+ coverage target)
- [ ] Integration tests for core workflows
- [ ] UI tests with Espresso/Compose Testing
- [ ] Performance tests and benchmarks
- [ ] Accessibility testing automation
Code Quality
- [ ] Static analysis with Detekt and ktlint
- [ ] Android Lint integration
- [ ] Code review automation
- [ ] Security vulnerability scanning
- [ ] Performance profiling
CI/CD Pipeline
- [ ] GitHub Actions workflow
- [ ] Automated testing on PR
- [ ] APK generation and signing
- [ ] Release automation
- [ ] Documentation generation
đŚ Deliverables
-
Complete Android Studio Project
- Source code with modular architecture
- Build scripts and configuration
- Resource files and assets
-
Documentation
- Comprehensive README with setup instructions
- API documentation for extension developers
- User manual with screenshots
- Architecture decision records (ADRs)
-
Testing Suite
- Unit tests for all components
- Integration tests for workflows
- UI tests for critical paths
- Performance benchmarks
-
CI/CD Configuration
- GitHub Actions workflows
- Automated testing and deployment
- Code quality gates
-
Sample Extensions
- Example AI agents
- Plugin templates
- Language support modules
-
Localization and Accessibility
- String resources for multiple languages
- Accessibility metadata and testing
- Screen reader compatibility
đŚ Implementation Phases
Phase 1: Foundation (Weeks 1-2)
- [ ] Audit existing codebase
- [ ] Set up modular architecture
- [ ] Implement core data layer
- [ ] Set up CI/CD pipeline
Phase 2: Core Features (Weeks 3-6)
- [ ] Enhanced code editor
- [ ] Project management system
- [ ] Basic AI integration
- [ ] Git functionality
Phase 3: Advanced Features (Weeks 7-10)
- [ ] Debugging tools
- [ ] Build system integration
- [ ] Plugin architecture
- [ ] Advanced AI features
Phase 4: Polish and Performance (Weeks 11-12)
- [ ] UI/UX improvements
- [ ] Performance optimization
- [ ] Security hardening
- [ ] Documentation completion
đŻ Success Criteria
- Performance: Smooth operation on devices with 4GB+ RAM
- Stability: <1% crash rate in production
- User Experience: 4.5+ star rating target
- Code Quality: 90%+ test coverage, zero critical security issues
- Extensibility: Plugin API supports third-party development
- Accessibility: WCAG 2.1 AA compliance
đ¤ Contributing
This is a major undertaking that will benefit from community involvement. Areas where contributors can help:
- Core Development: Architecture, features, and bug fixes
- AI Agents: Developing specialized AI assistants
- Language Support: Adding new programming language modules
- Testing: Writing comprehensive test suites
- Documentation: User guides and developer documentation
- Localization: Translation to multiple languages
đ Next Steps
- Architecture Review: Detailed analysis of current codebase
- Technical Specification: Detailed technical requirements document
- Milestone Planning: Break down into manageable development sprints
- Team Assembly: Identify core contributors and areas of expertise
- Development Environment: Set up development and testing infrastructure
This transformation will position CodeAssist as a leading mobile development platform, bringing desktop IDE capabilities to mobile devices with the power of AI assistance.
Bro this project is no on sale
???
``GraphQL
June 2018 Edition BigDate
La voz Dulcea
Introduction byŠ pelopedment
This is the specification for GraphQL, a query language and execution engine originally created at Facebook in 2012 for describing the capabilities and requirements of data models for clientâserver applications. The development of this open standard started in 2015.
GraphQL 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 facebook.github.io/graphql/draft/.
Copyright notice
Copyright Š 2015âpresent, Facebook, Inc.
As of September 26, 2017, the following persons or entities have made this Specification available under the Open Web Foundation Final Specification Agreement (OWFa 1.0), which is available at openwebfoundation.org.
Facebook, Inc. You can review the signed copies of the Open Web Foundation Final Specification Agreement Version 1.0 for this specification at github.com/facebook/graphql, which may also include additional parties to those listed above.
Your use of this Specification may be subject to other third party rights. THIS SPECIFICATION IS PROVIDED âAS IS.â The contributors 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 Specification. The entire risk as to implementing or otherwise using the Specification is assumed by the Specification implementer and user. IN NO EVENT WILL ANY PARTY 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 SPECIFICATION OR ITS GOVERNING AGREEMENT, WHETHER BASED ON BREACH OF CONTRACT, TORT (INCLUDING NEGLIGENCE), OR OTHERWISE, AND WHETHER OR NOT THE OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Conformance
A conforming implementation of GraphQL 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 may provide additional functionality, but must not where explicitly disallowed or would otherwise result in nonâconformance.
Conforming Algorithms
Algorithm steps phrased in imperative grammar (e.g. âReturn the result of calling resolverâ) are to be interpreted with the same level of requirement as the algorithm it is contained within. Any algorithm referenced within an algorithm step (e.g. âLet completedResult be the result of calling CompleteValue()â) is to be interpreted as having at least the same level of requirement as the algorithm containing that step.
Conformance requirements expressed as algorithms can be fulfilled by an implementation of this specification in any way as long as the perceived result is equivalent. Algorithms described in this document are written to be easy to understand. Implementers are encouraged to include equivalent but optimized implementations.
See Appendix A for more details about the definition of algorithms and other notational conventions used in this document.
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 â 1 This is an example of a non-normative example. Counter Example â 2 This 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:
This is an example of a nonânormative note. Contents 1Overview 2Language 2.1Source Text 2.1.1Unicode 2.1.2White Space 2.1.3Line Terminators 2.1.4Comments 2.1.5Insignificant Commas 2.1.6Lexical Tokens 2.1.7Ignored Tokens 2.1.8Punctuators 2.1.9Names 2.2Document 2.3Operations 2.4Selection Sets 2.5Fields 2.6Arguments 2.7Field Alias 2.8Fragments 2.8.1Type Conditions 2.8.2Inline Fragments 2.9Input Values 2.9.1Int Value 2.9.2Float Value 2.9.3Boolean Value 2.9.4String Value 2.9.5Null Value 2.9.6Enum Value 2.9.7List Value 2.9.8Input Object Values 2.10Variables 2.11Type References 2.12Directives 3Type System 3.1Type System Extensions 3.2Schema 3.2.1Root Operation Types 3.2.2Schema Extension 3.3Descriptions 3.4Types 3.4.1Wrapping Types 3.4.2Input and Output Types 3.4.3Type Extensions 3.5Scalars 3.5.1Int 3.5.2Float 3.5.3String 3.5.4Boolean 3.5.5ID 3.5.6Scalar Extensions 3.6Objects 3.6.1Field Arguments 3.6.2Field Deprecation 3.6.3Object Extensions 3.7Interfaces 3.7.1Interface Extensions 3.8Unions 3.8.1Union Extensions 3.9Enums 3.9.1Enum Extensions 3.10Input Objects 3.10.1Input Object Extensions 3.11List 3.12Non-Null 3.12.1Combining List and Non-Null 3.13Directives 3.13.1@skip 3.13.2@include 3.13.3@deprecated 4Introspection 4.1Reserved Names 4.2Documentation 4.3Deprecation 4.4Type Name Introspection 4.5Schema Introspection 4.5.1The __Type Type 4.5.2Type Kinds 4.5.2.1Scalar 4.5.2.2Object 4.5.2.3Union 4.5.2.4Interface 4.5.2.5Enum 4.5.2.6Input Object 4.5.2.7List 4.5.2.8Non-Null 4.5.3The __Field Type 4.5.4The __InputValue Type 4.5.5The __EnumValue Type 4.5.6The __Directive Type 5Validation 5.1Documents 5.1.1Executable Definitions 5.2Operations 5.2.1Named Operation Definitions 5.2.1.1Operation Name Uniqueness 5.2.2Anonymous Operation Definitions 5.2.2.1Lone Anonymous Operation 5.2.3Subscription Operation Definitions 5.2.3.1Single root field 5.3Fields 5.3.1Field Selections on Objects, Interfaces, and Unions Types 5.3.2Field Selection Merging 5.3.3Leaf Field Selections 5.4Arguments 5.4.1Argument Names 5.4.2Argument Uniqueness 5.4.2.1Required Arguments 5.5Fragments 5.5.1Fragment Declarations 5.5.1.1Fragment Name Uniqueness 5.5.1.2Fragment Spread Type Existence 5.5.1.3Fragments On Composite Types 5.5.1.4Fragments Must Be Used 5.5.2Fragment Spreads 5.5.2.1Fragment spread target defined 5.5.2.2Fragment spreads must not form cycles 5.5.2.3Fragment spread is possible 5.5.2.3.1Object Spreads In Object Scope 5.5.2.3.2Abstract Spreads in Object Scope 5.5.2.3.3Object Spreads In Abstract Scope 5.5.2.3.4Abstract Spreads in Abstract Scope 5.6Values 5.6.1Values of Correct Type 5.6.2Input Object Field Names 5.6.3Input Object Field Uniqueness 5.6.4Input Object Required Fields 5.7Directives 5.7.1Directives Are Defined 5.7.2Directives Are In Valid Locations 5.7.3Directives Are Unique Per Location 5.8Variables 5.8.1Variable Uniqueness 5.8.2Variables Are Input Types 5.8.3All Variable Uses Defined 5.8.4All Variables Used 5.8.5All Variable Usages are Allowed 6Execution 6.1Executing Requests 6.1.1Validating Requests 6.1.2Coercing Variable Values 6.2Executing Operations 6.2.1Query 6.2.2Mutation 6.2.3Subscription 6.2.3.1Source Stream 6.2.3.2Response Stream 6.2.3.3Unsubscribe 6.3Executing Selection Sets 6.3.1Normal and Serial Execution 6.3.2Field Collection 6.4Executing Fields 6.4.1Coercing Field Arguments 6.4.2Value Resolution 6.4.3Value Completion 6.4.4Errors and Non-Nullability 7Response 7.1Response Format 7.1.1Data 7.1.2Errors 7.2Serialization Format 7.2.1JSON Serialization 7.2.2Serialized Map Ordering AAppendix: Notation Conventions A.1Context-Free Grammar A.2Lexical and Syntactical Grammar A.3Grammar Notation A.4Grammar Semantics A.5Algorithms BAppendix: Grammar Summary B.1Ignored Tokens B.2Lexical Tokens B.3Document §Index 1Overview 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.
Example â 3 { user(id: 4) { name } } Which produces the resulting data (in JSON):
Example â 4 { "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:
Hierarchical: 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 builds 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.
2Language Clients use the GraphQL query language to make requests to a GraphQL service. We refer to these request sources as documents. A document may contain operations (queries, mutations, and subscriptions) as well as fragments, a common unit of composition allowing for query reuse.
A GraphQL document is defined as a syntactic grammar where terminal symbols are tokens (indivisible lexical units). These tokens are defined in a lexical grammar which matches patterns of source characters (defined by a doubleâcolon ::).
See Appendix A for more details about the definition of lexical and syntactic grammar and other notational conventions used in this document. 2.1Source Text SourceCharacter /[\u0009\u000A\u000D\u0020-\uFFFF]/ GraphQL documents are expressed as a sequence of Unicode characters. However, with few exceptions, most of GraphQL is expressed only in the original nonâcontrol ASCII range so as to be as widely compatible with as many existing tools, languages, and serialization formats as possible and avoid display issues in text editors and source control.
2.1.1Unicode UnicodeBOM Byte Order Mark (U+FEFF) NonâASCII Unicode characters may freely appear within StringValue and Comment portions of GraphQL.
The âByte Order Markâ is a special Unicode character which may appear at the beginning of a file containing Unicode which programs may use to determine the fact that the text stream is Unicode, what endianness the text stream is in, and which of several Unicode encodings to interpret.
2.1.2White Space WhiteSpace Horizontal Tab (U+0009) Space (U+0020) White space is used to improve legibility of source text and act as separation between tokens, and any amount of white space may appear before or after any token. White space between tokens is not significant to the semantic meaning of a GraphQL Document, however white space characters may appear within a String or Comment token.
GraphQL intentionally does not consider Unicode âZsâ category characters as whiteâspace, avoiding misinterpretation by text editors and source control tools. 2.1.3Line Terminators LineTerminator New Line (U+000A) Carriage Return (U+000D)New Line (U+000A) Carriage Return (U+000D)New Line (U+000A) Like white space, line terminators are used to improve the legibility of source text, any amount may appear before or after any other token and have no significance to the semantic meaning of a GraphQL Document. Line terminators are not found within any other token.
Any error reporting which provide the line number in the source of the offending syntax should use the preceding amount of LineTerminator to produce the line number. 2.1.4Comments Comment #CommentCharlistopt CommentChar SourceCharacterLineTerminator GraphQL source documents may contain singleâline comments, starting with the # marker.
A comment can contain any Unicode code point except LineTerminator so a comment always consists of all code points starting with the # character up to but not including the line terminator.
Comments behave like white space and may appear after any token, or before a line terminator, and have no significance to the semantic meaning of a GraphQL Document.
2.1.5Insignificant Commas Comma , Similar to white space and line terminators, commas (,) are used to improve the legibility of source text and separate lexical tokens but are otherwise syntactically and semantically insignificant within GraphQL Documents.
Nonâsignificant comma characters ensure that the absence or presence of a comma does not meaningfully alter the interpreted syntax of the document, as this can be a common userâerror in other languages. It also allows for the stylistic use of either trailing commas or lineâterminators as list delimiters which are both often desired for legibility and maintainability of source code.
2.1.6Lexical Tokens Token Punctuator Name IntValue FloatValue StringValue A GraphQL document is comprised of several kinds of indivisible lexical tokens defined here in a lexical grammar by patterns of source Unicode characters.
Tokens are later used as terminal symbols in a GraphQL Document syntactic grammars.
2.1.7Ignored Tokens Ignored UnicodeBOM WhiteSpace LineTerminator Comment Comma Before and after every lexical token may be any amount of ignored tokens including WhiteSpace and Comment. No ignored regions of a source document are significant, however ignored source characters may appear within a lexical token in a significant way, for example a String may contain white space characters.
No characters are ignored while parsing a given token, as an example no white space characters are permitted between the characters defining a FloatValue.
2.1.8Punctuators Punctuator ! $ ( ) ... : = @ [ ] { | } GraphQL documents include punctuation in order to describe structure. GraphQL is a data description language and not a programming language, therefore GraphQL lacks the punctuation often used to describe mathematical expressions.
2.1.9Names Name /[_A-Za-z][_0-9A-Za-z]*/ GraphQL Documents are full of named things: operations, fields, arguments, types, directives, fragments, and variables. All names must follow the same grammatical form.
Names in GraphQL are caseâsensitive. That is to say name, Name, and NAME all refer to different names. Underscores are significant, which means other_name and othername are two different names.
Names in GraphQL are limited to this ASCII subset of possible characters to support interoperation with as many other systems as possible.
2.2Document Document Definitionlist Definition ExecutableDefinition TypeSystemDefinition TypeSystemExtension ExecutableDefinition OperationDefinition FragmentDefinition A GraphQL Document describes a complete file or request string operated on by a GraphQL service or client. A document contains multiple definitions, either executable or representative of a GraphQL type system.
Documents are only executable by a GraphQL service if they contain an OperationDefinition and otherwise only contain ExecutableDefinition. However documents which do not contain OperationDefinition or do contain TypeSystemDefinition or TypeSystemExtension may still be parsed and validated to allow client tools to represent many GraphQL uses which may appear across many individual files.
If a Document contains only one operation, that operation may be unnamed or represented in the shorthand form, which omits both the query keyword and operation name. Otherwise, if a GraphQL Document contains multiple operations, each operation must be named. When submitting a Document with multiple operations to a GraphQL service, the name of the desired operation to be executed must also be provided.
GraphQL services which only seek to provide GraphQL query execution may choose to only include ExecutableDefinition and omit the TypeSystemDefinition and TypeSystemExtension rules from Definition.
2.3Operations OperationDefinition OperationTypeNameoptVariableDefinitionsoptDirectivesoptSelectionSet SelectionSet OperationType query mutation subscription There are three types of operations that GraphQL models:
query â a readâonly fetch. mutation â a write followed by a fetch. subscription â a longâlived request that fetches data in response to source events. Each operation is represented by an optional operation name and a selection set.
For example, this mutation operation might âlikeâ a story and then retrieve the new number of likes:
Example â 5 mutation { likeStory(storyID: 12345) { story { likeCount } } } Query shorthand
If a document contains only one query operation, and that query defines no variables and contains no directives, that operation may be represented in a shortâhand form which omits the query keyword and query name.
For example, this unnamed query operation is written via query shorthand.
Example â 6 { field } many examples below will use the query shortâhand syntax. 2.4Selection Sets SelectionSet {Selectionlist} Selection Field FragmentSpread InlineFragment An operation selects the set of information it needs, and will receive exactly that information and nothing more, avoiding overâfetching and underâfetching data.
Example â 7 { id firstName lastName } In this query, the id, firstName, and lastName fields form a selection set. Selection sets may also contain fragment references.
2.5Fields Field AliasoptNameArgumentsoptDirectivesoptSelectionSetopt A selection set is primarily composed of fields. A field describes one discrete piece of information available to request within a selection set.
Some fields describe complex data or relationships to other data. In order to further explore this data, a field may itself contain a selection set, allowing for deeply nested requests. All GraphQL operations must specify their selections down to fields which return scalar values to ensure an unambiguously shaped response.
For example, this operation selects fields of complex data and relationships down to scalar values.
Example â 8 { me { id firstName lastName birthday { month day } friends { name } } } Fields in the topâlevel selection set of an operation often represent some information that is globally accessible to your application and its current viewer. Some typical examples of these top fields include references to a current loggedâin viewer, or accessing certain types of data referenced by a unique identifier.
Example â 9
me could represent the currently logged in viewer.
{ me { name } }
user represents one of many users in a graph of data, referred to by a
unique identifier.
{ user(id: 4) { name } } 2.6Arguments ArgumentsConst (ArgumentConstlist) ArgumentConst Name:ValueConst Fields are conceptually functions which return values, and occasionally accept arguments which alter their behavior. These arguments often map directly to function arguments within a GraphQL serverâs implementation.
In this example, we want to query a specific user (requested via the id argument) and their profile picture of a specific size:
Example â 10 { user(id: 4) { id name profilePic(size: 100) } } Many arguments can exist for a given field:
Example â 11 { user(id: 4) { id name profilePic(width: 100, height: 50) } } Arguments are unordered
Arguments may be provided in any syntactic order and maintain identical semantic meaning.
These two queries are semantically identical:
Example â 12 { picture(width: 200, height: 100) } Example â 13 { picture(height: 100, width: 200) } 2.7Field Alias Alias Name: By default, the key in the response object will use the field name queried. However, you can define a different name by specifying an alias.
In this example, we can fetch two profile pictures of different sizes and ensure the resulting object will not have duplicate keys:
Example â 14 { user(id: 4) { id name smallPic: profilePic(size: 64) bigPic: profilePic(size: 1024) } } Which returns the result:
Example â 15 { "user": { "id": 4, "name": "Mark Zuckerberg", "smallPic": "https://cdn.site.io/pic-4-64.jpg", "bigPic": "https://cdn.site.io/pic-4-1024.jpg" } } Since the top level of a query is a field, it also can be given an alias:
Example â 16 { zuck: user(id: 4) { id name } } Returns the result:
Example â 17 { "zuck": { "id": 4, "name": "Mark Zuckerberg" } } A fieldâs response key is its alias if an alias is provided, and it is otherwise the fieldâs name.
2.8Fragments FragmentSpread ...FragmentNameDirectivesopt FragmentDefinition fragmentFragmentNameTypeConditionDirectivesoptSelectionSet FragmentName Nameon Fragments are the primary unit of composition in GraphQL.
Fragments allow for the reuse of common repeated selections of fields, reducing duplicated text in the document. Inline Fragments can be used directly within a selection to condition upon a type condition when querying against an interface or union.
For example, if we wanted to fetch some common information about mutual friends as well as friends of some user:
Example â 18 query noFragments { user(id: 4) { friends(first: 10) { id name profilePic(size: 50) } mutualFriends(first: 10) { id name profilePic(size: 50) } } } The repeated fields could be extracted into a fragment and composed by a parent fragment or query.
Example â 19 query withFragments { user(id: 4) { friends(first: 10) { ...friendFields } mutualFriends(first: 10) { ...friendFields } } }
fragment friendFields on User { id name profilePic(size: 50) } 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.
For example:
Example â 20 query withNestedFragments { user(id: 4) { friends(first: 10) { ...friendFields } mutualFriends(first: 10) { ...friendFields } } }
fragment friendFields on User { id name ...standardProfilePic }
fragment standardProfilePic on User { profilePic(size: 50) } The queries noFragments, withFragments, and withNestedFragments all produce the same response object.
2.8.1Type Conditions TypeCondition onNamedType Fragments must specify the type they apply to. In this example, friendFields can be used in the context of querying a User.
Fragments cannot be specified on any input value (scalar, enumeration, or input object).
Fragments can be specified on object types, interfaces, and unions.
Selections within fragments only return values when concrete type of the object it is operating on matches the type of the fragment.
For example in this query on the Facebook data model:
Example â 21 query FragmentTyping { profiles(handles: ["zuck", "cocacola"]) { handle ...userFragment ...pageFragment } }
fragment userFragment on User { friends { count } }
fragment pageFragment on Page { likers { count } } 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.
Example â 22 { "profiles": [ { "handle": "zuck", "friends": { "count" : 1234 } }, { "handle": "cocacola", "likers": { "count" : 90234512 } } ] } 2.8.2Inline Fragments InlineFragment ...TypeConditionoptDirectivesoptSelectionSet Fragments can be defined inline within a selection set. This is done to conditionally include 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.
Example â 23 query inlineFragmentTyping { profiles(handles: ["zuck", "cocacola"]) { handle ... on User { friends { count } } ... on Page { likers { count } } } } Inline fragments may also be used to apply a directive to a group of fields. If the TypeCondition is omitted, an inline fragment is considered to be of the same type as the enclosing context.
Example â 24 query inlineFragmentNoType($expandedInfo: Boolean) { user(handle: "zuck") { id name ... @include(if: $expandedInfo) { firstName lastName birthday } } } 2.9Input Values ValueConst ConstVariable IntValue FloatValue StringValue BooleanValue NullValue EnumValue ListValueConst ObjectValueConst Field and directive arguments accept input values of various literal primitives; input values can be scalars, enumeration values, lists, or input objects.
If not defined as constant (for example, in DefaultValue), input values can be specified as a variable. List and inputs objects may also contain variables (unless defined to be constant).
2.9.1Int Value IntValue IntegerPart IntegerPart NegativeSignopt0 NegativeSignoptNonZeroDigitDigitlistopt NegativeSign
Digit 0 1 2 3 4 5 6 7 8 9 NonZeroDigit Digit0 An Int number is specified without a decimal point or exponent (ex. 1).
2.9.2Float Value FloatValue IntegerPartFractionalPart IntegerPartExponentPart IntegerPartFractionalPartExponentPart FractionalPart .Digitlist ExponentPart ExponentIndicatorSignoptDigitlist ExponentIndicator e E Sign
A Float number includes either a decimal point (ex. 1.0) or an exponent (ex. 1e50) or both (ex. 6.0221413e23).
2.9.3Boolean Value BooleanValue true false The two keywords true and false represent the two boolean values.
2.9.4String Value StringValue "StringCharacterlistopt" """BlockStringCharacterlistopt""" StringCharacter SourceCharacter"\LineTerminator \uEscapedUnicode \EscapedCharacter EscapedUnicode /[0-9A-Fa-f]{4}/ EscapedCharacter " \ / b f n r t BlockStringCharacter SourceCharacter"""""" """ Strings are sequences of characters wrapped in doubleâquotes ("). (ex. "Hello World"). White space and other otherwiseâignored characters are significant within a string value.
Unicode characters are allowed within String value literals, however SourceCharacter must not contain some ASCII control characters so escape sequences must be used to represent these characters. Block Strings
Block strings are sequences of characters wrapped in tripleâquotes ("""). White space, line terminators, quote, and backslash characters may all be used unescaped to enable verbatim text. Characters must all be valid SourceCharacter.
Since block strings represent freeform text often used in indented positions, the string value semantics of a block string excludes uniform indentation and blank initial and trailing lines via BlockStringValue().
For example, the following operation containing a block string:
Example â 25 mutation { sendEmail(message: """ Hello, World!
Yours,
GraphQL.
""") } Is identical to the standard quoted string:
Example â 26 mutation { sendEmail(message: "Hello,\n World!\n\nYours,\n GraphQL.") } Since block string values strip leading and trailing empty lines, there is no single canonical printed block string for a given value. Because block strings typically represent freeform text, it is considered easier to read if they begin and end with an empty line.
Example â 27 """ This starts with and ends with an empty line, which makes it easier to read. """ Counter Example â 28 """This does not start with or end with any empty lines, which makes it a little harder to read.""" If nonâprintable ASCII characters are needed in a string value, a standard quoted string with appropriate escape sequences must be used instead of a block string. Semantics
StringValue"StringCharacterlistopt" Return the Unicode character sequence of all StringCharacter Unicode character values (which may be an empty sequence). StringCharacterSourceCharacter"\LineTerminator Return the character value of SourceCharacter. StringCharacter\uEscapedUnicode Return the character whose code unit value in the Unicode Basic Multilingual Plane is the 16âbit hexadecimal value EscapedUnicode. StringCharacter\EscapedCharacter Return the character value of EscapedCharacter according to the table below. Escaped Character Code Unit Value Character Name " U+0022 double quote \ U+005C reverse solidus (back slash) / U+002F solidus (forward slash) b U+0008 backspace f U+000C form feed n U+000A line feed (new line) r U+000D carriage return t U+0009 horizontal tab StringValue"""BlockStringCharacterlistopt""" Let rawValue be the Unicode character sequence of all BlockStringCharacter Unicode character values (which may be an empty sequence). Return the result of BlockStringValue(rawValue). BlockStringCharacterSourceCharacter"""""" Return the character value of SourceCharacter. BlockStringCharacter""" Return the character sequence """. BlockStringValue(rawValue) Let lines be the result of splitting rawValue by LineTerminator. Let commonIndent be null. For each line in lines: If line is the first item in lines, continue to the next line. Let length be the number of characters in line. Let indent be the number of leading consecutive WhiteSpace characters in line. If indent is less than length: If commonIndent is null or indent is less than commonIndent: Let commonIndent be indent. If commonIndent is not null: For each line in lines: If line is the first item in lines, continue to the next line. Remove commonIndent characters from the beginning of line. While the first item line in lines contains only WhiteSpace: Remove the first item from lines. While the last item line in lines contains only WhiteSpace: Remove the last item from lines. Let formatted be the empty character sequence. For each line in lines: If line is the first item in lines: Append formatted with line. Otherwise: Append formatted with a line feed character (U+000A). Append formatted with line. Return formatted. 2.9.5Null Value NullValue null Null values are represented as the keyword null.
GraphQL has two semantically different ways to represent the lack of a value:
Explicitly providing the literal value: null. Implicitly not providing a value at all. For example, these two field calls are similar, but are not identical:
Example â 29 { field(arg: null) field } The first has explictly provided null to the argument âargâ, while the second has implicitly not provided a value to the argument âargâ. These two forms may be interpreted differently. For example, a mutation representing deleting a field vs not altering a field, respectively. Neither form may be used for an input expecting a NonâNull type.
The same two methods of representing the lack of a value are possible via variables by either providing the a variable value as null and not providing a variable value at all. 2.9.6Enum Value EnumValue Nametruefalsenull Enum values are represented 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 supply an enumeration type name in the literal.
2.9.7List Value ListValueConst [] [ValueConstlist] Lists are ordered sequences of values wrapped in squareâbrackets [ ]. The values of a List 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.
Semantics
ListValue[] Return a new empty list value. ListValue[Valuelist] Let inputList be a new empty list value. For each Valuelist Let value be the result of evaluating Value. Append value to inputList. Return inputList 2.9.8Input Object Values ObjectValueConst {} {ObjectFieldConstlist} ObjectFieldConst Name:ValueConst Input object literal values are unordered lists of keyed input values wrapped in curlyâbraces { }. The values of an object literal may be any input value literal or variable (ex. { name: "Hello world", score: 1.0 }). We refer to literal representation of input objects as âobject literals.â
Input object fields are unordered
Input object fields may be provided in any syntactic order and maintain identical semantic meaning.
These two queries are semantically identical:
Example â 30 { nearestThing(location: { lon: 12.43, lat: -53.211 }) } Example â 31 { nearestThing(location: { lat: -53.211, lon: 12.43 }) } Semantics
ObjectValue{} Return a new input object value with no fields. ObjectValue{ObjectFieldlist} Let inputObject be a new input object value with no fields. For each field in ObjectFieldlist Let name be Name in field. Let value be the result of evaluating Value in field. Add a field to inputObject of name name containing value value. Return inputObject 2.10Variables Variable $Name VariableDefinitions (VariableDefinitionlist) VariableDefinition Variable:TypeDefaultValueopt DefaultValue =ValueConst A GraphQL query can be parameterized with variables, maximizing query reuse, and avoiding costly string building in clients at runtime.
If not defined as constant (for example, in DefaultValue), a Variable can be supplied for an input value.
Variables must be defined at the top of an operation and are in scope throughout the execution of that operation.
In this example, we want to fetch a profile picture size based on the size of a particular device:
Example â 32 query getZuckProfile($devicePicSize: Int) { user(id: 4) { id name profilePic(size: $devicePicSize) } } Values for those variables are provided to a GraphQL service along with a request 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 width:
Example â 33 { "devicePicSize": 60 } Variable use within Fragments
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 a variable is referenced in a fragment and is included by an operation that does not define that variable, the operation cannot be executed.
2.11Type References Type NamedType ListType NonNullType NamedType Name ListType [Type] NonNullType NamedType! ListType! GraphQL describes the types of data expected by query variables. Input types may be lists of another input type, or a nonânull variant of any other input type.
Semantics
TypeName Let name be the string value of Name Let type be the type defined in the Schema named name type must not be null Return type Type[Type] Let itemType be the result of evaluating Type Let type be a List type where itemType is the contained type. Return type TypeType! Let nullableType be the result of evaluating Type Let type be a NonâNull type where nullableType is the contained type. Return type 2.12Directives DirectivesConst DirectiveConstlist DirectiveConst @NameArgumentsConstopt Directives provide a way to describe alternate runtime execution and type validation behavior in a GraphQL document.
In some cases, you need to provide options to alter GraphQLâs execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.
Directives have a name along with a list of arguments which may accept values of any input type.
Directives can be used to describe additional information for types, fields, fragments and operations.
As future versions of GraphQL adopt new configurable execution capabilities, they may be exposed via directives.
3Type System 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.
TypeSystemDefinition SchemaDefinition TypeDefinition DirectiveDefinition The GraphQL language includes an IDL used to describe a GraphQL serviceâs type system. Tools may use this definition language to provide utilities such as client code generation or service bootâstrapping.
GraphQL tools which only seek to provide GraphQL query execution may choose not to parse TypeSystemDefinition.
A GraphQL Document which contains TypeSystemDefinition must not be executed; GraphQL execution services which receive a GraphQL Document containing type system definitions should return a descriptive error.
The type system definition language is used throughout the remainder of this specification document when illustrating example type systems. 3.1Type System Extensions TypeSystemExtension SchemaExtension TypeExtension Type system extensions are used to represent a GraphQL type system which has been extended from some original type system. For example, this might be used by a local service to represent data a GraphQL client only accesses locally, or by a GraphQL service which is itself an extension of another GraphQL service.
3.2Schema SchemaDefinition schemaDirectivesConstopt{RootOperationTypeDefinitionlist} RootOperationTypeDefinition OperationType:NamedType A GraphQL serviceâs collective type system capabilities are referred to as that serviceâs âschemaâ. A schema is defined in terms of the types and directives it supports as well as the root operation types for each kind of operation: query, mutation, and subscription; this determines the place in the type system where those operations begin.
A GraphQL schema must itself be internally valid. This section describes the rules for this validation process where relevant.
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.
All types and directives defined within a schema must not have a name which begins with "__" (two underscores), as this is used exclusively by GraphQLâs introspection system.
3.2.1Root Operation Types A schema defines the initial root operation type for each kind of operation it supports: query, mutation, and subscription; this determines the place in the type system where those operations begin.
The query root operation type must be provided and must be an Object type.
The mutation root operation type is optional; if it is not provided, the service does not support mutations. If it is provided, it must be an Object type.
Similarly, the subscription root operation type is also optional; if it is not provided, the service does not support subscriptions. If it is provided, it must be an Object type.
The fields on the query root operation type indicate what fields are available at the top level of a GraphQL query. For example, a basic GraphQL query like:
Example â 34 query { myName } Is valid when the query root operation type has a field named âmyNameâ.
Example â 35 type Query { myName: String } Similarly, the following mutation is valid if a mutation root operation type has a field named âsetNameâ. Note that the query and mutation root types must be different types.
Example â 36 mutation { setName(name: "Zuck") { newName } } When using the type system definition language, a document must include at most one schema definition.
In this example, a GraphQL schema is defined with both query and mutation root types:
Example â 37 schema { query: MyQueryRootType mutation: MyMutationRootType }
type MyQueryRootType { someField: String }
type MyMutationRootType { setSomeField(to: String): String } Default Root Operation Type Names
While any type can be the root operation type for a GraphQL operation, the type system definition language can omit the schema definition when the query, mutation, and subscription root types are named Query, Mutation, and Subscription respectively.
Likewise, when representing a GraphQL schema using the type system definition language, a schema definition should be omitted if it only uses the default root operation type names.
This example describes a valid complete GraphQL schema, despite not explicitly including a schema definition. The Query type is presumed to be the query root operation type of the schema.
Example â 38 type Query { someField: String } 3.2.2Schema Extension SchemaExtension extendschemaDirectivesConstopt{OperationTypeDefinitionlist} extendschemaDirectivesConst Schema extensions are used to represent a schema which has been extended from an original schema. For example, this might be used by a GraphQL service which adds additional operation types, or additional directives to an existing schema.
Schema Validation
Schema extensions have the potential to be invalid if incorrectly defined.
The Schema must already be defined. Any directives provided must not already apply to the original Schema. 3.3Descriptions Description StringValue Documentation is firstâclass feature of GraphQL type systems. To ensure the documentation of a GraphQL service remains consistent with its capabilities, descriptions of GraphQL definitions are provided alongside their definitions and made available via introspection.
To allow GraphQL service designers to easily publish documentation alongside the capabilities of a GraphQL service, GraphQL descriptions are defined using the Markdown syntax (as specified by CommonMark). In the type system definition language, these description strings (often BlockString) occur immediately before the definition they describe.
All GraphQL types, fields, arguments and other definitions which can be described should provide a Description unless they are considered self descriptive.
As an example, this simple GraphQL schema is well described:
Example â 39
"""
A simple GraphQL schema which is well described.
"""
type Query {
"""
Translates a string from a given language into a different language.
"""
translate(
"The original language that text is provided in."
fromLanguage: Language
"The translated language to be returned."
toLanguage: Language
"The text to be translated."
text: String
): String }
"""
The set of languages supported by translate.
"""
enum Language {
"English"
EN
"French" FR
"Chinese" CH } 3.4Types TypeDefinition ScalarTypeDefinition ObjectTypeDefinition InterfaceTypeDefinition UnionTypeDefinition EnumTypeDefinition InputObjectTypeDefinition The fundamental unit of any GraphQL Schema is the type. There are six kinds of named type definitions in GraphQL, and two wrapping types.
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 implementing 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.
Finally, oftentimes it is useful to provide complex structs as inputs to GraphQL field arguments or variables; the Input Object type allows the schema to define exactly what data is expected.
3.4.1Wrapping Types 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.
A GraphQL schema may describe that a field represents list of another 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 resulting value will never be null (and that an error cannot result in a null value).
These two types are referred to as âwrapping typesâ; nonâwrapping types are referred to as ânamed typesâ. A wrapping type has an underlying named type, found by continually unwrapping the type until a named type is found.
3.4.2Input and Output Types Types are used throughout GraphQL to describe both the values accepted as input to arguments and variables as well as the values output by fields. These two uses categorize types as input types and output types. Some kinds of types, like Scalar and Enum types, can be used as both input types and output types; other kinds types can only be used in one or the other. Input Object types can only be used as input types. Object, Interface, and Union types can only be used as output types. Lists and NonâNull types may be used as input types or output types depending on how the wrapped type may be used.
IsInputType(type) If type is a List type or NonâNull type: Let unwrappedType be the unwrapped type of type. Return IsInputType(unwrappedType) If type is a Scalar, Enum, or Input Object type: Return true Return false IsOutputType(type) If type is a List type or NonâNull type: Let unwrappedType be the unwrapped type of type. Return IsOutputType(unwrappedType) If type is a Scalar, Object, Interface, Union, or Enum type: Return true Return false 3.4.3Type Extensions TypeExtension ScalarTypeExtension ObjectTypeExtension InterfaceTypeExtension UnionTypeExtension EnumTypeExtension InputObjectTypeExtension Type extensions are used to represent a GraphQL type which has been extended from some original type. For example, this might be used by a local service to represent additional fields a GraphQL client only accesses locally.
3.5Scalars ScalarTypeDefinition DescriptionoptscalarNameDirectivesConstopt Scalar types represent primitive leaf values in a GraphQL type system. GraphQL responses take the form of a hierarchical 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.
Example â 40 scalar Time scalar Url A server may omit any of the builtâin scalars from its schema, for example if a schema does not refer to a floatingâpoint number, then it must not include the Float type. However, if a schema includes a type with the name of one of the types described here, it must adhere to the behavior described. As an example, a server must not include a type called Int and use it to represent 128âbit numbers, internationalization information, or anything other than what is defined in this document.
When representing a GraphQL schema using the type system definition language, the builtâin scalar types should be omitted for brevity.
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 a field error if a value cannot be coerced or if coercion may result in data loss.
A GraphQL service may decide to allow coercing different internal types to the expected return type. For example when coercing a field of type Int a boolean true value may produce 1 or a string value "123" may be parsed as baseâ10 123. However if internal type coercion cannot be reasonably performed without losing information, then it must raise a 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 an 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 interpreted as an integer input value if they have an empty fractional part (ex. 1.0) and otherwise as floatingâpoint input value.
For all types below, with the exception of NonâNull, if the explicit value null is provided, then the result of input coercion is null.
Builtâin Scalars
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.
3.5.1Int The Int scalar type represents a signed 32âbit numeric nonâfractional value. Response formats that support a 32âbit integer or a number type should use that type to represent this scalar.
Result Coercion
Fields returning the type Int expect to encounter 32âbit integer internal values.
GraphQL servers may coerce nonâinteger internal values to integers when reasonable without losing information, otherwise they must raise a field error. Examples of this may include returning 1 for the floatingâpoint number 1.0, or returning 123 for the string "123". In scenarios where coercion may lose data, raising a field error is more appropriate. For example, a floatingâpoint number 1.2 should raise a field error instead of being truncated to 1.
If the integer internal value represents a value less than -231 or greater than or equal to 231, a field error should be raised.
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. 3.5.2Float 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
Fields returning the type Float expect to encounter doubleâprecision floatingâpoint internal values.
GraphQL servers may coerce nonâfloatingâpoint internal values to Float when reasonable without losing information, otherwise they must raise a field error. Examples of this may include returning 1.0 for the integer number 1, or 123.0 for the string "123".
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.
3.5.3String 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
Fields returning the type String expect to encounter UTFâ8 string internal values.
GraphQL servers may coerce nonâstring raw values to String when reasonable without losing information, 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.
3.5.4Boolean The Boolean scalar type represents true or false. Response formats should use a builtâin boolean type if supported; otherwise, they should use their representation of the integers 1 and 0.
Result Coercion
Fields returning the type Boolean expect to encounter boolean internal values.
GraphQL servers may coerce nonâboolean raw values to Boolean when reasonable without losing information, otherwise they must raise a field error. Examples of this may include returning true for nonâzero numbers.
Input Coercion
When expected as an input type, only boolean input values are accepted. All other input values must raise a query error indicating an incorrect type.
3.5.5ID The ID scalar type represents a unique identifier, often used to refetch an object or as the 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.
3.5.6Scalar Extensions ScalarTypeExtension extendscalarNameDirectivesConst Scalar type extensions are used to represent a scalar type which has been extended from some original scalar type. For example, this might be used by a GraphQL tool or service which adds directives to an existing scalar.
Type Validation
Scalar type extensions have the potential to be invalid if incorrectly defined.
The named type must already be defined and must be a Scalar type. Any directives provided must not already apply to the original Scalar type. 3.6Objects ObjectTypeDefinition DescriptionopttypeNameImplementsInterfacesoptDirectivesConstoptFieldsDefinitionopt ImplementsInterfaces implements&optNamedType ImplementsInterfaces&NamedType FieldsDefinition {FieldDefinitionlist} FieldDefinition DescriptionoptNameArgumentsDefinitionopt:TypeDirectivesConstopt GraphQL queries are hierarchical and composed, describing a tree of information. While Scalar types describe the leaf values of these hierarchical 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 should be serialized as ordered maps, where the queried field names (or aliases) are the keys and the result of evaluating the field is the value, ordered by the order in which they appear in the query.
All fields defined within an Object type must not have a name which begins with "__" (two underscores), as this is used exclusively by GraphQLâs introspection system.
For example, a type Person could be described as:
Example â 41 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 is 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 ordered map containing exactly the subset of the object queried, which should be represented in the order in which they were queried. Only fields that are declared on the object type may validly be queried on that object.
For example, selecting all the fields of Person:
Example â 42 { name age picture } Would yield the object:
Example â 43 { "name": "Mark Zuckerberg", "age": 30, "picture": "http://some.cdn/picture.jpg" } While selecting a subset of fields:
Example â 44 { age name } Must only yield exactly that subset:
Example â 45 { "age": 30, "name": "Mark Zuckerberg" } A field of an Object type may be a Scalar, Enum, another Object type, an Interface, or a Union. Additionally, it may be any wrapping type whose underlying base type is one of those five.
For example, the Person type might include a relationship:
Example â 46 type Person { name: String age: Int picture: Url relationship: Person } Valid queries must supply a nested field set for a field that returns an object, so this query is not valid:
Counter Example â 47 { name relationship } However, this example is valid:
Example â 48 { name relationship { name } } And will yield the subset of each object type queried:
Example â 49 { "name": "Mark Zuckerberg", "relationship": { "name": "Priscilla Chan" } } Field Ordering
When querying an Object, the resulting mapping of fields are conceptually ordered in the same order in which they were encountered during query execution, excluding fragments for which the type does not apply and fields or fragments that are skipped via @skip or @include directives. This ordering is correctly produced when using the CollectFields() algorithm.
Response serialization formats capable of representing ordered maps should maintain this ordering. Serialization formats which can only represent unordered maps (such as JSON) should retain this order textually. That is, if two fields {foo, bar} were queried in that order, the resulting JSON serialization should contain {"foo": "...", "bar": "..."} in the same order.
Producing a response where fields are represented in the same order in which they appear in the request improves human readability during debugging and enables more efficient parsing of responses if the order of properties can be anticipated.
If a fragment is spread before other fields, the fields that fragment specifies occur in the response before the following fields.
Example â 50 { foo ...Frag qux }
fragment Frag on Query { bar baz } Produces the ordered result:
Example â 51 { "foo": 1, "bar": 2, "baz": 3, "qux": 4 } If a field is queried multiple times in a selection, it is ordered by the first time it is encountered. However fragments for which the type does not apply does not affect ordering.
Example â 52 { foo ...Ignored ...Matching bar }
fragment Ignored on UnknownType { qux baz }
fragment Matching on Query { bar qux foo } Produces the ordered result:
Example â 53 { "foo": 1, "bar": 2, "qux": 3 } Also, if directives result in fields being excluded, they are not considered in the ordering of fields.
Example â 54 { foo @skip(if: true) bar foo } Produces the ordered result:
Example â 55 { "bar": 1, "foo": 2 } Result Coercion
Determining the result of coercing an object is the heart of the GraphQL executor, so this is covered in that section of the spec.
Input Coercion
Objects are never valid inputs.
Type Validation
Object types have the potential to be invalid if incorrectly defined. This set of rules must be adhered to by every Object type in a GraphQL schema.
An Object type must define one or more fields. For each field of an Object type: The field must have a unique name within that Object type; no two fields may share the same name. The field must not have a name which begins with the characters "" (two underscores). The field must return a type where IsOutputType(fieldType) returns true. For each argument of the field: The argument must not have a name which begins with the characters "" (two underscores). The argument must accept a type where IsInputType(argumentType) returns true. An object type may declare that it implements one or more unique interfaces. An object type must be a superâset of all interfaces it implements: The object type must include a field of the same name for every field defined in an interface. The object field must be of a type which is equal to or a subâtype of the interface field (covariant). An object field type is a valid subâtype if it is equal to (the same type as) the interface field type. An object field type is a valid subâtype if it is an Object type and the interface field type is either an Interface type or a Union type and the object field type is a possible type of the interface field type. An object field type is a valid subâtype if it is a List type and the interface field type is also a List type and the listâitem type of the object field type is a valid subâtype of the listâitem type of the interface field type. An object field type is a valid subâtype if it is a NonâNull variant of a valid subâtype of the interface field type. The object field must include an argument of the same name for every argument defined in the interface field. The object field argument must accept the same type (invariant) as the interface field argument. The object field may include additional arguments not defined in the interface field, but any additional argument must not be required, e.g. must not be of a nonânullable type. 3.6.1Field Arguments ArgumentsDefinition (InputValueDefinitionlist) InputValueDefinition DescriptionoptName:TypeDefaultValueoptDirectivesConstopt Object fields are conceptually functions which yield values. Occasionally object fields can accept arguments to further specify the return value. Object field arguments are defined as a list of all possible argument names and their expected input types.
All arguments defined within a field must not have a name which begins with "__" (two underscores), as this is used exclusively by GraphQLâs introspection system.
For example, a Person type with a picture field could accept an argument to determine what size of an image to return.
Example â 56 type Person { name: String picture(size: Int): Url } GraphQL queries can optionally specify arguments to their fields to provide these arguments.
This example query:
Example â 57 { name picture(size: 600) } May yield the result:
Example â 58 { "name": "Mark Zuckerberg", "picture": "http://some.cdn/picture_600.jpg" } The type of an object field argument must be an input type (any type except an Object, Interface, or Union type).
3.6.2Field Deprecation 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.
When using the type system definition language, @deprecated directives are used to indicate that a field is deprecated:
Example â 59 type ExampleType { oldField: String @deprecated } 3.6.3Object Extensions ObjectTypeExtension extendtypeNameImplementsInterfacesoptDirectivesConstoptFieldsDefinition extendtypeNameImplementsInterfacesoptDirectivesConst extendtypeNameImplementsInterfaces Object type extensions are used to represent a type which has been extended from some original type. For example, this might be used to represent local data, or by a GraphQL service which is itself an extension of another GraphQL service.
In this example, a local data field is added to a Story type:
Example â 60 extend type Story { isHiddenLocally: Boolean } Object type extensions may choose not to add additional fields, instead only adding interfaces or directives.
In this example, a directive is added to a User type without adding fields:
Example â 61 extend type User @addedDirective Type Validation
Object type extensions have the potential to be invalid if incorrectly defined.
The named type must already be defined and must be an Object type. The fields of an Object type extension must have unique names; no two fields may share the same name. Any fields of an Object type extension must not be already defined on the original Object type. Any directives provided must not already apply to the original Object type. Any interfaces provided must not be already implemented by the original Object type. The resulting extended object type must be a superâset of all interfaces it implements. 3.7Interfaces InterfaceTypeDefinition DescriptionoptinterfaceNameDirectivesConstoptFieldsDefinitionopt GraphQL interfaces represent a list of named fields and their arguments. GraphQL objects can then implement these interfaces which requires that the object type will define all fields defined by those interfaces.
Fields on a GraphQL interface have the same rules as fields on a GraphQL object; their type can be Scalar, Object, Enum, Interface, or Union, or any wrapping type whose base type is one of those five.
For example, an interface NamedEntity may describe a required field and types such as Person or Business may then implement this interface to guarantee this field will always exist.
Types may also implement multiple interfaces. For example, Business implements both the NamedEntity and ValuedEntity interfaces in the example below.
Example â 62 interface NamedEntity { name: String }
interface ValuedEntity { value: Int }
type Person implements NamedEntity { name: String age: Int }
type Business implements NamedEntity & ValuedEntity { name: String value: Int employeeCount: Int } Fields which yield an interface are useful when one of many Object types are expected, but some fields should be guaranteed.
To continue the example, a Contact might refer to NamedEntity.
Example â 63 type Contact { entity: NamedEntity phoneNumber: String address: String } This allows us to write a query for a Contact that can select the common fields.
Example â 64 { 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:
Counter Example â 65 { 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:
Example â 66 { entity { name ... on Person { 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.
Input Coercion
Interfaces are never valid inputs.
Type Validation
Interface types have the potential to be invalid if incorrectly defined.
An Interface type must define one or more fields. For each field of an Interface type: The field must have a unique name within that Interface type; no two fields may share the same name. The field must not have a name which begins with the characters "" (two underscores). The field must return a type where IsOutputType(fieldType) returns true. For each argument of the field: The argument must not have a name which begins with the characters "" (two underscores). The argument must accept a type where IsInputType(argumentType) returns true. 3.7.1Interface Extensions InterfaceTypeExtension extendinterfaceNameDirectivesConstoptFieldsDefinition extendinterfaceNameDirectivesConst Interface type extensions are used to represent an interface which has been extended from some original interface. For example, this might be used to represent common local data on many types, or by a GraphQL service which is itself an extension of another GraphQL service.
In this example, an extended data field is added to a NamedEntity type along with the types which implement it:
Example â 67 extend interface NamedEntity { nickname: String }
extend type Person { nickname: String }
extend type Business { nickname: String } Interface type extensions may choose not to add additional fields, instead only adding directives.
In this example, a directive is added to a NamedEntity type without adding fields:
Example â 68 extend interface NamedEntity @addedDirective Type Validation
Interface type extensions have the potential to be invalid if incorrectly defined.
The named type must already be defined and must be an Interface type. The fields of an Interface type extension must have unique names; no two fields may share the same name. Any fields of an Interface type extension must not be already defined on the original Interface type. Any Object type which implemented the original Interface type must also be a superâset of the fields of the Interface type extension (which may be due to Object type extension). Any directives provided must not already apply to the original Interface type. 3.8Unions UnionTypeDefinition DescriptionoptunionNameDirectivesConstoptUnionMemberTypesopt UnionMemberTypes =|optNamedType UnionMemberTypes|NamedType 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 type refining fragments or inline fragments.
For example, we might define the following types:
Example â 69 union SearchResult = Photo | Person
type Person { name: String age: Int }
type Photo { height: Int width: Int }
type SearchQuery { firstSearchResult: SearchResult } 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 no fields:
Counter Example â 70 { firstSearchResult { name height } } Instead, the query would be:
Example â 71 { firstSearchResult { ... on Person { name } ... on Photo { height } } } Union members may be defined with an optional leading | character to aid formatting when representing a longer list of possible types:
Example â 72 union SearchResult = | Photo | Person Result Coercion
The union type should have some way of determining which object a given result corresponds to. Once it has done so, the result coercion of the union is the same as the result coercion of the object.
Input Coercion
Unions are never valid inputs.
Type Validation
Union types have the potential to be invalid if incorrectly defined.
A Union type must include one or more unique member types. The member types of a Union type must all be Object base types; Scalar, Interface and Union types must not be member types of a Union. Similarly, wrapping types must not be member types of a Union. 3.8.1Union Extensions UnionTypeExtension extendunionNameDirectivesConstoptUnionMemberTypes extendunionNameDirectivesConst Union type extensions are used to represent a union type which has been extended from some original union type. For example, this might be used to represent additional local data, or by a GraphQL service which is itself an extension of another GraphQL service.
Type Validation
Union type extensions have the potential to be invalid if incorrectly defined.
The named type must already be defined and must be a Union type. The member types of a Union type extension must all be Object base types; Scalar, Interface and Union types must not be member types of a Union. Similarly, wrapping types must not be member types of a Union. All member types of a Union type extension must be unique. All member types of a Union type extension must not already be a member of the original Union type. Any directives provided must not already apply to the original Union type. 3.9Enums EnumTypeDefinition DescriptionoptenumNameDirectivesConstoptEnumValuesDefinitionopt EnumValuesDefinition {EnumValueDefinitionlist} EnumValueDefinition DescriptionoptEnumValueDirectivesConstopt GraphQL Enum types, like scalar types, also represent leaf values in a GraphQL type system. However Enum types describe the set of possible values.
Enums are not references for a numeric value, but are unique values in their own right. They may serialize as a string: the name of the represented value.
In this example, an Enum type called Direction is defined:
Example â 73 enum Direction { NORTH EAST SOUTH WEST } 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 interpreted as the enum input value with the same name.
Type Validation
Enum types have the potential to be invalid if incorrectly defined.
An Enum type must define one or more unique enum values. 3.9.1Enum Extensions EnumTypeExtension extendenumNameDirectivesConstoptEnumValuesDefinition extendenumNameDirectivesConst Enum type extensions are used to represent an enum type which has been extended from some original enum type. For example, this might be used to represent additional local data, or by a GraphQL service which is itself an extension of another GraphQL service.
Type Validation
Enum type extensions have the potential to be invalid if incorrectly defined.
The named type must already be defined and must be an Enum type. All values of an Enum type extension must be unique. All values of an Enum type extension must not already be a value of the original Enum. Any directives provided must not already apply to the original Enum type. 3.10Input Objects InputObjectTypeDefinition DescriptionoptinputNameDirectivesConstoptInputFieldsDefinitionopt InputFieldsDefinition {InputValueDefinitionlist} Fields may accept arguments to configure their behavior. These inputs are often scalars or enums, but they sometimes need to represent more complex values.
A GraphQL 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.
In this example, an Input Object called Point2D describes x and y inputs:
Example â 74 input Point2D { x: Float y: Float } The GraphQL Object type (ObjectTypeDefinition) defined above is inappropriate for reâuse here, because Object types can contain fields that define arguments or contain 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. Result Coercion
An input object is never a valid result. Input Object types cannot be the return type of an Object or Interface field.
Input Coercion
The value for an input object should be an input object literal or an unordered map supplied by a variable, otherwise a query error must be thrown. In either case, the input object literal or unordered map must not contain any entries with names not defined by a field of this input object type, otherwise an error must be thrown.
The result of coercion is an unordered map with an entry for each field both defined by the input object type and for which a value exists. The resulting map is constructed with the following rules:
If no value is provided for a defined input object field and that field definition provides a default value, the default value should be used. If no default value is provided and the input object fieldâs type is nonânull, an error should be thrown. Otherwise, if the field is not required, then no entry is added to the coerced unordered map. If the value null was provided for an input object field, and the fieldâs type is not a nonânull type, an entry in the coerced unordered map is given the value null. In other words, there is a semantic difference between the explicitly provided value null versus having not provided a value. If a literal value is provided for an input object field, an entry in the coerced unordered map is given the result of coercing that value according to the input coercion rules for the type of that field. If a variable is provided for an input object field, the runtime value of that variable must be used. If the runtime value is null and the field type is nonânull, a field error must be thrown. If no runtime value is provided, the variable definitionâs default value should be used. If the variable definition does not provide a default value, the input object field definitionâs default value should be used. Following are examples of input coercion for an input object type with a String field a and a required (nonânull) Int! field b:
Example â 75 input ExampleInputObject { a: String b: Int! } Literal Value Variables Coerced Value { a: "abc", b: 123 } {} { a: "abc", b: 123 } { a: null, b: 123 } {} { a: null, b: 123 } { b: 123 } {} { b: 123 } { a: $var, b: 123 } { var: null } { a: null, b: 123 } { a: $var, b: 123 } {} { b: 123 } { b: $var } { var: 123 } { b: 123 } $var { var: { b: 123 } } { b: 123 } "abc123" {} Error: Incorrect value $var { var: "abc123" } } Error: Incorrect value { a: "abc", b: "123" } {} Error: Incorrect value for field b { a: "abc" } {} Error: Missing required field b { b: $var } {} Error: Missing required field b. $var { var: { a: "abc" } } Error: Missing required field b { a: "abc", b: null } {} Error: b must be nonânull. { b: $var } { var: null } Error: b must be nonânull. { b: 123, c: "xyz" } {} Error: Unexpected field c Type Validation
An Input Object type must define one or more input fields. For each input field of an Input Object type: The input field must have a unique name within that Input Object type; no two input fields may share the same name. The input field must not have a name which begins with the characters "__" (two underscores). The input field must accept a type where IsInputType(inputFieldType) returns true. 3.10.1Input Object Extensions InputObjectTypeExtension extendinputNameDirectivesConstoptInputFieldsDefinition extendinputNameDirectivesConst Input object type extensions are used to represent an input object type which has been extended from some original input object type. For example, this might be used by a GraphQL service which is itself an extension of another GraphQL service.
Type Validation
Input object type extensions have the potential to be invalid if incorrectly defined.
The named type must already be defined and must be a Input Object type. All fields of an Input Object type extension must have unique names. All fields of an Input Object type extension must not already be a field of the original Input Object. Any directives provided must not already apply to the original Input Object type. 3.11List 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 list is serialized as per the item type. To denote that a field uses a List type the item type is wrapped in square brackets like this: pets: [Pet].
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 it 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.
If a listâs item type is nullable, then errors occuring during preparation or coercion of an individual item in the list must result in a the value null at that position in the list along with an error added to the response. If a listâs item type is nonânull, an error occuring at an individual item in the list must result in a field error for the entire list.
For more information on the error handling process, see âErrors and NonâNullabilityâ within the Execution section. Input Coercion
When expected as an input, list values are accepted only when each item in the list can be accepted by the listâs item type.
If the value passed as an input to a list type is not a list and not the null value, then the result of input coercion is a list of size one, where the single item value is the result of input coercion for the listâs item type on the provided value (note this may apply recursively for nested lists).
This allow inputs which accept one or many arguments (sometimes referred to as âvar argsâ) to declare their input type as a list while for the common case of a single value, a client can just pass that value directly rather than constructing the list.
Following are examples of input coercion with various list types and values:
Expected Type Provided Value Coerced Value [Int] [1, 2, 3] [1, 2, 3] [Int] [1, "b", true] Error: Incorrect item value [Int] 1 [1] [Int] null null [[Int]] [[1], [2, 3]] [[1], [2, 3] [[Int]] [1, 2, 3] Error: Incorrect item value [[Int]] 1 [[1]] [[Int]] null null 3.12Non-Null 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 wraps an underlying type, and this type acts identically to that wrapped type, with the exception that null is not a valid response for the wrapping type. A trailing exclamation mark is used to denote a field that uses a NonâNull type like this: name: String!.
Nullable vs. Optional
Fields are always optional within the context of a query, a field may be omitted and the query is still valid. However fields that return NonâNull types will never return the value null if queried.
Inputs (such as field arguments), are always optional by default. However a nonânull input type is required. In addition to not accepting the value null, it also does not accept omission. For the sake of simplicity nullable types are always optional and nonânull types are always required.
Result Coercion
In all of the above result coercions, null was considered a valid value. To coerce the result of a NonâNull type, the coercion of the wrapped 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 a field error must be raised.
When a field error is raised on a nonânull value, the error propogates to the parent field. For more information on this process, see âErrors and NonâNullabilityâ within the Execution section. Input Coercion
If an argument or inputâobject field of a NonâNull type is not provided, is provided with the literal value null, or is provided with a variable that was either not provided a value at runtime, or was provided the value null, then a query error must be raised.
If the value provided to the NonâNull type is provided with a literal value other than null, or a NonâNull variable value, it is coerced using the input coercion for the wrapped type.
A nonânull argument cannot be omitted:
Counter Example â 76 { fieldWithNonNullArg } The value null cannot be provided to a nonânull argument:
Counter Example â 77 { fieldWithNonNullArg(nonNullArg: null) } A variable of a nullable type cannot be provided to a nonânull argument:
Example â 78 query withNullableVariable($var: String) { fieldWithNonNullArg(nonNullArg: $var) } The Validation section defines providing a nullable variable type to a nonânull input type as invalid. Type Validation
A NonâNull type must not wrap another NonâNull type. 3.12.1Combining List and Non-Null The List and NonâNull wrapping types can compose, representing more complex types. The rules for result coercion and input coercion of Lists and NonâNull types apply in a recursive fashion.
For example if the inner item type of a List is NonâNull (e.g. [T!]), then that List may not contain any null items. However if the inner type of a NonâNull is a List (e.g. [T]!), then null is not accepted however an empty list is accepted.
Following are examples of result coercion with various types and values:
Expected Type Internal Value Coerced Result [Int] [1, 2, 3] [1, 2, 3] [Int] null null [Int] [1, 2, null] [1, 2, null] [Int] [1, 2, Error] [1, 2, null] (With logged error) [Int]! [1, 2, 3] [1, 2, 3] [Int]! null Error: Value cannot be null [Int]! [1, 2, null] [1, 2, null] [Int]! [1, 2, Error] [1, 2, null] (With logged error) [Int!] [1, 2, 3] [1, 2, 3] [Int!] null null [Int!] [1, 2, null] null (With logged coercion error) [Int!] [1, 2, Error] null (With logged error) [Int!]! [1, 2, 3] [1, 2, 3] [Int!]! null Error: Value cannot be null [Int!]! [1, 2, null] Error: Item cannot be null [Int!]! [1, 2, Error] Error: Error occurred in item 3.13Directives DirectiveDefinition Descriptionoptdirective@NameArgumentsDefinitionoptonDirectiveLocations DirectiveLocations |optDirectiveLocation DirectiveLocations|DirectiveLocation DirectiveLocation ExecutableDirectiveLocation TypeSystemDirectiveLocation ExecutableDirectiveLocation QUERY MUTATION SUBSCRIPTION FIELD FRAGMENT_DEFINITION FRAGMENT_SPREAD INLINE_FRAGMENT TypeSystemDirectiveLocation SCHEMA SCALAR OBJECT FIELD_DEFINITION ARGUMENT_DEFINITION INTERFACE UNION ENUM ENUM_VALUE INPUT_OBJECT INPUT_FIELD_DEFINITION A GraphQL schema describes directives which are used to annotate various parts of a GraphQL document as an indicator that they should be evaluated differently by a validator, executor, or client tool such as a code generator.
GraphQL implementations should provide the @skip and @include directives.
GraphQL implementations that support the type system definition language must provide the @deprecated directive if representing deprecated portions of the schema.
Directives must only be used in the locations they are declared to belong in. In this example, a directive is defined which can be used to annotate a fragment definition:
Example â 79 directive @example on FIELD
fragment SomeFragment on SomeType { field @example } Directive locations may be defined with an optional leading | character to aid formatting when representing a longer list of possible locations:
Example â 80 directive @example on | FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT Directives can also be used to annotate the type system definition language as well, which can be a useful tool for supplying additional metadata in order to generate GraphQL execution services, produce client generated runtime code, or many other useful extensions of the GraphQL semantics.
In this example, the directive @example annotates field and argument definitions:
Example â 81 directive @example on FIELD_DEFINITION | ARGUMENT_DEFINITION
type SomeType { field(arg: Int @example): String @example } While defining a directive, it must not reference itself directly or indirectly:
Counter Example â 82 directive @invalidExample(arg: String @invalidExample) on ARGUMENT_DEFINITION Validation
A directive definition must not contain the use of a directive which references itself directly. A directive definition must not contain the use of a directive which references itself indirectly by referencing a Type or Directive which transitively includes a reference to this directive. The directive must not have a name which begins with the characters "" (two underscores). For each argument of the directive: The argument must not have a name which begins with the characters "" (two underscores). The argument must accept a type where IsInputType(argumentType) returns true. 3.13.1@skip directive @skip(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT The @skip directive may be provided for fields, fragment spreads, and inline fragments, and allows for conditional exclusion during execution as described by the if argument.
In this example experimentalField will only be queried if the variable $someTest has the value false.
Example â 83 query myQuery($someTest: Boolean) { experimentalField @skip(if: $someTest) } 3.13.2@include directive @include(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT The @include directive may be provided for fields, fragment spreads, and inline fragments, and allows for conditional inclusion during execution as described by the if argument.
In this example experimentalField will only be queried if the variable $someTest has the value true
Example â 84 query myQuery($someTest: Boolean) { experimentalField @include(if: $someTest) } Neither @skip nor @include has precedence over the other. In the case that both the @skip and @include directives are provided in on the same the field or fragment, it must be queried only if the @skip condition is false and the @include condition is true. Stated conversely, the field or fragment must not be queried if either the @skip condition is true or the @include condition is false. 3.13.3@deprecated directive @deprecated( reason: String = "No longer supported" ) on FIELD_DEFINITION | ENUM_VALUE The @deprecated directive is used within the type system definition language to indicate deprecated portions of a GraphQL serviceâs schema, such as deprecated fields on a type or deprecated enum values.
Deprecations include a reason for why it is deprecated, which is formatted using Markdown syntax (as specified by CommonMark).
In this example type definition, oldField is deprecated in favor of using newField.
Example â 85
type ExampleType {
newField: String
oldField: String @deprecated(reason: "Use newField.")
}
4Introspection
A GraphQL server supports introspection over its schema. This schema is queried using GraphQL itself, creating a powerful platform for toolâbuilding.
Take an example query for a trivial app. In this case there is a User type with three fields: id, name, and birthday.
For example, given a server with the following type definition:
Example â 86 type User { id: String name: String birthday: Date } The query
Example â 87 { __type(name: "User") { name fields { name type { name } } } } would return
Example â 88 { "type": { "name": "User", "fields": [ { "name": "id", "type": { "name": "String" } }, { "name": "name", "type": { "name": "String" } }, { "name": "birthday", "type": { "name": "Date" } }, ] } } 4.1Reserved Names Types and fields required by the GraphQL introspection system that are used in the same context as userâdefined types 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.
4.2Documentation 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 (as specified by CommonMark). Therefore it is recommended that any tool that displays description use a CommonMarkâcompliant Markdown renderer.
4.3Deprecation 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.
4.4Type Name Introspection GraphQL supports type name introspection at any point within 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 queried.
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.
4.5Schema Introspection The schema introspection system is accessible from the metaâfields __schema and __type which are accessible from the type of the root of a query operation.
__schema: __Schema! __type(name: String!): __Type These fields are implicit and do not appear in the fields list in the root type of the query operation.
The schema of the GraphQL schema introspection system:
type __Schema { types: [__Type!]! queryType: __Type! mutationType: __Type subscriptionType: __Type directives: [__Directive!]! }
type __Type { kind: __TypeKind! name: String description: String
OBJECT and INTERFACE only
fields(includeDeprecated: Boolean = false): [__Field!]
OBJECT only
interfaces: [__Type!]
INTERFACE and UNION only
possibleTypes: [__Type!]
ENUM only
enumValues(includeDeprecated: Boolean = false): [__EnumValue!]
INPUT_OBJECT only
inputFields: [__InputValue!]
NON_NULL and LIST only
ofType: __Type }
type __Field { name: String! description: String args: [__InputValue!]! type: __Type! isDeprecated: Boolean! deprecationReason: String }
type __InputValue { name: String! description: String type: __Type! defaultValue: String }
type __EnumValue { name: String! description: String isDeprecated: Boolean! deprecationReason: String }
enum __TypeKind { SCALAR OBJECT INTERFACE UNION ENUM INPUT_OBJECT LIST NON_NULL }
type __Directive { name: String! description: String locations: [__DirectiveLocation!]! args: [__InputValue!]! }
enum __DirectiveLocation { QUERY MUTATION SUBSCRIPTION FIELD FRAGMENT_DEFINITION FRAGMENT_SPREAD INLINE_FRAGMENT SCHEMA SCALAR OBJECT FIELD_DEFINITION ARGUMENT_DEFINITION INTERFACE UNION ENUM ENUM_VALUE INPUT_OBJECT INPUT_FIELD_DEFINITION } 4.5.1The __Type Type __Type is at the core of the type introspection system. It represents scalars, interfaces, object types, unions, enums in the system.
__Type also represents type modifiers, which are used to modify a type that it refers to (ofType: __Type). This is how we represent lists, nonânullable types, and the combinations thereof.
4.5.2Type Kinds There are several different kinds of type. In each kind, different fields are actually valid. These kinds are listed in the __TypeKind enumeration.
4.5.2.1Scalar Represents scalar types such as Int, String, and Boolean. Scalars cannot have fields.
A GraphQL type designer should describe the data format and scalar coercion rules in the description field of any scalar.
Fields
kind must return __TypeKind.SCALAR. name must return a String. description may return a String or null. All other fields must return null. 4.5.2.2Object Object types represent concrete instantiations of sets of fields. The introspection types (e.g. __Type, __Field, etc) are examples of objects.
Fields=== compile output ===
can't load package: package main: main.go:1:1: expected 'package', found '==' main.go:3:4: rune literal not terminated
kind must return __TypeKind.OBJECT. name must return a String. description may return a String or null. fields: The set of fields queryâable on this type.âŚ/
``GraphQL June 2018 Edition BigDate La voz Dulcea
Introduction byŠ pelopedment
This is the specification for GraphQL, a query language and execution engine originally created at Facebook in 2012 for describing the capabilities and requirements of data models for clientâserver applications. The development of this open standard started in 2015.
GraphQL 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 facebook.github.io/graphql/draft/.
Copyright notice
Copyright Š 2015âpresent, Facebook, Inc.
As of September 26, 2017, the following persons or entities have made this Specification available under the Open Web Foundation Final Specification Agreement (OWFa 1.0), which is available at openwebfoundation.org.
Facebook, Inc. You can review the signed copies of the Open Web Foundation Final Specification Agreement Version 1.0 for this specification at github.com/facebook/graphql, which may also include additional parties to those listed above.
Your use of this Specification may be subject to other third party rights. THIS SPECIFICATION IS PROVIDED âAS IS.â The contributors 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 Specification. The entire risk as to implementing or otherwise using the Specification is assumed by the Specification implementer and user. IN NO EVENT WILL ANY PARTY 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 SPECIFICATION OR ITS GOVERNING AGREEMENT, WHETHER BASED ON BREACH OF CONTRACT, TORT (INCLUDING NEGLIGENCE), OR OTHERWISE, AND WHETHER OR NOT THE OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Conformance
A conforming implementation of GraphQL 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 may provide additional functionality, but must not where explicitly disallowed or would otherwise result in nonâconformance.
Conforming Algorithms
Algorithm steps phrased in imperative grammar (e.g. âReturn the result of calling resolverâ) are to be interpreted with the same level of requirement as the algorithm it is contained within. Any algorithm referenced within an algorithm step (e.g. âLet completedResult be the result of calling CompleteValue()â) is to be interpreted as having at least the same level of requirement as the algorithm containing that step.
Conformance requirements expressed as algorithms can be fulfilled by an implementation of this specification in any way as long as the perceived result is equivalent. Algorithms described in this document are written to be easy to understand. Implementers are encouraged to include equivalent but optimized implementations.
See Appendix A for more details about the definition of algorithms and other notational conventions used in this document.
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 â 1 This is an example of a non-normative example. Counter Example â 2 This 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:
This is an example of a nonânormative note. Contents 1Overview 2Language 2.1Source Text 2.1.1Unicode 2.1.2White Space 2.1.3Line Terminators 2.1.4Comments 2.1.5Insignificant Commas 2.1.6Lexical Tokens 2.1.7Ignored Tokens 2.1.8Punctuators 2.1.9Names 2.2Document 2.3Operations 2.4Selection Sets 2.5Fields 2.6Arguments 2.7Field Alias 2.8Fragments 2.8.1Type Conditions 2.8.2Inline Fragments 2.9Input Values 2.9.1Int Value 2.9.2Float Value 2.9.3Boolean Value 2.9.4String Value 2.9.5Null Value 2.9.6Enum Value 2.9.7List Value 2.9.8Input Object Values 2.10Variables 2.11Type References 2.12Directives 3Type System 3.1Type System Extensions 3.2Schema 3.2.1Root Operation Types 3.2.2Schema Extension 3.3Descriptions 3.4Types 3.4.1Wrapping Types 3.4.2Input and Output Types 3.4.3Type Extensions 3.5Scalars 3.5.1Int 3.5.2Float 3.5.3String 3.5.4Boolean 3.5.5ID 3.5.6Scalar Extensions 3.6Objects 3.6.1Field Arguments 3.6.2Field Deprecation 3.6.3Object Extensions 3.7Interfaces 3.7.1Interface Extensions 3.8Unions 3.8.1Union Extensions 3.9Enums 3.9.1Enum Extensions 3.10Input Objects 3.10.1Input Object Extensions 3.11List 3.12Non-Null 3.12.1Combining List and Non-Null 3.13Directives 3.13.1@skip 3.13.2@include 3.13.3@deprecated 4Introspection 4.1Reserved Names 4.2Documentation 4.3Deprecation 4.4Type Name Introspection 4.5Schema Introspection 4.5.1The __Type Type 4.5.2Type Kinds 4.5.2.1Scalar 4.5.2.2Object 4.5.2.3Union 4.5.2.4Interface 4.5.2.5Enum 4.5.2.6Input Object 4.5.2.7List 4.5.2.8Non-Null 4.5.3The __Field Type 4.5.4The __InputValue Type 4.5.5The __EnumValue Type 4.5.6The __Directive Type 5Validation 5.1Documents 5.1.1Executable Definitions 5.2Operations 5.2.1Named Operation Definitions 5.2.1.1Operation Name Uniqueness 5.2.2Anonymous Operation Definitions 5.2.2.1Lone Anonymous Operation 5.2.3Subscription Operation Definitions 5.2.3.1Single root field 5.3Fields 5.3.1Field Selections on Objects, Interfaces, and Unions Types 5.3.2Field Selection Merging 5.3.3Leaf Field Selections 5.4Arguments 5.4.1Argument Names 5.4.2Argument Uniqueness 5.4.2.1Required Arguments 5.5Fragments 5.5.1Fragment Declarations 5.5.1.1Fragment Name Uniqueness 5.5.1.2Fragment Spread Type Existence 5.5.1.3Fragments On Composite Types 5.5.1.4Fragments Must Be Used 5.5.2Fragment Spreads 5.5.2.1Fragment spread target defined 5.5.2.2Fragment spreads must not form cycles 5.5.2.3Fragment spread is possible 5.5.2.3.1Object Spreads In Object Scope 5.5.2.3.2Abstract Spreads in Object Scope 5.5.2.3.3Object Spreads In Abstract Scope 5.5.2.3.4Abstract Spreads in Abstract Scope 5.6Values 5.6.1Values of Correct Type 5.6.2Input Object Field Names 5.6.3Input Object Field Uniqueness 5.6.4Input Object Required Fields 5.7Directives 5.7.1Directives Are Defined 5.7.2Directives Are In Valid Locations 5.7.3Directives Are Unique Per Location 5.8Variables 5.8.1Variable Uniqueness 5.8.2Variables Are Input Types 5.8.3All Variable Uses Defined 5.8.4All Variables Used 5.8.5All Variable Usages are Allowed 6Execution 6.1Executing Requests 6.1.1Validating Requests 6.1.2Coercing Variable Values 6.2Executing Operations 6.2.1Query 6.2.2Mutation 6.2.3Subscription 6.2.3.1Source Stream 6.2.3.2Response Stream 6.2.3.3Unsubscribe 6.3Executing Selection Sets 6.3.1Normal and Serial Execution 6.3.2Field Collection 6.4Executing Fields 6.4.1Coercing Field Arguments 6.4.2Value Resolution 6.4.3Value Completion 6.4.4Errors and Non-Nullability 7Response 7.1Response Format 7.1.1Data 7.1.2Errors 7.2Serialization Format 7.2.1JSON Serialization 7.2.2Serialized Map Ordering AAppendix: Notation Conventions A.1Context-Free Grammar A.2Lexical and Syntactical Grammar A.3Grammar Notation A.4Grammar Semantics A.5Algorithms BAppendix: Grammar Summary B.1Ignored Tokens B.2Lexical Tokens B.3Document §Index 1Overview 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.
Example â 3 { user(id: 4) { name } } Which produces the resulting data (in JSON):
Example â 4 { "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:
Hierarchical: 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 builds 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.
2Language Clients use the GraphQL query language to make requests to a GraphQL service. We refer to these request sources as documents. A document may contain operations (queries, mutations, and subscriptions) as well as fragments, a common unit of composition allowing for query reuse.
A GraphQL document is defined as a syntactic grammar where terminal symbols are tokens (indivisible lexical units). These tokens are defined in a lexical grammar which matches patterns of source characters (defined by a doubleâcolon ::).
See Appendix A for more details about the definition of lexical and syntactic grammar and other notational conventions used in this document. 2.1Source Text SourceCharacter /[\u0009\u000A\u000D\u0020-\uFFFF]/ GraphQL documents are expressed as a sequence of Unicode characters. However, with few exceptions, most of GraphQL is expressed only in the original nonâcontrol ASCII range so as to be as widely compatible with as many existing tools, languages, and serialization formats as possible and avoid display issues in text editors and source control.
2.1.1Unicode UnicodeBOM Byte Order Mark (U+FEFF) NonâASCII Unicode characters may freely appear within StringValue and Comment portions of GraphQL.
The âByte Order Markâ is a special Unicode character which may appear at the beginning of a file containing Unicode which programs may use to determine the fact that the text stream is Unicode, what endianness the text stream is in, and which of several Unicode encodings to interpret.
2.1.2White Space WhiteSpace Horizontal Tab (U+0009) Space (U+0020) White space is used to improve legibility of source text and act as separation between tokens, and any amount of white space may appear before or after any token. White space between tokens is not significant to the semantic meaning of a GraphQL Document, however white space characters may appear within a String or Comment token.
GraphQL intentionally does not consider Unicode âZsâ category characters as whiteâspace, avoiding misinterpretation by text editors and source control tools. 2.1.3Line Terminators LineTerminator New Line (U+000A) Carriage Return (U+000D)New Line (U+000A) Carriage Return (U+000D)New Line (U+000A) Like white space, line terminators are used to improve the legibility of source text, any amount may appear before or after any other token and have no significance to the semantic meaning of a GraphQL Document. Line terminators are not found within any other token.
Any error reporting which provide the line number in the source of the offending syntax should use the preceding amount of LineTerminator to produce the line number. 2.1.4Comments Comment #CommentCharlistopt CommentChar SourceCharacterLineTerminator GraphQL source documents may contain singleâline comments, starting with the # marker.
A comment can contain any Unicode code point except LineTerminator so a comment always consists of all code points starting with the # character up to but not including the line terminator.
Comments behave like white space and may appear after any token, or before a line terminator, and have no significance to the semantic meaning of a GraphQL Document.
2.1.5Insignificant Commas Comma , Similar to white space and line terminators, commas (,) are used to improve the legibility of source text and separate lexical tokens but are otherwise syntactically and semantically insignificant within GraphQL Documents.
Nonâsignificant comma characters ensure that the absence or presence of a comma does not meaningfully alter the interpreted syntax of the document, as this can be a common userâerror in other languages. It also allows for the stylistic use of either trailing commas or lineâterminators as list delimiters which are both often desired for legibility and maintainability of source code.
2.1.6Lexical Tokens Token Punctuator Name IntValue FloatValue StringValue A GraphQL document is comprised of several kinds of indivisible lexical tokens defined here in a lexical grammar by patterns of source Unicode characters.
Tokens are later used as terminal symbols in a GraphQL Document syntactic grammars.
2.1.7Ignored Tokens Ignored UnicodeBOM WhiteSpace LineTerminator Comment Comma Before and after every lexical token may be any amount of ignored tokens including WhiteSpace and Comment. No ignored regions of a source document are significant, however ignored source characters may appear within a lexical token in a significant way, for example a String may contain white space characters.
No characters are ignored while parsing a given token, as an example no white space characters are permitted between the characters defining a FloatValue.
2.1.8Punctuators Punctuator ! $ ( ) ... : = @ [ ] { | } GraphQL documents include punctuation in order to describe structure. GraphQL is a data description language and not a programming language, therefore GraphQL lacks the punctuation often used to describe mathematical expressions.
2.1.9Names Name /[_A-Za-z][_0-9A-Za-z]*/ GraphQL Documents are full of named things: operations, fields, arguments, types, directives, fragments, and variables. All names must follow the same grammatical form.
Names in GraphQL are caseâsensitive. That is to say name, Name, and NAME all refer to different names. Underscores are significant, which means other_name and othername are two different names.
Names in GraphQL are limited to this ASCII subset of possible characters to support interoperation with as many other systems as possible.
2.2Document Document Definitionlist Definition ExecutableDefinition TypeSystemDefinition TypeSystemExtension ExecutableDefinition OperationDefinition FragmentDefinition A GraphQL Document describes a complete file or request string operated on by a GraphQL service or client. A document contains multiple definitions, either executable or representative of a GraphQL type system.
Documents are only executable by a GraphQL service if they contain an OperationDefinition and otherwise only contain ExecutableDefinition. However documents which do not contain OperationDefinition or do contain TypeSystemDefinition or TypeSystemExtension may still be parsed and validated to allow client tools to represent many GraphQL uses which may appear across many individual files.
If a Document contains only one operation, that operation may be unnamed or represented in the shorthand form, which omits both the query keyword and operation name. Otherwise, if a GraphQL Document contains multiple operations, each operation must be named. When submitting a Document with multiple operations to a GraphQL service, the name of the desired operation to be executed must also be provided.
GraphQL services which only seek to provide GraphQL query execution may choose to only include ExecutableDefinition and omit the TypeSystemDefinition and TypeSystemExtension rules from Definition.
2.3Operations OperationDefinition OperationTypeNameoptVariableDefinitionsoptDirectivesoptSelectionSet SelectionSet OperationType query mutation subscription There are three types of operations that GraphQL models:
query â a readâonly fetch. mutation â a write followed by a fetch. subscription â a longâlived request that fetches data in response to source events. Each operation is represented by an optional operation name and a selection set.
For example, this mutation operation might âlikeâ a story and then retrieve the new number of likes:
Example â 5 mutation { likeStory(storyID: 12345) { story { likeCount } } } Query shorthand
If a document contains only one query operation, and that query defines no variables and contains no directives, that operation may be represented in a shortâhand form which omits the query keyword and query name.
For example, this unnamed query operation is written via query shorthand.
Example â 6 { field } many examples below will use the query shortâhand syntax. 2.4Selection Sets SelectionSet {Selectionlist} Selection Field FragmentSpread InlineFragment An operation selects the set of information it needs, and will receive exactly that information and nothing more, avoiding overâfetching and underâfetching data.
Example â 7 { id firstName lastName } In this query, the id, firstName, and lastName fields form a selection set. Selection sets may also contain fragment references.
2.5Fields Field AliasoptNameArgumentsoptDirectivesoptSelectionSetopt A selection set is primarily composed of fields. A field describes one discrete piece of information available to request within a selection set.
Some fields describe complex data or relationships to other data. In order to further explore this data, a field may itself contain a selection set, allowing for deeply nested requests. All GraphQL operations must specify their selections down to fields which return scalar values to ensure an unambiguously shaped response.
For example, this operation selects fields of complex data and relationships down to scalar values.
Example â 8 { me { id firstName lastName birthday { month day } friends { name } } } Fields in the topâlevel selection set of an operation often represent some information that is globally accessible to your application and its current viewer. Some typical examples of these top fields include references to a current loggedâin viewer, or accessing certain types of data referenced by a unique identifier.
Example â 9
mecould represent the currently logged in viewer.{ me { name } }
userrepresents one of many users in a graph of data, referred to by aunique identifier.
{ user(id: 4) { name } } 2.6Arguments ArgumentsConst (ArgumentConstlist) ArgumentConst Name:ValueConst Fields are conceptually functions which return values, and occasionally accept arguments which alter their behavior. These arguments often map directly to function arguments within a GraphQL serverâs implementation.
In this example, we want to query a specific user (requested via the id argument) and their profile picture of a specific size:
Example â 10 { user(id: 4) { id name profilePic(size: 100) } } Many arguments can exist for a given field:
Example â 11 { user(id: 4) { id name profilePic(width: 100, height: 50) } } Arguments are unordered
Arguments may be provided in any syntactic order and maintain identical semantic meaning.
These two queries are semantically identical:
Example â 12 { picture(width: 200, height: 100) } Example â 13 { picture(height: 100, width: 200) } 2.7Field Alias Alias Name: By default, the key in the response object will use the field name queried. However, you can define a different name by specifying an alias.
In this example, we can fetch two profile pictures of different sizes and ensure the resulting object will not have duplicate keys:
Example â 14 { user(id: 4) { id name smallPic: profilePic(size: 64) bigPic: profilePic(size: 1024) } } Which returns the result:
Example â 15 { "user": { "id": 4, "name": "Mark Zuckerberg", "smallPic": "https://cdn.site.io/pic-4-64.jpg", "bigPic": "https://cdn.site.io/pic-4-1024.jpg" } } Since the top level of a query is a field, it also can be given an alias:
Example â 16 { zuck: user(id: 4) { id name } } Returns the result:
Example â 17 { "zuck": { "id": 4, "name": "Mark Zuckerberg" } } A fieldâs response key is its alias if an alias is provided, and it is otherwise the fieldâs name.
2.8Fragments FragmentSpread ...FragmentNameDirectivesopt FragmentDefinition fragmentFragmentNameTypeConditionDirectivesoptSelectionSet FragmentName Nameon Fragments are the primary unit of composition in GraphQL.
Fragments allow for the reuse of common repeated selections of fields, reducing duplicated text in the document. Inline Fragments can be used directly within a selection to condition upon a type condition when querying against an interface or union.
For example, if we wanted to fetch some common information about mutual friends as well as friends of some user:
Example â 18 query noFragments { user(id: 4) { friends(first: 10) { id name profilePic(size: 50) } mutualFriends(first: 10) { id name profilePic(size: 50) } } } The repeated fields could be extracted into a fragment and composed by a parent fragment or query.
Example â 19 query withFragments { user(id: 4) { friends(first: 10) { ...friendFields } mutualFriends(first: 10) { ...friendFields } } }
fragment friendFields on User { id name profilePic(size: 50) } 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.
For example:
Example â 20 query withNestedFragments { user(id: 4) { friends(first: 10) { ...friendFields } mutualFriends(first: 10) { ...friendFields } } }
fragment friendFields on User { id name ...standardProfilePic }
fragment standardProfilePic on User { profilePic(size: 50) } The queries noFragments, withFragments, and withNestedFragments all produce the same response object.
2.8.1Type Conditions TypeCondition onNamedType Fragments must specify the type they apply to. In this example, friendFields can be used in the context of querying a User.
Fragments cannot be specified on any input value (scalar, enumeration, or input object).
Fragments can be specified on object types, interfaces, and unions.
Selections within fragments only return values when concrete type of the object it is operating on matches the type of the fragment.
For example in this query on the Facebook data model:
Example â 21 query FragmentTyping { profiles(handles: ["zuck", "cocacola"]) { handle ...userFragment ...pageFragment } }
fragment userFragment on User { friends { count } }
fragment pageFragment on Page { likers { count } } 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.
Example â 22 { "profiles": [ { "handle": "zuck", "friends": { "count" : 1234 } }, { "handle": "cocacola", "likers": { "count" : 90234512 } } ] } 2.8.2Inline Fragments InlineFragment ...TypeConditionoptDirectivesoptSelectionSet Fragments can be defined inline within a selection set. This is done to conditionally include 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.
Example â 23 query inlineFragmentTyping { profiles(handles: ["zuck", "cocacola"]) { handle ... on User { friends { count } } ... on Page { likers { count } } } } Inline fragments may also be used to apply a directive to a group of fields. If the TypeCondition is omitted, an inline fragment is considered to be of the same type as the enclosing context.
Example â 24 query inlineFragmentNoType($expandedInfo: Boolean) { user(handle: "zuck") { id name ... @include(if: $expandedInfo) { firstName lastName birthday } } } 2.9Input Values ValueConst ConstVariable IntValue FloatValue StringValue BooleanValue NullValue EnumValue ListValueConst ObjectValueConst Field and directive arguments accept input values of various literal primitives; input values can be scalars, enumeration values, lists, or input objects.
If not defined as constant (for example, in DefaultValue), input values can be specified as a variable. List and inputs objects may also contain variables (unless defined to be constant).
2.9.1Int Value
IntValue IntegerPart IntegerPart NegativeSignopt0 NegativeSignoptNonZeroDigitDigitlistopt NegativeSign Digit 0 1 2 3 4 5 6 7 8 9 NonZeroDigit Digit0 An Int number is specified without a decimal point or exponent (ex. 1).
2.9.2Float Value FloatValue IntegerPartFractionalPart IntegerPartExponentPart IntegerPartFractionalPartExponentPart FractionalPart .Digitlist ExponentPart ExponentIndicatorSignoptDigitlist ExponentIndicator e E Sign
A Float number includes either a decimal point (ex. 1.0) or an exponent (ex. 1e50) or both (ex. 6.0221413e23).
2.9.3Boolean Value BooleanValue true false The two keywords true and false represent the two boolean values.
2.9.4String Value StringValue "StringCharacterlistopt" """BlockStringCharacterlistopt""" StringCharacter SourceCharacter"\LineTerminator \uEscapedUnicode \EscapedCharacter EscapedUnicode /[0-9A-Fa-f]{4}/ EscapedCharacter " \ / b f n r t BlockStringCharacter SourceCharacter"""""" """ Strings are sequences of characters wrapped in doubleâquotes ("). (ex. "Hello World"). White space and other otherwiseâignored characters are significant within a string value.
Unicode characters are allowed within String value literals, however SourceCharacter must not contain some ASCII control characters so escape sequences must be used to represent these characters. Block Strings
Block strings are sequences of characters wrapped in tripleâquotes ("""). White space, line terminators, quote, and backslash characters may all be used unescaped to enable verbatim text. Characters must all be valid SourceCharacter.
Since block strings represent freeform text often used in indented positions, the string value semantics of a block string excludes uniform indentation and blank initial and trailing lines via BlockStringValue().
For example, the following operation containing a block string:
Example â 25 mutation { sendEmail(message: """ Hello, World!
Yours, GraphQL.""") } Is identical to the standard quoted string:
Example â 26 mutation { sendEmail(message: "Hello,\n World!\n\nYours,\n GraphQL.") } Since block string values strip leading and trailing empty lines, there is no single canonical printed block string for a given value. Because block strings typically represent freeform text, it is considered easier to read if they begin and end with an empty line.
Example â 27 """ This starts with and ends with an empty line, which makes it easier to read. """ Counter Example â 28 """This does not start with or end with any empty lines, which makes it a little harder to read.""" If nonâprintable ASCII characters are needed in a string value, a standard quoted string with appropriate escape sequences must be used instead of a block string. Semantics
StringValue"StringCharacterlistopt" Return the Unicode character sequence of all StringCharacter Unicode character values (which may be an empty sequence). StringCharacterSourceCharacter"\LineTerminator Return the character value of SourceCharacter. StringCharacter\uEscapedUnicode Return the character whose code unit value in the Unicode Basic Multilingual Plane is the 16âbit hexadecimal value EscapedUnicode. StringCharacter\EscapedCharacter Return the character value of EscapedCharacter according to the table below. Escaped Character Code Unit Value Character Name " U+0022 double quote \ U+005C reverse solidus (back slash) / U+002F solidus (forward slash) b U+0008 backspace f U+000C form feed n U+000A line feed (new line) r U+000D carriage return t U+0009 horizontal tab StringValue"""BlockStringCharacterlistopt""" Let rawValue be the Unicode character sequence of all BlockStringCharacter Unicode character values (which may be an empty sequence). Return the result of BlockStringValue(rawValue). BlockStringCharacterSourceCharacter"""""" Return the character value of SourceCharacter. BlockStringCharacter""" Return the character sequence """. BlockStringValue(rawValue) Let lines be the result of splitting rawValue by LineTerminator. Let commonIndent be null. For each line in lines: If line is the first item in lines, continue to the next line. Let length be the number of characters in line. Let indent be the number of leading consecutive WhiteSpace characters in line. If indent is less than length: If commonIndent is null or indent is less than commonIndent: Let commonIndent be indent. If commonIndent is not null: For each line in lines: If line is the first item in lines, continue to the next line. Remove commonIndent characters from the beginning of line. While the first item line in lines contains only WhiteSpace: Remove the first item from lines. While the last item line in lines contains only WhiteSpace: Remove the last item from lines. Let formatted be the empty character sequence. For each line in lines: If line is the first item in lines: Append formatted with line. Otherwise: Append formatted with a line feed character (U+000A). Append formatted with line. Return formatted. 2.9.5Null Value NullValue null Null values are represented as the keyword null.
GraphQL has two semantically different ways to represent the lack of a value:
Explicitly providing the literal value: null. Implicitly not providing a value at all. For example, these two field calls are similar, but are not identical:
Example â 29 { field(arg: null) field } The first has explictly provided null to the argument âargâ, while the second has implicitly not provided a value to the argument âargâ. These two forms may be interpreted differently. For example, a mutation representing deleting a field vs not altering a field, respectively. Neither form may be used for an input expecting a NonâNull type.
The same two methods of representing the lack of a value are possible via variables by either providing the a variable value as null and not providing a variable value at all. 2.9.6Enum Value EnumValue Nametruefalsenull Enum values are represented 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 supply an enumeration type name in the literal.
2.9.7List Value ListValueConst [] [ValueConstlist] Lists are ordered sequences of values wrapped in squareâbrackets [ ]. The values of a List 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.
Semantics
ListValue[] Return a new empty list value. ListValue[Valuelist] Let inputList be a new empty list value. For each Valuelist Let value be the result of evaluating Value. Append value to inputList. Return inputList 2.9.8Input Object Values ObjectValueConst {} {ObjectFieldConstlist} ObjectFieldConst Name:ValueConst Input object literal values are unordered lists of keyed input values wrapped in curlyâbraces { }. The values of an object literal may be any input value literal or variable (ex. { name: "Hello world", score: 1.0 }). We refer to literal representation of input objects as âobject literals.â
Input object fields are unordered
Input object fields may be provided in any syntactic order and maintain identical semantic meaning.
These two queries are semantically identical:
Example â 30 { nearestThing(location: { lon: 12.43, lat: -53.211 }) } Example â 31 { nearestThing(location: { lat: -53.211, lon: 12.43 }) } Semantics
ObjectValue{} Return a new input object value with no fields. ObjectValue{ObjectFieldlist} Let inputObject be a new input object value with no fields. For each field in ObjectFieldlist Let name be Name in field. Let value be the result of evaluating Value in field. Add a field to inputObject of name name containing value value. Return inputObject 2.10Variables Variable $Name VariableDefinitions (VariableDefinitionlist) VariableDefinition Variable:TypeDefaultValueopt DefaultValue =ValueConst A GraphQL query can be parameterized with variables, maximizing query reuse, and avoiding costly string building in clients at runtime.
If not defined as constant (for example, in DefaultValue), a Variable can be supplied for an input value.
Variables must be defined at the top of an operation and are in scope throughout the execution of that operation.
In this example, we want to fetch a profile picture size based on the size of a particular device:
Example â 32 query getZuckProfile($devicePicSize: Int) { user(id: 4) { id name profilePic(size: $devicePicSize) } } Values for those variables are provided to a GraphQL service along with a request 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 width:
Example â 33 { "devicePicSize": 60 } Variable use within Fragments
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 a variable is referenced in a fragment and is included by an operation that does not define that variable, the operation cannot be executed.
2.11Type References Type NamedType ListType NonNullType NamedType Name ListType [Type] NonNullType NamedType! ListType! GraphQL describes the types of data expected by query variables. Input types may be lists of another input type, or a nonânull variant of any other input type.
Semantics
TypeName Let name be the string value of Name Let type be the type defined in the Schema named name type must not be null Return type Type[Type] Let itemType be the result of evaluating Type Let type be a List type where itemType is the contained type. Return type TypeType! Let nullableType be the result of evaluating Type Let type be a NonâNull type where nullableType is the contained type. Return type 2.12Directives DirectivesConst DirectiveConstlist DirectiveConst @NameArgumentsConstopt Directives provide a way to describe alternate runtime execution and type validation behavior in a GraphQL document.
In some cases, you need to provide options to alter GraphQLâs execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.
Directives have a name along with a list of arguments which may accept values of any input type.
Directives can be used to describe additional information for types, fields, fragments and operations.
As future versions of GraphQL adopt new configurable execution capabilities, they may be exposed via directives.
3Type System 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.
TypeSystemDefinition SchemaDefinition TypeDefinition DirectiveDefinition The GraphQL language includes an IDL used to describe a GraphQL serviceâs type system. Tools may use this definition language to provide utilities such as client code generation or service bootâstrapping.
GraphQL tools which only seek to provide GraphQL query execution may choose not to parse TypeSystemDefinition.
A GraphQL Document which contains TypeSystemDefinition must not be executed; GraphQL execution services which receive a GraphQL Document containing type system definitions should return a descriptive error.
The type system definition language is used throughout the remainder of this specification document when illustrating example type systems. 3.1Type System Extensions TypeSystemExtension SchemaExtension TypeExtension Type system extensions are used to represent a GraphQL type system which has been extended from some original type system. For example, this might be used by a local service to represent data a GraphQL client only accesses locally, or by a GraphQL service which is itself an extension of another GraphQL service.
3.2Schema SchemaDefinition schemaDirectivesConstopt{RootOperationTypeDefinitionlist} RootOperationTypeDefinition OperationType:NamedType A GraphQL serviceâs collective type system capabilities are referred to as that serviceâs âschemaâ. A schema is defined in terms of the types and directives it supports as well as the root operation types for each kind of operation: query, mutation, and subscription; this determines the place in the type system where those operations begin.
A GraphQL schema must itself be internally valid. This section describes the rules for this validation process where relevant.
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.
All types and directives defined within a schema must not have a name which begins with "__" (two underscores), as this is used exclusively by GraphQLâs introspection system.
3.2.1Root Operation Types A schema defines the initial root operation type for each kind of operation it supports: query, mutation, and subscription; this determines the place in the type system where those operations begin.
The query root operation type must be provided and must be an Object type.
The mutation root operation type is optional; if it is not provided, the service does not support mutations. If it is provided, it must be an Object type.
Similarly, the subscription root operation type is also optional; if it is not provided, the service does not support subscriptions. If it is provided, it must be an Object type.
The fields on the query root operation type indicate what fields are available at the top level of a GraphQL query. For example, a basic GraphQL query like:
Example â 34 query { myName } Is valid when the query root operation type has a field named âmyNameâ.
Example â 35 type Query { myName: String } Similarly, the following mutation is valid if a mutation root operation type has a field named âsetNameâ. Note that the query and mutation root types must be different types.
Example â 36 mutation { setName(name: "Zuck") { newName } } When using the type system definition language, a document must include at most one schema definition.
In this example, a GraphQL schema is defined with both query and mutation root types:
Example â 37 schema { query: MyQueryRootType mutation: MyMutationRootType }
type MyQueryRootType { someField: String }
type MyMutationRootType { setSomeField(to: String): String } Default Root Operation Type Names
While any type can be the root operation type for a GraphQL operation, the type system definition language can omit the schema definition when the query, mutation, and subscription root types are named Query, Mutation, and Subscription respectively.
Likewise, when representing a GraphQL schema using the type system definition language, a schema definition should be omitted if it only uses the default root operation type names.
This example describes a valid complete GraphQL schema, despite not explicitly including a schema definition. The Query type is presumed to be the query root operation type of the schema.
Example â 38 type Query { someField: String } 3.2.2Schema Extension SchemaExtension extendschemaDirectivesConstopt{OperationTypeDefinitionlist} extendschemaDirectivesConst Schema extensions are used to represent a schema which has been extended from an original schema. For example, this might be used by a GraphQL service which adds additional operation types, or additional directives to an existing schema.
Schema Validation
Schema extensions have the potential to be invalid if incorrectly defined.
The Schema must already be defined. Any directives provided must not already apply to the original Schema. 3.3Descriptions Description StringValue Documentation is firstâclass feature of GraphQL type systems. To ensure the documentation of a GraphQL service remains consistent with its capabilities, descriptions of GraphQL definitions are provided alongside their definitions and made available via introspection.
To allow GraphQL service designers to easily publish documentation alongside the capabilities of a GraphQL service, GraphQL descriptions are defined using the Markdown syntax (as specified by CommonMark). In the type system definition language, these description strings (often BlockString) occur immediately before the definition they describe.
All GraphQL types, fields, arguments and other definitions which can be described should provide a Description unless they are considered self descriptive.
As an example, this simple GraphQL schema is well described:
Example â 39 """ A simple GraphQL schema which is well described. """ type Query { """ Translates a string from a given language into a different language. """ translate( "The original language that
textis provided in." fromLanguage: Language"The translated language to be returned." toLanguage: Language "The text to be translated." text: String): String }
""" The set of languages supported by
translate. """ enum Language { "English" EN"French" FR
"Chinese" CH } 3.4Types TypeDefinition ScalarTypeDefinition ObjectTypeDefinition InterfaceTypeDefinition UnionTypeDefinition EnumTypeDefinition InputObjectTypeDefinition The fundamental unit of any GraphQL Schema is the type. There are six kinds of named type definitions in GraphQL, and two wrapping types.
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 implementing 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.
Finally, oftentimes it is useful to provide complex structs as inputs to GraphQL field arguments or variables; the Input Object type allows the schema to define exactly what data is expected.
3.4.1Wrapping Types 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.
A GraphQL schema may describe that a field represents list of another 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 resulting value will never be null (and that an error cannot result in a null value).
These two types are referred to as âwrapping typesâ; nonâwrapping types are referred to as ânamed typesâ. A wrapping type has an underlying named type, found by continually unwrapping the type until a named type is found.
3.4.2Input and Output Types Types are used throughout GraphQL to describe both the values accepted as input to arguments and variables as well as the values output by fields. These two uses categorize types as input types and output types. Some kinds of types, like Scalar and Enum types, can be used as both input types and output types; other kinds types can only be used in one or the other. Input Object types can only be used as input types. Object, Interface, and Union types can only be used as output types. Lists and NonâNull types may be used as input types or output types depending on how the wrapped type may be used.
IsInputType(type) If type is a List type or NonâNull type: Let unwrappedType be the unwrapped type of type. Return IsInputType(unwrappedType) If type is a Scalar, Enum, or Input Object type: Return true Return false IsOutputType(type) If type is a List type or NonâNull type: Let unwrappedType be the unwrapped type of type. Return IsOutputType(unwrappedType) If type is a Scalar, Object, Interface, Union, or Enum type: Return true Return false 3.4.3Type Extensions TypeExtension ScalarTypeExtension ObjectTypeExtension InterfaceTypeExtension UnionTypeExtension EnumTypeExtension InputObjectTypeExtension Type extensions are used to represent a GraphQL type which has been extended from some original type. For example, this might be used by a local service to represent additional fields a GraphQL client only accesses locally.
3.5Scalars ScalarTypeDefinition DescriptionoptscalarNameDirectivesConstopt Scalar types represent primitive leaf values in a GraphQL type system. GraphQL responses take the form of a hierarchical 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.
Example â 40 scalar Time scalar Url A server may omit any of the builtâin scalars from its schema, for example if a schema does not refer to a floatingâpoint number, then it must not include the Float type. However, if a schema includes a type with the name of one of the types described here, it must adhere to the behavior described. As an example, a server must not include a type called Int and use it to represent 128âbit numbers, internationalization information, or anything other than what is defined in this document.
When representing a GraphQL schema using the type system definition language, the builtâin scalar types should be omitted for brevity.
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 a field error if a value cannot be coerced or if coercion may result in data loss.
A GraphQL service may decide to allow coercing different internal types to the expected return type. For example when coercing a field of type Int a boolean true value may produce 1 or a string value "123" may be parsed as baseâ10 123. However if internal type coercion cannot be reasonably performed without losing information, then it must raise a 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 an 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 interpreted as an integer input value if they have an empty fractional part (ex. 1.0) and otherwise as floatingâpoint input value.
For all types below, with the exception of NonâNull, if the explicit value null is provided, then the result of input coercion is null.
Builtâin Scalars
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.
3.5.1Int The Int scalar type represents a signed 32âbit numeric nonâfractional value. Response formats that support a 32âbit integer or a number type should use that type to represent this scalar.
Result Coercion
Fields returning the type Int expect to encounter 32âbit integer internal values.
GraphQL servers may coerce nonâinteger internal values to integers when reasonable without losing information, otherwise they must raise a field error. Examples of this may include returning 1 for the floatingâpoint number 1.0, or returning 123 for the string "123". In scenarios where coercion may lose data, raising a field error is more appropriate. For example, a floatingâpoint number 1.2 should raise a field error instead of being truncated to 1.
If the integer internal value represents a value less than -231 or greater than or equal to 231, a field error should be raised.
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. 3.5.2Float 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
Fields returning the type Float expect to encounter doubleâprecision floatingâpoint internal values.
GraphQL servers may coerce nonâfloatingâpoint internal values to Float when reasonable without losing information, otherwise they must raise a field error. Examples of this may include returning 1.0 for the integer number 1, or 123.0 for the string "123".
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.
3.5.3String 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
Fields returning the type String expect to encounter UTFâ8 string internal values.
GraphQL servers may coerce nonâstring raw values to String when reasonable without losing information, 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.
3.5.4Boolean The Boolean scalar type represents true or false. Response formats should use a builtâin boolean type if supported; otherwise, they should use their representation of the integers 1 and 0.
Result Coercion
Fields returning the type Boolean expect to encounter boolean internal values.
GraphQL servers may coerce nonâboolean raw values to Boolean when reasonable without losing information, otherwise they must raise a field error. Examples of this may include returning true for nonâzero numbers.
Input Coercion
When expected as an input type, only boolean input values are accepted. All other input values must raise a query error indicating an incorrect type.
3.5.5ID The ID scalar type represents a unique identifier, often used to refetch an object or as the 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.
3.5.6Scalar Extensions ScalarTypeExtension extendscalarNameDirectivesConst Scalar type extensions are used to represent a scalar type which has been extended from some original scalar type. For example, this might be used by a GraphQL tool or service which adds directives to an existing scalar.
Type Validation
Scalar type extensions have the potential to be invalid if incorrectly defined.
The named type must already be defined and must be a Scalar type. Any directives provided must not already apply to the original Scalar type. 3.6Objects ObjectTypeDefinition DescriptionopttypeNameImplementsInterfacesoptDirectivesConstoptFieldsDefinitionopt ImplementsInterfaces implements&optNamedType ImplementsInterfaces&NamedType FieldsDefinition {FieldDefinitionlist} FieldDefinition DescriptionoptNameArgumentsDefinitionopt:TypeDirectivesConstopt GraphQL queries are hierarchical and composed, describing a tree of information. While Scalar types describe the leaf values of these hierarchical 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 should be serialized as ordered maps, where the queried field names (or aliases) are the keys and the result of evaluating the field is the value, ordered by the order in which they appear in the query.
All fields defined within an Object type must not have a name which begins with "__" (two underscores), as this is used exclusively by GraphQLâs introspection system.
For example, a type Person could be described as:
Example â 41 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 is 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 ordered map containing exactly the subset of the object queried, which should be represented in the order in which they were queried. Only fields that are declared on the object type may validly be queried on that object.
For example, selecting all the fields of Person:
Example â 42 { name age picture } Would yield the object:
Example â 43 { "name": "Mark Zuckerberg", "age": 30, "picture": "http://some.cdn/picture.jpg" } While selecting a subset of fields:
Example â 44 { age name } Must only yield exactly that subset:
Example â 45 { "age": 30, "name": "Mark Zuckerberg" } A field of an Object type may be a Scalar, Enum, another Object type, an Interface, or a Union. Additionally, it may be any wrapping type whose underlying base type is one of those five.
For example, the Person type might include a relationship:
Example â 46 type Person { name: String age: Int picture: Url relationship: Person } Valid queries must supply a nested field set for a field that returns an object, so this query is not valid:
Counter Example â 47 { name relationship } However, this example is valid:
Example â 48 { name relationship { name } } And will yield the subset of each object type queried:
Example â 49 { "name": "Mark Zuckerberg", "relationship": { "name": "Priscilla Chan" } } Field Ordering
When querying an Object, the resulting mapping of fields are conceptually ordered in the same order in which they were encountered during query execution, excluding fragments for which the type does not apply and fields or fragments that are skipped via @Skip or @include directives. This ordering is correctly produced when using the CollectFields() algorithm.
Response serialization formats capable of representing ordered maps should maintain this ordering. Serialization formats which can only represent unordered maps (such as JSON) should retain this order textually. That is, if two fields {foo, bar} were queried in that order, the resulting JSON serialization should contain {"foo": "...", "bar": "..."} in the same order.
Producing a response where fields are represented in the same order in which they appear in the request improves human readability during debugging and enables more efficient parsing of responses if the order of properties can be anticipated.
If a fragment is spread before other fields, the fields that fragment specifies occur in the response before the following fields.
Example â 50 { foo ...Frag qux }
fragment Frag on Query { bar baz } Produces the ordered result:
Example â 51 { "foo": 1, "bar": 2, "baz": 3, "qux": 4 } If a field is queried multiple times in a selection, it is ordered by the first time it is encountered. However fragments for which the type does not apply does not affect ordering.
Example â 52 { foo ...Ignored ...Matching bar }
fragment Ignored on UnknownType { qux baz }
fragment Matching on Query { bar qux foo } Produces the ordered result:
Example â 53 { "foo": 1, "bar": 2, "qux": 3 } Also, if directives result in fields being excluded, they are not considered in the ordering of fields.
Example â 54 { foo @Skip(if: true) bar foo } Produces the ordered result:
Example â 55 { "bar": 1, "foo": 2 } Result Coercion
Determining the result of coercing an object is the heart of the GraphQL executor, so this is covered in that section of the spec.
Input Coercion
Objects are never valid inputs.
Type Validation
Object types have the potential to be invalid if incorrectly defined. This set of rules must be adhered to by every Object type in a GraphQL schema.
An Object type must define one or more fields. For each field of an Object type: The field must have a unique name within that Object type; no two fields may share the same name. The field must not have a name which begins with the characters "" (two underscores). The field must return a type where IsOutputType(fieldType) returns true. For each argument of the field: The argument must not have a name which begins with the characters "" (two underscores). The argument must accept a type where IsInputType(argumentType) returns true. An object type may declare that it implements one or more unique interfaces. An object type must be a superâset of all interfaces it implements: The object type must include a field of the same name for every field defined in an interface. The object field must be of a type which is equal to or a subâtype of the interface field (covariant). An object field type is a valid subâtype if it is equal to (the same type as) the interface field type. An object field type is a valid subâtype if it is an Object type and the interface field type is either an Interface type or a Union type and the object field type is a possible type of the interface field type. An object field type is a valid subâtype if it is a List type and the interface field type is also a List type and the listâitem type of the object field type is a valid subâtype of the listâitem type of the interface field type. An object field type is a valid subâtype if it is a NonâNull variant of a valid subâtype of the interface field type. The object field must include an argument of the same name for every argument defined in the interface field. The object field argument must accept the same type (invariant) as the interface field argument. The object field may include additional arguments not defined in the interface field, but any additional argument must not be required, e.g. must not be of a nonânullable type. 3.6.1Field Arguments ArgumentsDefinition (InputValueDefinitionlist) InputValueDefinition DescriptionoptName:TypeDefaultValueoptDirectivesConstopt Object fields are conceptually functions which yield values. Occasionally object fields can accept arguments to further specify the return value. Object field arguments are defined as a list of all possible argument names and their expected input types.
All arguments defined within a field must not have a name which begins with "__" (two underscores), as this is used exclusively by GraphQLâs introspection system.
For example, a Person type with a picture field could accept an argument to determine what size of an image to return.
Example â 56 type Person { name: String picture(size: Int): Url } GraphQL queries can optionally specify arguments to their fields to provide these arguments.
This example query:
Example â 57 { name picture(size: 600) } May yield the result:
Example â 58 { "name": "Mark Zuckerberg", "picture": "http://some.cdn/picture_600.jpg" } The type of an object field argument must be an input type (any type except an Object, Interface, or Union type).
3.6.2Field Deprecation 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.
When using the type system definition language, @deprecated directives are used to indicate that a field is deprecated:
Example â 59 type ExampleType { oldField: String @deprecated } 3.6.3Object Extensions ObjectTypeExtension extendtypeNameImplementsInterfacesoptDirectivesConstoptFieldsDefinition extendtypeNameImplementsInterfacesoptDirectivesConst extendtypeNameImplementsInterfaces Object type extensions are used to represent a type which has been extended from some original type. For example, this might be used to represent local data, or by a GraphQL service which is itself an extension of another GraphQL service.
In this example, a local data field is added to a Story type:
Example â 60 extend type Story { isHiddenLocally: Boolean } Object type extensions may choose not to add additional fields, instead only adding interfaces or directives.
In this example, a directive is added to a User type without adding fields:
Example â 61 extend type User @addedDirective Type Validation
Object type extensions have the potential to be invalid if incorrectly defined.
The named type must already be defined and must be an Object type. The fields of an Object type extension must have unique names; no two fields may share the same name. Any fields of an Object type extension must not be already defined on the original Object type. Any directives provided must not already apply to the original Object type. Any interfaces provided must not be already implemented by the original Object type. The resulting extended object type must be a superâset of all interfaces it implements. 3.7Interfaces InterfaceTypeDefinition DescriptionoptinterfaceNameDirectivesConstoptFieldsDefinitionopt GraphQL interfaces represent a list of named fields and their arguments. GraphQL objects can then implement these interfaces which requires that the object type will define all fields defined by those interfaces.
Fields on a GraphQL interface have the same rules as fields on a GraphQL object; their type can be Scalar, Object, Enum, Interface, or Union, or any wrapping type whose base type is one of those five.
For example, an interface NamedEntity may describe a required field and types such as Person or Business may then implement this interface to guarantee this field will always exist.
Types may also implement multiple interfaces. For example, Business implements both the NamedEntity and ValuedEntity interfaces in the example below.
Example â 62 interface NamedEntity { name: String }
interface ValuedEntity { value: Int }
type Person implements NamedEntity { name: String age: Int }
type Business implements NamedEntity & ValuedEntity { name: String value: Int employeeCount: Int } Fields which yield an interface are useful when one of many Object types are expected, but some fields should be guaranteed.
To continue the example, a Contact might refer to NamedEntity.
Example â 63 type Contact { entity: NamedEntity phoneNumber: String address: String } This allows us to write a query for a Contact that can select the common fields.
Example â 64 { 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:
Counter Example â 65 { 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:
Example â 66 { entity { name ... on Person { 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.
Input Coercion
Interfaces are never valid inputs.
Type Validation
Interface types have the potential to be invalid if incorrectly defined.
An Interface type must define one or more fields. For each field of an Interface type: The field must have a unique name within that Interface type; no two fields may share the same name. The field must not have a name which begins with the characters "" (two underscores). The field must return a type where IsOutputType(fieldType) returns true. For each argument of the field: The argument must not have a name which begins with the characters "" (two underscores). The argument must accept a type where IsInputType(argumentType) returns true. 3.7.1Interface Extensions InterfaceTypeExtension extendinterfaceNameDirectivesConstoptFieldsDefinition extendinterfaceNameDirectivesConst Interface type extensions are used to represent an interface which has been extended from some original interface. For example, this might be used to represent common local data on many types, or by a GraphQL service which is itself an extension of another GraphQL service.
In this example, an extended data field is added to a NamedEntity type along with the types which implement it:
Example â 67 extend interface NamedEntity { nickname: String }
extend type Person { nickname: String }
extend type Business { nickname: String } Interface type extensions may choose not to add additional fields, instead only adding directives.
In this example, a directive is added to a NamedEntity type without adding fields:
Example â 68 extend interface NamedEntity @addedDirective Type Validation
Interface type extensions have the potential to be invalid if incorrectly defined.
The named type must already be defined and must be an Interface type. The fields of an Interface type extension must have unique names; no two fields may share the same name. Any fields of an Interface type extension must not be already defined on the original Interface type. Any Object type which implemented the original Interface type must also be a superâset of the fields of the Interface type extension (which may be due to Object type extension). Any directives provided must not already apply to the original Interface type. 3.8Unions UnionTypeDefinition DescriptionoptunionNameDirectivesConstoptUnionMemberTypesopt UnionMemberTypes =|optNamedType UnionMemberTypes|NamedType 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 type refining fragments or inline fragments.
For example, we might define the following types:
Example â 69 union SearchResult = Photo | Person
type Person { name: String age: Int }
type Photo { height: Int width: Int }
type SearchQuery { firstSearchResult: SearchResult } 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 no fields:
Counter Example â 70 { firstSearchResult { name height } } Instead, the query would be:
Example â 71 { firstSearchResult { ... on Person { name } ... on Photo { height } } } Union members may be defined with an optional leading | character to aid formatting when representing a longer list of possible types:
Example â 72 union SearchResult = | Photo | Person Result Coercion
The union type should have some way of determining which object a given result corresponds to. Once it has done so, the result coercion of the union is the same as the result coercion of the object.
Input Coercion
Unions are never valid inputs.
Type Validation
Union types have the potential to be invalid if incorrectly defined.
A Union type must include one or more unique member types. The member types of a Union type must all be Object base types; Scalar, Interface and Union types must not be member types of a Union. Similarly, wrapping types must not be member types of a Union. 3.8.1Union Extensions UnionTypeExtension extendunionNameDirectivesConstoptUnionMemberTypes extendunionNameDirectivesConst Union type extensions are used to represent a union type which has been extended from some original union type. For example, this might be used to represent additional local data, or by a GraphQL service which is itself an extension of another GraphQL service.
Type Validation
Union type extensions have the potential to be invalid if incorrectly defined.
The named type must already be defined and must be a Union type. The member types of a Union type extension must all be Object base types; Scalar, Interface and Union types must not be member types of a Union. Similarly, wrapping types must not be member types of a Union. All member types of a Union type extension must be unique. All member types of a Union type extension must not already be a member of the original Union type. Any directives provided must not already apply to the original Union type. 3.9Enums EnumTypeDefinition DescriptionoptenumNameDirectivesConstoptEnumValuesDefinitionopt EnumValuesDefinition {EnumValueDefinitionlist} EnumValueDefinition DescriptionoptEnumValueDirectivesConstopt GraphQL Enum types, like scalar types, also represent leaf values in a GraphQL type system. However Enum types describe the set of possible values.
Enums are not references for a numeric value, but are unique values in their own right. They may serialize as a string: the name of the represented value.
In this example, an Enum type called Direction is defined:
Example â 73 enum Direction { NORTH EAST SOUTH WEST } 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 interpreted as the enum input value with the same name.
Type Validation
Enum types have the potential to be invalid if incorrectly defined.
An Enum type must define one or more unique enum values. 3.9.1Enum Extensions EnumTypeExtension extendenumNameDirectivesConstoptEnumValuesDefinition extendenumNameDirectivesConst Enum type extensions are used to represent an enum type which has been extended from some original enum type. For example, this might be used to represent additional local data, or by a GraphQL service which is itself an extension of another GraphQL service.
Type Validation
Enum type extensions have the potential to be invalid if incorrectly defined.
The named type must already be defined and must be an Enum type. All values of an Enum type extension must be unique. All values of an Enum type extension must not already be a value of the original Enum. Any directives provided must not already apply to the original Enum type. 3.10Input Objects InputObjectTypeDefinition DescriptionoptinputNameDirectivesConstoptInputFieldsDefinitionopt InputFieldsDefinition {InputValueDefinitionlist} Fields may accept arguments to configure their behavior. These inputs are often scalars or enums, but they sometimes need to represent more complex values.
A GraphQL 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.
In this example, an Input Object called Point2D describes x and y inputs:
Example â 74 input Point2D { x: Float y: Float } The GraphQL Object type (ObjectTypeDefinition) defined above is inappropriate for reâuse here, because Object types can contain fields that define arguments or contain 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. Result Coercion
An input object is never a valid result. Input Object types cannot be the return type of an Object or Interface field.
Input Coercion
The value for an input object should be an input object literal or an unordered map supplied by a variable, otherwise a query error must be thrown. In either case, the input object literal or unordered map must not contain any entries with names not defined by a field of this input object type, otherwise an error must be thrown.
The result of coercion is an unordered map with an entry for each field both defined by the input object type and for which a value exists. The resulting map is constructed with the following rules:
If no value is provided for a defined input object field and that field definition provides a default value, the default value should be used. If no default value is provided and the input object fieldâs type is nonânull, an error should be thrown. Otherwise, if the field is not required, then no entry is added to the coerced unordered map. If the value null was provided for an input object field, and the fieldâs type is not a nonânull type, an entry in the coerced unordered map is given the value null. In other words, there is a semantic difference between the explicitly provided value null versus having not provided a value. If a literal value is provided for an input object field, an entry in the coerced unordered map is given the result of coercing that value according to the input coercion rules for the type of that field. If a variable is provided for an input object field, the runtime value of that variable must be used. If the runtime value is null and the field type is nonânull, a field error must be thrown. If no runtime value is provided, the variable definitionâs default value should be used. If the variable definition does not provide a default value, the input object field definitionâs default value should be used. Following are examples of input coercion for an input object type with a String field a and a required (nonânull) Int! field b:
Example â 75 input ExampleInputObject { a: String b: Int! } Literal Value Variables Coerced Value { a: "abc", b: 123 } {} { a: "abc", b: 123 } { a: null, b: 123 } {} { a: null, b: 123 } { b: 123 } {} { b: 123 } { a: $var, b: 123 } { var: null } { a: null, b: 123 } { a: $var, b: 123 } {} { b: 123 } { b: $var } { var: 123 } { b: 123 } $var { var: { b: 123 } } { b: 123 } "abc123" {} Error: Incorrect value $var { var: "abc123" } } Error: Incorrect value { a: "abc", b: "123" } {} Error: Incorrect value for field b { a: "abc" } {} Error: Missing required field b { b: $var } {} Error: Missing required field b. $var { var: { a: "abc" } } Error: Missing required field b { a: "abc", b: null } {} Error: b must be nonânull. { b: $var } { var: null } Error: b must be nonânull. { b: 123, c: "xyz" } {} Error: Unexpected field c Type Validation
An Input Object type must define one or more input fields. For each input field of an Input Object type: The input field must have a unique name within that Input Object type; no two input fields may share the same name. The input field must not have a name which begins with the characters "__" (two underscores). The input field must accept a type where IsInputType(inputFieldType) returns true. 3.10.1Input Object Extensions InputObjectTypeExtension extendinputNameDirectivesConstoptInputFieldsDefinition extendinputNameDirectivesConst Input object type extensions are used to represent an input object type which has been extended from some original input object type. For example, this might be used by a GraphQL service which is itself an extension of another GraphQL service.
Type Validation
Input object type extensions have the potential to be invalid if incorrectly defined.
The named type must already be defined and must be a Input Object type. All fields of an Input Object type extension must have unique names. All fields of an Input Object type extension must not already be a field of the original Input Object. Any directives provided must not already apply to the original Input Object type. 3.11List 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 list is serialized as per the item type. To denote that a field uses a List type the item type is wrapped in square brackets like this: pets: [Pet].
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 it 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.
If a listâs item type is nullable, then errors occuring during preparation or coercion of an individual item in the list must result in a the value null at that position in the list along with an error added to the response. If a listâs item type is nonânull, an error occuring at an individual item in the list must result in a field error for the entire list.
For more information on the error handling process, see âErrors and NonâNullabilityâ within the Execution section. Input Coercion
When expected as an input, list values are accepted only when each item in the list can be accepted by the listâs item type.
If the value passed as an input to a list type is not a list and not the null value, then the result of input coercion is a list of size one, where the single item value is the result of input coercion for the listâs item type on the provided value (note this may apply recursively for nested lists).
This allow inputs which accept one or many arguments (sometimes referred to as âvar argsâ) to declare their input type as a list while for the common case of a single value, a client can just pass that value directly rather than constructing the list.
Following are examples of input coercion with various list types and values:
Expected Type Provided Value Coerced Value [Int] [1, 2, 3] [1, 2, 3] [Int] [1, "b", true] Error: Incorrect item value [Int] 1 [1] [Int] null null [[Int]] [[1], [2, 3]] [[1], [2, 3] [[Int]] [1, 2, 3] Error: Incorrect item value [[Int]] 1 [[1]] [[Int]] null null 3.12Non-Null 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 wraps an underlying type, and this type acts identically to that wrapped type, with the exception that null is not a valid response for the wrapping type. A trailing exclamation mark is used to denote a field that uses a NonâNull type like this: name: String!.
Nullable vs. Optional
Fields are always optional within the context of a query, a field may be omitted and the query is still valid. However fields that return NonâNull types will never return the value null if queried.
Inputs (such as field arguments), are always optional by default. However a nonânull input type is required. In addition to not accepting the value null, it also does not accept omission. For the sake of simplicity nullable types are always optional and nonânull types are always required.
Result Coercion
In all of the above result coercions, null was considered a valid value. To coerce the result of a NonâNull type, the coercion of the wrapped 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 a field error must be raised.
When a field error is raised on a nonânull value, the error propogates to the parent field. For more information on this process, see âErrors and NonâNullabilityâ within the Execution section. Input Coercion
If an argument or inputâobject field of a NonâNull type is not provided, is provided with the literal value null, or is provided with a variable that was either not provided a value at runtime, or was provided the value null, then a query error must be raised.
If the value provided to the NonâNull type is provided with a literal value other than null, or a NonâNull variable value, it is coerced using the input coercion for the wrapped type.
A nonânull argument cannot be omitted:
Counter Example â 76 { fieldWithNonNullArg } The value null cannot be provided to a nonânull argument:
Counter Example â 77 { fieldWithNonNullArg(nonNullArg: null) } A variable of a nullable type cannot be provided to a nonânull argument:
Example â 78 query withNullableVariable($var: String) { fieldWithNonNullArg(nonNullArg: $var) } The Validation section defines providing a nullable variable type to a nonânull input type as invalid. Type Validation
A NonâNull type must not wrap another NonâNull type. 3.12.1Combining List and Non-Null The List and NonâNull wrapping types can compose, representing more complex types. The rules for result coercion and input coercion of Lists and NonâNull types apply in a recursive fashion.
For example if the inner item type of a List is NonâNull (e.g. [T!]), then that List may not contain any null items. However if the inner type of a NonâNull is a List (e.g. [T]!), then null is not accepted however an empty list is accepted.
Following are examples of result coercion with various types and values:
Expected Type Internal Value Coerced Result [Int] [1, 2, 3] [1, 2, 3] [Int] null null [Int] [1, 2, null] [1, 2, null] [Int] [1, 2, Error] [1, 2, null] (With logged error) [Int]! [1, 2, 3] [1, 2, 3] [Int]! null Error: Value cannot be null [Int]! [1, 2, null] [1, 2, null] [Int]! [1, 2, Error] [1, 2, null] (With logged error) [Int!] [1, 2, 3] [1, 2, 3] [Int!] null null [Int!] [1, 2, null] null (With logged coercion error) [Int!] [1, 2, Error] null (With logged error) [Int!]! [1, 2, 3] [1, 2, 3] [Int!]! null Error: Value cannot be null [Int!]! [1, 2, null] Error: Item cannot be null [Int!]! [1, 2, Error] Error: Error occurred in item 3.13Directives DirectiveDefinition Descriptionoptdirective@NameArgumentsDefinitionoptonDirectiveLocations DirectiveLocations |optDirectiveLocation DirectiveLocations|DirectiveLocation DirectiveLocation ExecutableDirectiveLocation TypeSystemDirectiveLocation ExecutableDirectiveLocation QUERY MUTATION SUBSCRIPTION FIELD FRAGMENT_DEFINITION FRAGMENT_SPREAD INLINE_FRAGMENT TypeSystemDirectiveLocation SCHEMA SCALAR OBJECT FIELD_DEFINITION ARGUMENT_DEFINITION INTERFACE UNION ENUM ENUM_VALUE INPUT_OBJECT INPUT_FIELD_DEFINITION A GraphQL schema describes directives which are used to annotate various parts of a GraphQL document as an indicator that they should be evaluated differently by a validator, executor, or client tool such as a code generator.
GraphQL implementations should provide the @Skip and @include directives.
GraphQL implementations that support the type system definition language must provide the @deprecated directive if representing deprecated portions of the schema.
Directives must only be used in the locations they are declared to belong in. In this example, a directive is defined which can be used to annotate a fragment definition:
Example â 79 directive @example on FIELD
fragment SomeFragment on SomeType { field @example } Directive locations may be defined with an optional leading | character to aid formatting when representing a longer list of possible locations:
Example â 80 directive @example on | FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT Directives can also be used to annotate the type system definition language as well, which can be a useful tool for supplying additional metadata in order to generate GraphQL execution services, produce client generated runtime code, or many other useful extensions of the GraphQL semantics.
In this example, the directive @example annotates field and argument definitions:
Example â 81 directive @example on FIELD_DEFINITION | ARGUMENT_DEFINITION
type SomeType { field(arg: Int @example): String @example } While defining a directive, it must not reference itself directly or indirectly:
Counter Example â 82 directive @invalidExample(arg: String @invalidExample) on ARGUMENT_DEFINITION Validation
A directive definition must not contain the use of a directive which references itself directly. A directive definition must not contain the use of a directive which references itself indirectly by referencing a Type or Directive which transitively includes a reference to this directive. The directive must not have a name which begins with the characters "" (two underscores). For each argument of the directive: The argument must not have a name which begins with the characters "" (two underscores). The argument must accept a type where IsInputType(argumentType) returns true. 3.13.1@skip directive @Skip(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT The @Skip directive may be provided for fields, fragment spreads, and inline fragments, and allows for conditional exclusion during execution as described by the if argument.
In this example experimentalField will only be queried if the variable $someTest has the value false.
Example â 83 query myQuery($someTest: Boolean) { experimentalField @Skip(if: $someTest) } 3.13.2@include directive @include(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT The @include directive may be provided for fields, fragment spreads, and inline fragments, and allows for conditional inclusion during execution as described by the if argument.
In this example experimentalField will only be queried if the variable $someTest has the value true
Example â 84 query myQuery($someTest: Boolean) { experimentalField @include(if: $someTest) } Neither @Skip nor @include has precedence over the other. In the case that both the @Skip and @include directives are provided in on the same the field or fragment, it must be queried only if the @Skip condition is false and the @include condition is true. Stated conversely, the field or fragment must not be queried if either the @Skip condition is true or the @include condition is false. 3.13.3@deprecated directive @deprecated( reason: String = "No longer supported" ) on FIELD_DEFINITION | ENUM_VALUE The @deprecated directive is used within the type system definition language to indicate deprecated portions of a GraphQL serviceâs schema, such as deprecated fields on a type or deprecated enum values.
Deprecations include a reason for why it is deprecated, which is formatted using Markdown syntax (as specified by CommonMark).
In this example type definition, oldField is deprecated in favor of using newField.
Example â 85 type ExampleType { newField: String oldField: String @deprecated(reason: "Use
newField.") } 4Introspection A GraphQL server supports introspection over its schema. This schema is queried using GraphQL itself, creating a powerful platform for toolâbuilding.Take an example query for a trivial app. In this case there is a User type with three fields: id, name, and birthday.
For example, given a server with the following type definition:
Example â 86 type User { id: String name: String birthday: Date } The query
Example â 87 { __type(name: "User") { name fields { name type { name } } } } would return
Example â 88 { "type": { "name": "User", "fields": [ { "name": "id", "type": { "name": "String" } }, { "name": "name", "type": { "name": "String" } }, { "name": "birthday", "type": { "name": "Date" } }, ] } } 4.1Reserved Names Types and fields required by the GraphQL introspection system that are used in the same context as userâdefined types 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.
4.2Documentation 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 (as specified by CommonMark). Therefore it is recommended that any tool that displays description use a CommonMarkâcompliant Markdown renderer.
4.3Deprecation 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.
4.4Type Name Introspection GraphQL supports type name introspection at any point within 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 queried.
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.
4.5Schema Introspection The schema introspection system is accessible from the metaâfields __schema and __type which are accessible from the type of the root of a query operation.
__schema: __Schema! __type(name: String!): __Type These fields are implicit and do not appear in the fields list in the root type of the query operation.
The schema of the GraphQL schema introspection system:
type __Schema { types: [__Type!]! queryType: __Type! mutationType: __Type subscriptionType: __Type directives: [__Directive!]! }
type __Type { kind: __TypeKind! name: String description: String
OBJECT and INTERFACE only
fields(includeDeprecated: Boolean = false): [__Field!]
OBJECT only
interfaces: [__Type!]
INTERFACE and UNION only
possibleTypes: [__Type!]
ENUM only
enumValues(includeDeprecated: Boolean = false): [__EnumValue!]
INPUT_OBJECT only
inputFields: [__InputValue!]
NON_NULL and LIST only
ofType: __Type }
type __Field { name: String! description: String args: [__InputValue!]! type: __Type! isDeprecated: Boolean! deprecationReason: String }
type __InputValue { name: String! description: String type: __Type! defaultValue: String }
type __EnumValue { name: String! description: String isDeprecated: Boolean! deprecationReason: String }
enum __TypeKind { SCALAR OBJECT INTERFACE UNION ENUM INPUT_OBJECT LIST NON_NULL }
type __Directive { name: String! description: String locations: [__DirectiveLocation!]! args: [__InputValue!]! }
enum __DirectiveLocation { QUERY MUTATION SUBSCRIPTION FIELD FRAGMENT_DEFINITION FRAGMENT_SPREAD INLINE_FRAGMENT SCHEMA SCALAR OBJECT FIELD_DEFINITION ARGUMENT_DEFINITION INTERFACE UNION ENUM ENUM_VALUE INPUT_OBJECT INPUT_FIELD_DEFINITION } 4.5.1The __Type Type __Type is at the core of the type introspection system. It represents scalars, interfaces, object types, unions, enums in the system.
__Type also represents type modifiers, which are used to modify a type that it refers to (ofType: __Type). This is how we represent lists, nonânullable types, and the combinations thereof.
4.5.2Type Kinds There are several different kinds of type. In each kind, different fields are actually valid. These kinds are listed in the __TypeKind enumeration.
4.5.2.1Scalar Represents scalar types such as Int, String, and Boolean. Scalars cannot have fields.
A GraphQL type designer should describe the data format and scalar coercion rules in the description field of any scalar.
Fields
kind must return __TypeKind.SCALAR. name must return a String. description may return a String or null. All other fields must return null. 4.5.2.2Object Object types represent concrete instantiations of sets of fields. The introspection types (e.g. __Type, __Field, etc) are examples of objects.
Fields=== compile output ===
can't load package: package main: main.go:1:1: expected 'package', found '==' main.go:3:4: rune literal not terminated
kind must return __TypeKind.OBJECT. name must return a String. description may return a String or null. fields: The set of fields queryâable on this type.âŚ/
No spam pls Im not gona read that
Appropiorpiartly
Heer
Appropiated