==========================
== Zhuo Hong Wei's Blog ==
==========================
Any and everything

Thoughts on Graphql

GraphQL has been around for a long time, but I’ve only recently encountered it at work. Before I pen my thoughts, I want to clarify that I only have limited experience working with GraphQL.

What I like about GraphQL

Imagine that we have a query that returns a list of friends, each of which is a Person entity with many fields.

To me the most useful thing about GraphQL is to be able to customize the response (aka Payload) by specifying which fields you want, like so:

query GetFriends {
  friends {
    firstName
    lastName
  }
}

This return you a list of Person objects with only firstName and lastName. Customizing fields is a useful capability, especially in web and mobile apps where different parts of the UI may require data at varying detail. For example, you may have another friends query with the following response payload if you are building an UI to support editing (hence the need for id):

query GetFriendsWithId {
  friends {
    id
    firstName
    lastName
    status
  }
}

Prior to GraphQL, in a startup that I worked, we supported this capability in REST APIs with a fields parameter, where you might send something like:

{
  "fields": ["firstName", "lastName", "address.street", "address.postalCode"]
}

This was very clunky especially when it came to accessing heavily nested structures.

Another thing I like about GraphQL is the ability to re-use parts of query using fragments, like so:

query GetFriendsWithId {
  friends {
    ...PersonWithId
  }
}
query GetEnemiesWithId {
  enemies {
    ...PersonWithId
  }
}
fragment PersonWithId on Person {
    id
    firstName
    lastName
    status
  }
}

What I don’t like about GraphQL

  1. I’m still getting used to the terms Query, Mutation, Input and Payload. Mutation bring to mind gene mutations when instead it is an update operation. Why not Input with Output instead of Input with Payload?

  2. Unclear error handling semantics