§2023-11-29

GraphQL, an open-source query language and runtime for manipulating APIs. GraphQL was designed by Facebook in 2012 (and released publicly in 2015) to solve various weaknesses with traditional REST architecture by making a new system that is declarative, client-driven, and performant.

¶What is GraphQL?

GraphQL stands for Graph Query Language, but unlike other query languages such as SQL (Structured Query Language), it is not a language for communicating directly with a database, but rather a language that defines a contract through which a client communicates with a API server. The GraphQL specification is an open standard that describes the rules and characteristics of the language. It also provides instructions for executing a GraphQL query.

Due to the fact that GraphQL is defined by an open standard, there is no official implementation of GraphQL. A GraphQL implementation can be written with any programming language, integrate with any type of database, and support any client (such as mobile or web applications), as long as it follows the rules outlined in the spec. One of the most popular commercial GraphQL implementations is Apollo GraphQL, which touts several GraphQL client and server implementations, but it is not necessary to use Apollo to use or understand GraphQL.

¶GraphQL Characteristics

There are several key characteristics of GraphQL design. GraphQL queries are declarative and hierarchical, and a GraphQL schema is strongly-typed and introspective.

¶Declarative

GraphQL queries are declarative, meaning the client will declare exactly which fields it is interested in, and the response will only include those properties.

This example GraphQL query for a hypothetical fantasy game API requests a wizard with an ID of "1", and requests the name and race fields on that object.

{
  wizard(id: "1") {
    name
    race
  }
}

The response, which is returned in JSON format, will return a data object that contains the found wizard object, with the two fields the query requested.

{
  "data": {
    "wizard": {
      "name": "Merlin",
      "race": "HUMAN"
    }
  }
}

Since a GraphQL response only gives you the exact information you want, it results in a more efficient and performant network request than alternatives that always provide a complete set of data. Hierarchical

GraphQL queries are also hierarchical. The data returned follows the shape of the query. In this example, the query has been extended to include spells, and is requesting the name and attack fields of every spell.