GraphQL validation

GraphQL is a popular, modern, and elegant approach to building APIs. It's enabled many data-driven/interactive applications and data integrations.

One of the distinctive features of GraphQL is how you perform the querying and modification of data. All these operations are tightly controlled by the schema—a foundational component of every GraphQL API.

GraphQL schemas as client-server data contracts

The GraphQL schema describes all the data elements/fields that are available in the API, essentially defining the data model of the data exchange/data interface. In that interchange, the data is represented as a graph of inter-related, typed, JSON-like objects. (I actually find GraphQL SDL to be a very elegant and expressive way to capture such logical data models, even outside of building GraphQL APIs.)

Here's a simple example of a GraphQL schema written in the GraphQL Schema Definition Language (SDL):

type Query {
user(id: ID!): User

type User {
id: ID!
name: String
email: String

When you see a schema like this, you can think of it as a data contract (sort of) between the client and the server. While the clients can choose freely which fields they want to retrieve, all their queries must adhere to the schema defined by the server.

GraphQL queries must match the schema

GraphQL queries are JSON-like documents that are sent to the server to retrieve or modify data. GraphQL servers can only process queries that are well-formed and conform to the defined schema.

Here's an example query for a GraphQL API with the above schema:

user(id: "1") {

The query above is valid because it strictly conforms to the defined schema. If you add, e.g., the age field to the query, it would be invalid because the age field is not defined in the schema. You wouldn't typically have such issues with simple schemas/queries like the ones above, but as your schema and queries grow in complexity, the queries can fail unexpectedly when they suddenly don't conform to the schema.

Exporing GraphQL validation and building a GraphQL validator

I started looking into the technical details of GraphQL schemas and queries early on when I was getting into GraphQL. To then play with programmatically manipulating GraphQL documents, I created a tool that validates GraphQL queries against a GraphQL schema.

The tool is built in TypeScript using the GraphQL.js library. I use the library to build the schema from the provided SDL, parse the query from source, and validate the query against the schema.

Bottom line

GraphQL schemas define the data model and the structure of the data exchange between the client and the server.

All GraphQL queries must match/conform to the schema/data model defined by the server. This tight control over the queries and the schema is one of the key features of GraphQL.

See also

Made by Anton Vasetenkov.

If you want to say hi, you can reach me on LinkedIn or via email. If you like my work, you can support me by buying me a coffee.