GraphQL Json Schema to SDL
3 minute read
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.
SDL to JSON?
We are only covering the conversion of Json to SDL, and not the other way about simply because if you have access to the GraphQL API, you can always get the schema in Json format, (the same cannot be said for SDL, hence this article).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.
Important
You will need to perform your own assessment inline with your organizations own security practices as to whether you can run ad-hoc npm packages such as this. Some other points to note:
- Marketplacer cannot be held responsible for the use of this npm package, nor the functionality it does, or does not provide
- This process is not covered by Marketplacer support
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.