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 fragment
s, 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
-
I’m still getting used to the terms
Query
,Mutation
,Input
andPayload
.Mutation
bring to mind gene mutations when instead it is an update operation. Why notInput
withOutput
instead ofInput
withPayload
? -
Unclear error handling semantics