See how to design a single-line URL-based query syntax for GraphQL servers that is simple to read and write.
Currently, if we want to use HTTP caching in GraphQL, we must use a GraphQL server that supports persisted queries. That’s because the persisted query will already have the GraphQL query stored in the server; as such, we do not need to provide this information in our request.
In order for GraphQL servers to also support HTTP caching via the single endpoint, the GraphQL query must be provided as a URL param. The GraphQL over HTTP specification will hopefully achieve this goal, providing a standardized language for all GraphQL clients, servers, and libraries to interact with each other.
I suspect, though, that all attempts to pass a GraphQL query via a URL param will be far from ideal. This is because a URL param must be provided as a single-line value, so the query will either need to be encoded or reformatted, making it difficult to understand (for us humans, not for machines).
For instance, this is how a GraphQL query looks when replacing all line breaks with spaces to make it fit within a single line:
{ posts(limit:5) { id title @titleCase excerpt @default(value:"No title", condition:IS_EMPTY) author { name } tags { id name } comments(limit:3, order:"date|DESC") { id date(format:"d/m/Y") author { name } content } } }
Can you make sense of it? Me neither.
And this is how the GraphiQL client encodes the simple query { posts { id title } }
as a URL param:
%7B%0A%20%20posts%20%7B%0A%20%20%20%20id%0A%20%20%20%20title%0A%20%20%7D%0A%7D
Once again, we don’t know what’s going on here.
Both these examples evince the issue: single-line GraphQL queries can work from a technical point of view, transmitting the information to the server, but it is not easy for people to read and write those queries.
Being able to operate with single-line queries would have many benefits. For instance, we could compose the query directly in the browser’s address bar, doing away with the need for some GraphQL client.
It is not that I dislike GraphQL clients — indeed, I love GraphiQL. But I do dislike the idea that I depend on them.
In other words, we could benefit from a query syntax that allows people to:
This is a formidable challenge. But it is not insurmountable.
In this article, I will introduce an alternative syntax, which supports being “easy to read and write in a single line” by us humans.
I am not really proposing introducing this syntax to GraphQL — I understand that would never happen. But the design process for this syntax can, nevertheless, exemplify what we must pay attention to when designing the GraphQL over HTTP specification.
#graphql