Share this:
Share

GraphQL is a query language for APIs. It provides the caller of the APIs to get what it only wants. As the APIs evolve, the client may not need to change. GraphQL can get all the data from multiple sources with one request. This saves bandwidth and time. It is not tied to any database. Rather, it uses your existing code and data.
GraphQL supports multiple languages https://graphql.github.io/code/

Concepts

A GraphQL service is defined in a schema. The schema has types. And types have fields. The developer then provides the functions to query or mutate the fields.
To illustrate the concepts, imagine we’re writing a library API to query or update book inventory. We have to define what data a Book should have, and what can be queried or updated.
Types

Scalar

GraphQL has these scalar types predefined:

  • Boolean: true or false
  • Float: Signed double precision floating point value
  • ID: Same as String. Used to differentiate between machine and human readable data.
  • Int: signed 32-bit Integer
  • String: UTF-8 character sequence
Enumeration

A user defined enumeration type

enum Category {
     FICTION
     NONFICTION
     SCIFI
     CHILDREN
     ADULT
}
User Defined

A type composed of fields of other types

type Book {
    id: ID!                        # required id field. ! means non-null field.
    title: String                  # Book title of type String
    author: String                 # Book author of type String
    pages: Int                     # Number of pages
    categories: [Category]         # Categories this Book is tagged with
    checkedOut: Boolean            # Indicates whether the Book is checked out
}

An object can be classified for use as an input by using input keyword. The above Book type would look like this

input BookInput { 
   title: String                   # Book title of type String 
   author: String                  # Book author of type String 
   pages: Int                      # Number of pages 
   categories: [Category]          # Categories this Book is tagged with 
   checkedOut: Boolean             # Indicates whether the Book is checked out 
}

Notice that the type name is postfix with Input by convention. Also the id field isn’t present because the system will generate the id.

Query

Query is a built-in type. Fields in this type are meant to get data.

For example

type Query {
  books: [Book]                                 # get all the Books
  book(id: ID!): Book                           # get the Book given the 
non-null id
  booksByAuthor(author: String): [Book]         # get all the Books by the 
given author
  booksByCategory(category: Category): [Book]   # get all the Books in the given category
}
Mutations

Mutation is a built-in type. Fields in this type are meant to insert/update data.
For example:

type Mutation {
  add(book: BookInput!): Book            # add a book to the inventory
  checkOutBook(id: ID!): Book            # check out a Book given the id
  returnBook(id: ID!): Book              # return a Book given the id
  remove(id: ID!): Book                  # remove the Book from the inventory given the id
}

To get the library API to work, we’ll need to implement the queries and mutations. See attached javascript.

Querying Book

When querying, we have to specify the query, any parameters, and the fields in the response.

query {
  books {
   id
   title
   author
   checkedOut
  }
}

The code block above shows how we can query for all the books in the library using GraphiQL. The query keyword is optional. Here we’re saying give me all the Books with the id, title, author, and checkedOut status. The user has the flexibility in requesting different fields given the same query, for example, just the id and title.

{
  books {
   id
   title
  }
}
Mutating Books

When doing inserts or updates we have to indicate that it’s a mutation block. Here we’re using the add field, and passing it an array of BookInputs. Because add returns a list of Books, we also have to specify what fields we want in the response.

 mutation {
  add(books: [
   {title: "GraphQL 101", author: "John Doe", pages: 102, categories: 
[NONFICTION, ADULT], checkedOut: false},
   {title: "GraphQL 101 for Kids", author: "Jane Doe", pages: 20, categories: 
[NONFICTION, CHILDREN], checkedOut: false}
  ]) {
   id
   title
   author
  }
}
Putting it all Together

Requirement:

  • nodejs installed
To Run:

Add books to the library

 mutation {
  add(books: [
   {title: "GraphQL 101", author: "John Doe", pages: 102, categories: 
[NONFICTION, ADULT], checkedOut: false},
   {title: "GraphQL 101", author: "John Doe", pages: 102, categories: 
[NONFICTION, ADULT], checkedOut: false}
  ]) {
   id
   title
   author
}

List books in the library

{
  books {
   id
   title
   author
   checkedOut
  }
}

Check out a book

 mutation {
  checkoutBook(id: "<REPLACE_WITH_ID>") {
   title
   author
   categories
   checkedOut
  }
}

Return a book

 mutation {
  returnBook(id: "<REPLACE_WITH_ID>") {
    title
    author
    categories
    checkedOut
  }
}

Get books by an author

{
  booksByAuthor(author: "Jane Smith") {
    title
   }
}

Get books by category

{
  booksByCategory(category:FICTION) {
    id
    title
   }
}

Get a book by id

{
   book(id: "<REPLACE_WITH_ID>") {
     title
     author
     checkedOut
   }
}

Remove a book from the library

mutation {
  remove(id: "<REPLACE_WITH_ID>") {
    title
    author
  }
}

Johnny Loi is a senior software engineer at SAP Customer Experience located in Boulder, USA. This is his first technical article contribution on this website. He enjoys working with JVM languages and frontend technologies. In his free time, he likes to tinker with hardware and software prototyping, and machine learning. Johnny is also a photography enthusiast.

Share this:
Share