May 01, 2017

GraphQL SDL — Schema Definition Language

nikolasburk
Nikolas Burk
@nikolasburk
Join the
discussion
1

GraphQL has its own language to write GraphQL Schemas: The GraphQL Schema Definition Language (SDL). SDL is simple and intuitive to use while being extremely powerful and expressive.

What is a GraphQL Schema Definition?

A GraphQL Schema Definition is the most concise way to specify a GraphQL schema. The syntax is well-defined and are part of the official GraphQL specification. Schema Definitions are sometimes referred to as IDL (Interface Definition Language) or SDL (Schema Definition Language).

The GraphQL schema for a blogging app could be specified like this:

type Post {
  id: String!
  title: String!
  publishedAt: DateTime!
  likes: Int! @default(value: 0)
  blog: Blog @relation(name: "Posts")
}

type Blog {
  id: String!
  name: String!
  description: String
  posts: [Post!]! @relation(name: "Posts")
}

The main components of a schema definition are the types and their fields. Additional information can be provided as custom directives like the @default value specified for the likes field.

Type

A type has a name and can implement one or more interfaces:

type Post implements Item {
  # ...
}

Field

A field has a name and a type:

age: Int

The GraphQL spec defines some built-in scalar values but more can be defined by a concrete implementation. The built in scalar types are:

  • Int
  • Float
  • String
  • Boolean
  • ID

In addition to scalar types, a field can use any other type defined in the schema definition.

Non-nullable fields are denoted by an exclamation mark:

age: Int!

Lists are denoted by square brackets:

names: [String!]

Enum

An enum is a scalar value that has a specified set of possible values:

enum Category {
  PROGRAMMING_LANGUAGES
  API_DESIGN
}

Interface

In GraphQL an interface is a list of fields. A GraphQL type must have the same fields as all the interfaces it implements and all interface fields must be of the same type.

interface Item {
  title: String!
}

Schema directive

A directive allows you to attach arbitrary information to any other schema definition element. Directives are always placed behind the element they describe:

name: String! @defaultValue(value: "new blogpost")

Directives don’t have intrinsic meaning. Each GraphQL implementation can define their own custom directives that add new functionality.

GraphQL specifies built-in skip and include directives that can be used to include or exclude specific fields in queries, but these aren't used in the schema language.