Index
Edit

What About GraphQL?

tl;dr: GraphQL is awesome, but it is really not a general query language. It is a great way to structure a purpose built API to a specific data set. The Sanity query language GROQ is general and can query any collection of unstructured JSON-documents without any up-front configuration. In a Sanity/GraphQL environment you would carefully craft a specific GraphQL API powered by GROQ under the hood.

GraphQL is a pattern for designing flexible APIs to structured, connected data originated at Facebook. GraphQL is very popular, and there are loads of nice tooling and libraries for it appearing every week. Naturally we are often asked why we did not design Sanity with GraphQL as the core query language.

Take this perfectly sensible GROQ-query:

*[_type == "author" && name match "Edgar" && debutYear < 1900]{
  name,
  debutYear,
  "bookCount": count(books)
}

(Fetch authors, whose name contain the string "Edgar" and debuted before 1900, return the name, year of debut, and number of books for each author. The results would perhaps include {"name": "Edgar Allan Poe", "debutYear": 1827, "bookCount": 27})

When you design a GraphQL-API you define a number of queries and the parameters they accept. In an imaginary API, the above query could be expressed as:

{
  authors(debutedBefore: 1900, nameIncludes: "Edgar") {
    name,
    debutYear,
    bookCount()
  }
}

This is clearly awesome, the problem is that in order to perform this query you would have to configure the query authors and every possible parameter it takes. What if you wanted to find only authors that have published more than 5 books? No problem, you just add another parameter to the query, minBookCount perhaps. You see where this is leading?

There have of course been attempts to encode all kinds of general query abilities in a GraphQL-API, but then we end up with an ugly query language instead of a great API, and we are not really getting the best of GraphQL.

So calling GraphQL a query language is really a misnomer. Instead of using it as an awful general query language, we like to use it as an awesome API pattern. The strength of GraphQL is that it is not general, but that you design a specific way to access your data.

If you want to use GraphQL with Sanity at this time, you will have to code your own microservice mapping GraphQL to GROQ. That being said, adding a GraphQL API is on our long term road map.

Previous: Query Cheat Sheet - GROQNext: IDs and Paths