GraphQL

How to create Schema in GraphQL using Schema Definition Language

January 29, 2018

author:

How to create Schema in GraphQL using Schema Definition Language

To define the schema of an API, GraphQL uses its own type system. This syntax for writing schema is known as Schema Definition Language (SDL).

Let us create one of the types here:

type Author {
  name: String!
  email: String!
}

Here type Author has two fields namely name and email. ‘!’ is used to mention required fields.

We can use SDL and create type schema as many times as we require. Let us create one more type and map with Author:

type Post {
  title: String!
  body: String!
  author: Author!
}

Since post is usually written by an author, in above schema, we just mapped Author in Post. On the other hand, we can also setup inverse relationship between Author and Post:

type Author {
  name: String!
   email: String!
  posts: [Post!]!
}

[Post!] in above schema reflects an array of posts. As in, a particular author can write many posts. Thus the relationship so build between Author and Post is one to many.

# Schema with Arguments

Fields in GraphQL can also hold arguments. Arguments in GraphQL are passed by name as opposed to languages like Python and JavaScript where functions and methods expect a list of ordered arguments.

type Post {
  title: String!
  body: String!
  author: Author!
  level(skill:  skillLevel = BASIC):  String!
}

These arguments can either be required or optional. For optional arguments, we can set a default value. For instance, in above SDL, if skill argument is not passed, the default value BASIC will be set.

# Defining Schema

While working with GraphQL, the schema is one of the fundamental concepts. As discussed earlier, it defines the features of an API. It also allows a client to access the required data. Both Author and Post are user-defined GraphQL types, and so we can directly add them into the schema unlike other types like query and mutation which we will explore soon. Therefore, for now, schema looks like:

type Post {
  title: String!
  body: String!
  author: Author!
}

type Author {
  name: String!
   email: String!
  posts: [Post!]!
}

Parting Thoughts:

Schema is an integral part of GraphQL. We learned its basics and how to pass arguments in schema. We also defined a schema for Post and Author. Got any questions? Ask in the comment section below..

Leave a comment

Your email address will not be published. Required fields are marked *