Introduction to GraphQL

Arpit Bhayani
@often_weird
http://arpitbhayani.me

The Request Response Paradigm

Some protocols and methods that help us achieve this
  • Native Sockets
  • Remote Procedure Calls
  • SOAP
  • REST

REST

Sending request and getting response over HTTP. It can optionally use HTTP verbs.

REST became a hit because of its

  • Simplicity
  • Ease of extension
  • Use of HTTP as a channel

Problems with REST

  • Endpoint Explosion
  • Rely and Maintain A Good Documentation
  • Multiple Requests
  • Over Fetching
  • Under Fetching
  • Special Endpoints For Specific Purpose

Welcome GraphQL

GraphQL

What SQL does with databases, GraphQL does with APIs.

Brief History of GraphQL

  • Facebook built and started using it in 2012
  • Open sourced it in 2015

GraphQL Concepts

  • GraphQL Server
  • GraphQL Schema
  • GraphQL Types
  • GraphQL Query
  • ...

GraphQL Server

GraphQL server is any web server in any language that adheres to GraphQL specifications.

GraphQL Schema

GraphQL Schema defines how a client can query a GraphQL server and get its response.

GraphQL Types

  • Scalar Types
  • User Defined Types

GraphQL Query

A GraphQL query is a string that is sent to a server to be interpreted and fulfilled, which then returns JSON back to the client.

Resolver Functions

Every field in GraphQL Schema is backed by a resolver function that would resolve the value for that field.

Features of GraphQL

  • Data Shape
  • Strongly Typed
  • Protocol Not Storage
  • Version Free
  • Document is right there

A Todo Application

  • Create a todo
  • Create a Tag
  • Mark a todo as complete
  • Unmark a completed todo as incomplete
  • Get all todos by its completion status
  • Get one single todo

Types

type Tag {
    id: String
    name: String
    color: String
    todos: [Todo]
}

type Todo {
    id: String
    todo: String
    created_at: String
    is_complete: Boolean
    tags: [Tag]
}

Query and Mutation

type Query {
    todos(is_complete: Boolean!, limit: Int): [Todo]
    todo(id: String): Todo
    tags: [Tag]
}

type Mutation {
    createTodo(todo: String!, tags: [String]): Todo
    createTag(name: String!, color: String): Tag
}

Server Side Code

Todo Dooby Doo

Graphiql

Interface to make queries to a GraphQL server

Calling GraphQL Endpoint with any HTTP Client

curl \
    -X POST \
    -H "Content-Type: application/json" \
    --data '{ "query": "{ todos { todo } }" }' \
    https://localhost:8082/graphql
            

Any Questions?