GraphQL Json Schema to SDL

You may on occasion need to convert the GraphQL Json schema to GraphQL SDL (Schema Definition Language), this guide takes you through one possible approach.

Introduction

A GraphQL schema can usually be expressed in 1 of 2 formats:

  • JSON: E.g. as the result of a standard introspection query
  • SDL: Schema Definition Language

Aside from the obvious formatting issues they provide essentially the same information - that being the GraphQL API Schema.

Why convert?

Some tooling may require the GraphQL schema in 1 format over another, for example it may require a .graphql file (SDL) to work. Therefore you may want to convert the JSON schema to SLD format.

Introspection

One of the benefits of GraphQL is that it is self-documenting / self-describing, meaning that by running an introspection query against the endpoint you can get the schema definition available to you. Again, the results of this query will almost always be in json format.

Your access permissions may dictate the shape of the schema that you can view.

We have an article on how to run an introspection query here, but in short all you need to do is:

  • Download one of our API collections (Operator or Seller) for either Insomnia or Postman
  • Configure your client to access your Marketplacer endpoint (i.e. your API key etc.)
  • Locate the “Introspection” folder in the collection
  • Run the query
  • Copy the resulting json payload to a file (e.g. schema.json) and set aside for now.

Converting

There are a number of tools that you can use to convert a Json-based GraphQL schema to an SDL based one, so the choice is yours. In this article we’ll be using graphql-json-to-sld which is a 3rd party npm package.

1. Installing the package

To install the package globally, run the following at a command prompt:

This assumes you have Node Package Manager (NPM) installed - this usually comes bundled with node.js

npm install -g graphql-json-to-sdl

2. Converting

At a command prompt, navigate to where you saved the schema.json file, and run the following command:

graphql-json-to-sdl schema.json schema.graphql

This runs the installed package and converts the schema.json file to a file called schema.graphql.

You can then use the SDL version of the GraphQL schema contained in the schema.graphql file.