GraphQL: Getting Started

To create a new project and install GraphQL.js in your current directory:

npm init
npm install graphql --save

Writing Code

 For an API that just returns “Hello world!”, we can put this code in a file named server.js:

var { graphql, buildSchema } = require('graphql');

// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
  type Query {
    hello: String
  }
`);

// The root provides a resolver function for each API endpoint
var root = {
  hello: () => {
    return 'Hello world!';
  },
};

// Run the GraphQL query '{ hello }' and print out the response
graphql(schema, '{ hello }', root).then((response) => {
  console.log(response);
});

If you run this with:

node server.js

You should see the GraphQL response printed out:

{ data: { hello: 'Hello world!' } }

GraphQL: Type System Cheat Sheet

Scalar Type

The default Scalar types:

  • Int − Signed 32-bit Integer
  • Float − Signed double-precision floating-point value
  • String − UTF – 8-character sequence
  • Boolean − True or false
  • ID − A unique identifier, often used as a unique identifier to fetch an object or as the key for a cache.

The syntax for defining a Scalar type:

field: data_type

Object Type

The syntax for defining an Object type

type object_type_name
{
   field1: data_type
   field2:data_type 
   ....
   fieldn:data_type
}

Query Type

The syntax for defining a Query Type

type Query {
   field1: data_type
   field2:data_type
   field2(param1:data_type,param2:data_type,...paramN:data_type):data_type
}

Mutation Type

The syntax for defining a Mutation type

type Mutation {
   field1: data_type
   field2(param1:data_type,param2:data_type,...paramN:data_type):data_type 
}

Enum Type

The syntax for defining an Enum type

type enum_name{
   value1
   value2
}

GraphQL: Resolver

Resolver function in a GraphQL schema accepts four positional arguments:

fieldName:(root, args, context, info) => { result }
ArgumentsDescription
rootThe object that contains the result returned from the resolver on the parent field.
argsAn object with the arguments passed into the field in the query.
contextThis is an object shared by all resolvers in a particular query.
infoIt contains information about the execution state of the query, including the field name, the path to the field from the root.

Resolvers in GraphQL can return different types of values:

ArgumentsDescription
null or undefinedIndicates the object could not be found
arrayOnly valid if the schema indicates that the result of a field should be a list
promiseResolvers often do asynchronous actions like fetching from a database or backend API, so they can return promises
scalar or objectA resolver can also return other values

GraphQL: Mutations

The basic syntax of a mutation query:

type Mutation {
  setMessage(message: String): String
}

type Query {
  getMessage: String
}

Graphql: Execution Module Cheat Sheet

function execute

Executes a GraphQL request on the provided schema.

export function execute(
  schema: GraphQLSchema,
  documentAST: Document,
  rootValue?: mixed,
  contextValue?: mixed,
  variableValues?: ?{[key: string]: mixed},
  operationName?: ?string
): MaybePromise<ExecutionResult>

type MaybePromise<T> = Promise<T> | T;

type ExecutionResult = {
  data: ?Object;
  errors?: Array<GraphQLError>;
}

Graphql: Error Module Cheat Sheet

GraphQLError 

A representation of an error that occurred within GraphQL.

class GraphQLError extends Error {
 constructor(
   message: string,
   nodes?: Array<any>,
   stack?: ?string,
   source?: Source,
   positions?: Array<number>,
   originalError?: ?Error,
   extensions?: ?{ [key: string]: mixed }
 )
}

syntaxError 

Produces a GraphQLError representing a syntax error.

function syntaxError(
  source: Source,
  position: number,
  description: string
): GraphQLError;

locatedError 

Produces a new GraphQLError aware of the location responsible for the error.

function locatedError(error: ?Error, nodes: Array<any>): GraphQLError {

formatError 

Format an error according to the rules described by the Response Format.

function formatError(error: GraphQLError): GraphQLFormattedError

type GraphQLFormattedError = {
  message: string,
  locations: ?Array<GraphQLErrorLocation>
};

type GraphQLErrorLocation = {
  line: number,
  column: number
};

Graphql: Language Module Cheat Sheet

Source

Source 

Represents the input string to the GraphQL server

export class Source {
  constructor(body: string, name?: string)
}

getLocation 

Converts a character offset to a row and column in the Source

function getLocation(source: Source, position: number): SourceLocation

type SourceLocation = {
  line: number;
  column: number;
}

Lexer

lex 

Lexes a GraphQL Source according to the GraphQL Gramma

function lex(source: Source): Lexer;

type Lexer = (resetPosition?: number) => Token;

export type Token = {
  kind: number;
  start: number;
  end: number;
  value: ?string;
};

Parser 

parse 

Parses a GraphQL Source according to the GraphQL Grammar

export function parse(
  source: Source | string,
  options?: ParseOptions
): Document

parseValue 

Parses a value according to the GraphQL Grammar

export function parseValue(
  source: Source | string,
  options?: ParseOptions
): Value

Visitor

visit 

A general-purpose visitor to traverse a parsed GraphQL AST

function visit(root, visitor, keyMap)

Alternatively to providing enter() and leave() functions, a visitor can instead provide functions named the same as the kinds of AST nodes, or enter/leave visitors at a named key, leading to four permutations of visitor API:

  • Named visitors triggered when entering a node a specific kind.
visit(ast, {
  Kind(node) {
    // enter the "Kind" node
  }
})
  • Named visitors that trigger upon entering and leaving a node of a specific kind.
visit(ast, {
  Kind: {
    enter(node) {
      // enter the "Kind" node
    }
    leave(node) {
      // leave the "Kind" node
    }
  }
})
  • Generic visitors that trigger upon entering and leaving any node.
visit(ast, {
  enter(node) {
    // enter any node
  },
  leave(node) {
    // leave any node
  }
})
  • Parallel visitors for entering and leaving nodes of a specific kind.
visit(ast, {
  enter: {
    Kind(node) {
      // enter the "Kind" node
    }
  },
  leave: {
    Kind(node) {
      // leave the "Kind" node
    }
  }
})

Printer 

print 

Prints an AST in a standard format.

function print(ast): string

GraphQL: Type Module Cheat Sheet

Definitions

GraphQLSchema

A representation of the capabilities of a GraphQL Server.

class GraphQLSchema {
  constructor(config: GraphQLSchemaConfig)
}

type GraphQLSchemaConfig = {
  query: GraphQLObjectType;
  mutation?: ?GraphQLObjectType;
}

GraphQLScalarType

A scalar type within GraphQL.

class GraphQLScalarType<InternalType> {
  constructor(config: GraphQLScalarTypeConfig<InternalType>)
}

type GraphQLScalarTypeConfig<InternalType> = {
  name: string;
  description?: ?string;
  serialize: (value: mixed) => ?InternalType;
  parseValue?: (value: mixed) => ?InternalType;
  parseLiteral?: (valueAST: Value) => ?InternalType;
}

GraphQLInterfaceType 

An interface type within GraphQL that defines field implementations will contain.

class GraphQLInterfaceType {
  constructor(config: GraphQLInterfaceTypeConfig)
}

type GraphQLInterfaceTypeConfig = {
  name: string,
  fields: GraphQLFieldConfigMapThunk | GraphQLFieldConfigMap,
  resolveType?: (value: any, info?: GraphQLResolveInfo) => ?GraphQLObjectType,
  description?: ?string
};

GraphQLUnionType

A union type within GraphQL that defines a list of implementations.

class GraphQLUnionType {
  constructor(config: GraphQLUnionTypeConfig)
}

type GraphQLUnionTypeConfig = {
  name: string,
  types: GraphQLObjectsThunk | Array<GraphQLObjectType>,
  resolveType?: (value: any, info?: GraphQLResolveInfo) => ?GraphQLObjectType;
  description?: ?string;
};

type GraphQLObjectsThunk = () => Array<GraphQLObjectType>;

GraphQLEnumType 

An enum type within GraphQL that defines a list of valid values.

class GraphQLEnumType {
  constructor(config: GraphQLEnumTypeConfig)
}

type GraphQLEnumTypeConfig = {
  name: string;
  values: GraphQLEnumValueConfigMap;
  description?: ?string;
}

type GraphQLEnumValueConfigMap = {
  [valueName: string]: GraphQLEnumValueConfig;
};

type GraphQLEnumValueConfig = {
  value?: any;
  deprecationReason?: string;
  description?: ?string;
}

type GraphQLEnumValueDefinition = {
  name: string;
  value?: any;
  deprecationReason?: string;
  description?: ?string;
}

GraphQLInputObjectType

An input object type within GraphQL that represents structured inputs.

class GraphQLInputObjectType {
  constructor(config: GraphQLInputObjectConfig)
}

type GraphQLInputObjectConfig = {
  name: string;
  fields: GraphQLInputObjectConfigFieldMapThunk | GraphQLInputObjectConfigFieldMap;
  description?: ?string;
}

type GraphQLInputObjectConfigFieldMapThunk = () => GraphQLInputObjectConfigFieldMap;

type GraphQLInputObjectFieldConfig = {
  type: GraphQLInputType;
  defaultValue?: any;
  description?: ?string;
}

type GraphQLInputObjectConfigFieldMap = {
  [fieldName: string]: GraphQLInputObjectFieldConfig;
};

type GraphQLInputObjectField = {
  name: string;
  type: GraphQLInputType;
  defaultValue?: any;
  description?: ?string;
}

type GraphQLInputObjectFieldMap = {
  [fieldName: string]: GraphQLInputObjectField;
};

GraphQLList 

A type wrapper around other types that represents a list of those types.

class GraphQLList {
  constructor(type: GraphQLType)
}

GraphQLNonNull

A type wrapper around other types that represents a non-null version of those types.

class GraphQLNonNull {
  constructor(type: GraphQLType)
}

Predicates

isInputType 

Returns if a type can be used as input types for arguments and directives.

function isInputType(type: ?GraphQLType): boolean

isOutputType 

Returns if a type can be used as output types as the result of fields.

function isOutputType(type: ?GraphQLType): boolean

isLeafType 

Returns if a type can be a leaf value in response.

function isLeafType(type: ?GraphQLType): boolean

isCompositeType 

Returns if a type can be the parent context of a selection set.

function isCompositeType(type: ?GraphQLType): boolean

isAbstractType 

Returns if a type is a combination of object types.

function isAbstractType(type: ?GraphQLType): boolean

Un-modifiers

getNullableType 

Strips any non-null wrappers from a type.

function getNullableType(type: ?GraphQLType): ?GraphQLNullableType

getNamedType 

Strips any non-null or list wrappers from a type.

function getNamedType(type: ?GraphQLType): ?GraphQLNamedType

Scalars

GraphQLInt 

A scalar type representing integers.

var GraphQLInt: GraphQLScalarType;

GraphQLFloat 

A scalar type representing floats.

var GraphQLFloat: GraphQLScalarType;

GraphQLString 

A scalar type representing strings.

var GraphQLString: GraphQLScalarType;

GraphQLBoolean 

A scalar type representing booleans.

var GraphQLBoolean: GraphQLScalarType;

GraphQLID 

A scalar type representing IDs.

var GraphQLID: GraphQLScalarType;

GraphQL: Utilities Module Cheat Sheet

Introspection

introspectionQuery

A GraphQL introspection query containing enough information to reproduce a type system.

var introspectionQuery: string

buildClientSchema 

Produces a client schema given the result of querying a schema with `introspectionQuery`.

function buildClientSchema(
  introspection: IntrospectionQuery
): GraphQLSchema

Build a GraphQLSchema for use by client tools.

Schema Representation 

buildSchema 

Builds a Schema object from GraphQL schema language.

function buildSchema(source: string | Source): GraphQLSchema {

printSchema 

Prints the schema in a standard format.

function printSchema(schema: GraphQLSchema): string {

printIntrospectionSchema 

Prints the introspection features of the schema in a standard format.

function printIntrospectionSchema(schema: GraphQLSchema): string {

buildASTSchema 

Builds a schema from a parsed AST Schema.

function buildASTSchema(
  ast: SchemaDocument,
  queryTypeName: string,
  mutationTypeName: ?string
): GraphQLSchema

typeFromAST 

Looks up a type referenced in an AST in the GraphQLSchema.

function typeFromAST(
  schema: GraphQLSchema,
  inputTypeAST: Type
): ?GraphQLType

astFromValue 

Produces a GraphQL Input Value AST given a JavaScript value.

function astFromValue(
  value: any,
  type?: ?GraphQLType
): ?Value

Visitors 

TypeInfo 

Tracks type and field definitions during a visitor AST traversal..

class TypeInfo {
  constructor(schema: GraphQLSchema)
  getType(): ?GraphQLOutputType {
  getParentType(): ?GraphQLCompositeType {
  getInputType(): ?GraphQLInputType {
  getFieldDef(): ?GraphQLFieldDefinition {
  getDirective(): ?GraphQLDirective {
  getArgument(): ?GraphQLArgument {
}

Value Validation

isValidJSValue 

Determines if a JavaScript value is valid for a GraphQL type.

function isValidJSValue(value: any, type: GraphQLInputType): string[]

isValidLiteralValue 

Determines if a literal value from an AST is valid for a GraphQL type.

function isValidLiteralValue(
  type: GraphQLInputType,
  valueAST: Value
): string[]

GraphQL: Validation Module Cheat Sheet

validate

Validates an AST against a provided Schema.

function validate(
  schema: GraphQLSchema,
  ast: Document,
  rules?: Array<any>
): Array<GraphQLError>

specifiedRules

A list of standard validation rules described in the GraphQL specification.

var specifiedRules: Array<(context: ValidationContext): any>