Get GraphQL whole schema query

Get GraphQL whole schema query

116

I want to get the schema from the server.
I can get all entities with the types but I’m unable to get the properties.

Getting all types:

query {
  __schema {
    queryType {
      fields {
        name
        type {
          kind
          ofType {
            kind
            name
          }
        }
      }
    }
  }
}

How to get the properties for type:

__type(name: "Person") {
    kind
    name
    fields {
      name
      type {
        kind
        name
        description
      }
    }
  }

How can I get all types with the properties in only 1 request? Or ever better: How can I get the whole schema with the mutators, enums, types …

Share
Improve this question

1

  • I ended using the introspectionQuery from ‘graphql’; as described at the bottom. It’s fine.

    – Aleksandrenko

    Dec 1, 2016 at 15:22

14 Answers
14

Reset to default

149

Update

Using graphql-cli is now the recommended workflow to get and update your schema.

The following commands will get you started:

# install via NPM
npm install -g graphql-cli

# Setup your .graphqlconfig file (configure endpoints + schema path)
graphql init

# Download the schema from the server
graphql get-schema

You can even listen for schema changes and continuously update your schema by running:

graphql get-schema --watch

In case you just want to download the GraphQL schema, use the following approach:

The easiest way to get a GraphQL schema is using the CLI tool get-graphql-schema.

You can install it via NPM:

npm install -g get-graphql-schema

There are two ways to get your schema. 1) GraphQL IDL format or 2) JSON introspection query format.

GraphQL IDL format

get-graphql-schema ENDPOINT_URL > schema.graphql

JSON introspection format

get-graphql-schema ENDPOINT_URL --json > schema.json

or

get-graphql-schema ENDPOINT_URL -j > schema.json

For more information you can refer to the following tutorial: How to download the GraphQL IDL Schema

Share
Improve this answer

9

  • 1

    The answer that was marked the solution was not implementable with the GraphQL server I was trying to use but this library did exactly what was required to generate a full schema. It probably should be marked the solution.

    – ml242

    May 11, 2017 at 20:37

  • 3

    The –json should go before the >

    – konsumer

    Jun 22, 2018 at 5:42

  • 2

    @Catharz: Nowhere does the question state that the OP does not want to use Node or JavaScript. Furthermore, this answer does not require using JavaScript libraries; it presents a command-line tool that happens to be written in JavaScript.

    – wchargin

    Sep 18, 2018 at 17:45

  • 1

    I followed the step and graphql get-schema doesn’t write to the schema.graphql file. It output to the screen, however. I don’t know why.

    – Tan Duong

    Nov 1, 2018 at 15:42

  • 3

    This answer is actually out of date – see github.com/Urigo/graphql-cli/blob/master/docs/… Re headers, you in your gql config you can do schema: { YOUR/ENDPOINT: { headers: {Authorization: "Token your_token"}}}

    – Brandon

    Jun 26, 2020 at 17:55


93

This is the query that GraphiQL uses (network capture):

query IntrospectionQuery {
  __schema {
    queryType {
      name
    }
    mutationType {
      name
    }
    subscriptionType {
      name
    }
    types {
      ...FullType
    }
    directives {
      name
      description
      locations
      args {
        ...InputValue
      }
    }
  }
}

fragment FullType on __Type {
  kind
  name
  description
  fields(includeDeprecated: true) {
    name
    description
    args {
      ...InputValue
    }
    type {
      ...TypeRef
    }
    isDeprecated
    deprecationReason
  }
  inputFields {
    ...InputValue
  }
  interfaces {
    ...TypeRef
  }
  enumValues(includeDeprecated: true) {
    name
    description
    isDeprecated
    deprecationReason
  }
  possibleTypes {
    ...TypeRef
  }
}

fragment InputValue on __InputValue {
  name
  description
  type {
    ...TypeRef
  }
  defaultValue
}

fragment TypeRef on __Type {
  kind
  name
  ofType {
    kind
    name
    ofType {
      kind
      name
      ofType {
        kind
        name
        ofType {
          kind
          name
          ofType {
            kind
            name
            ofType {
              kind
              name
              ofType {
                kind
                name
              }
            }
          }
        }
      }
    }
  }
}

Share
Improve this answer

1

  • The same query is used by Postwoman, but the UI only shows the relevant types when you click on the “Get schema” button.

    – Flogex

    Jun 15, 2020 at 12:30

18

You can use GraphQL-JS’s introspection query to get everything you’d like to know about the schema:

import { introspectionQuery } from 'graphql';

If you want just the information for types, you can use this:

{
    __schema: {
        types: {
            ...fullType
        }
    }
}

Which uses the following fragment from the introspection query:

fragment FullType on __Type {
    kind
    name
    description
    fields(includeDeprecated: true) {
      name
      description
      args {
        ...InputValue
      }
      type {
        ...TypeRef
      }
      isDeprecated
      deprecationReason
    }
    inputFields {
      ...InputValue
    }
    interfaces {
      ...TypeRef
    }
    enumValues(includeDeprecated: true) {
      name
      description
      isDeprecated
      deprecationReason
    }
    possibleTypes {
      ...TypeRef
    }
  }
  fragment InputValue on __InputValue {
    name
    description
    type { ...TypeRef }
    defaultValue
  }
  fragment TypeRef on __Type {
    kind
    name
    ofType {
      kind
      name
      ofType {
        kind
        name
        ofType {
          kind
          name
          ofType {
            kind
            name
            ofType {
              kind
              name
              ofType {
                kind
                name
                ofType {
                  kind
                  name
                }
              }
            }
          }
        }
      }
    }
  }
`;

If that seems complicated, it’s because fields can be arbitrarility deeply wrapped in nonNulls and Lists, which means that technically even the query above does not reflect the full schema if your fields are wrapped in more than 7 layers (which probably isn’t the case).

You can see the source code for introspectionQuery here.

Share
Improve this answer

2

  • This should be at the top!

    – Andy Richardson

    Apr 9, 2020 at 10:20

  • 2

    In newer versions of graphql this is now a function called getIntrospectionQuery()

    – Luke

    Jan 3, 2021 at 0:37


16

Using apollo cli:

npx apollo schema:download --endpoint=https://localhost:4000/graphql schema.json

Share
Improve this answer

2

  • 2

    use npx apollo client:download-schema –endpoint=localhost:4000/graphql schema.json

    – abhijithvijayan

    Apr 26, 2021 at 5:37

  • link returns 404

    – Raj

    Jan 14 at 6:20

7

You can use the Hasura’s graphqurl utility

npm install -g graphqurl

gq <endpoint> --introspect > schema.graphql

# or if you want it in json
gq <endpoint> --introspect --format json > schema.json

Full documentation: https://github.com/hasura/graphqurl

Share
Improve this answer

1

  • This library is now unmaintained with outdated and vulnerable dependencies.

    – Raj

    Jan 14 at 6:17

7

Update

After getting sick of modifying my previous script all the time, I caved and made my own CLI tool gql-sdl. I still can’t find a different tool that can download GraphQL SDL with zero config but would love for one to exist.

Basic usage:

$ gql-sdl https://api.github.com/graphql -H "Authorization: Bearer ghp_[redacted]"
directive @requiredCapabilities(requiredCapabilities: [String!]) on OBJECT | SCALAR | ARGUMENT_DEFINITION | INTERFACE | INPUT_OBJECT | FIELD_DEFINITION | ENUM | ENUM_VALUE | UNION | INPUT_FIELD_DEFINITION

"""Autogenerated input type of AbortQueuedMigrations"""
input AbortQueuedMigrationsInput {
  """The ID of the organization that is running the migrations."""
  ownerId: ID!

  """A unique identifier for the client performing the mutation."""
  clientMutationId: String
}
...

The header argument -H is technically optional but most GraphQL APIs require authentication via headers. You can also download the JSON response instead (--json) but that’s a use case already well served by other tools.

Under the hood this still uses the introspection query provided by GraphQL.js, so if you’re looking to incorporate this functionality into your own code see the example below.


Previous answer

Somehow I wasn’t able to get any of the suggested CLI tools to output the schema in GraphQL’s Schema Definition Language (SDL) instead of the introspection result JSON. I ended up throwing together a really quick Node script to make the GraphQL library do it for me:

const fs = require("fs");
const { buildClientSchema, getIntrospectionQuery, printSchema } = require("graphql");
const fetch = require("node-fetch");

async function saveSchema(endpoint, filename) {
    const response = await fetch(endpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ query: getIntrospectionQuery() })
    });
    const graphqlSchemaObj = buildClientSchema((await response.json()).data);
    const sdlString = printSchema(graphqlSchemaObj);
    fs.writeFileSync(filename, sdlString);
}

saveSchema("https://example.com/graphql", "schema.graphql");

getIntrospectionQuery() has the complete introspection query you need to get everything, and then buildClientSchema() and printSchema() turns the JSON mess into GraphQL SDL.

Wouldn’t be too difficult to make this into a CLI tool itself but that feels like overkill.

Share
Improve this answer

1

  • 1

    gql-sdl does the job really well with no upfront configuration, thanks! Usage example: gql-sdl https://localhost:4000/graphql -o schema-autogenerated.graphql -H "Authorization: Bearer <id token>"

    – cahen

    Dec 21, 2022 at 15:21


5

You can download a remote GraphQL server’s schema with the following command. When the command succeeds, you should see a new file named schema.json in the current working directory.


~$ npx apollo-cli download-schema $GRAPHQL_URL --output schema.json

Share
Improve this answer

    5

    You can use GraphQL-Codegen with the ast-plugin

    npm install --save graphql
    npm install --save-dev @graphql-codegen/cli
    npx graphql-codegen init
    

    Follow the steps to generate the codegen.yml file

    Once the tool is installed, you can use the plugin to download the schema which is schema-ast

    The best is to follow the instruction on the page to install itтАж but basically:

    npm install --save-dev @graphql-codegen/schema-ast

    Then configure the codegen.yml file to set which schema(s) is/are the source of truth and where to put the downloaded schema(s) file:

    schema:
      - 'https://localhost:3000/graphql'
    generates:
      path/to/file.graphql:
        plugins:
          - schema-ast
        config:
          includeDirectives: true
    

    Share
    Improve this answer

      5

      I was also looking and came across this Medium article on GraphQL

      The below query returned many details regarding schema, queries and their input & output params type.

      fragment FullType on __Type {
        kind
        name
        fields(includeDeprecated: true) {
          name
          args {
            ...InputValue
          }
          type {
            ...TypeRef
          }
          isDeprecated
          deprecationReason
        }
        inputFields {
          ...InputValue
        }
        interfaces {
          ...TypeRef
        }
        enumValues(includeDeprecated: true) {
          name
          isDeprecated
          deprecationReason
        }
        possibleTypes {
          ...TypeRef
        }
      }
      fragment InputValue on __InputValue {
        name
        type {
          ...TypeRef
        }
        defaultValue
      }
      fragment TypeRef on __Type {
        kind
        name
        ofType {
          kind
          name
          ofType {
            kind
            name
            ofType {
              kind
              name
              ofType {
                kind
                name
                ofType {
                  kind
                  name
                  ofType {
                    kind
                    name
                    ofType {
                      kind
                      name
                    }
                  }
                }
              }
            }
          }
        }
      }
      query IntrospectionQuery {
        __schema {
          queryType {
            name
          }
          mutationType {
            name
          }
          types {
            ...FullType
          }
          directives {
            name
            locations
            args {
              ...InputValue
            }
          }
        }
      }
      
      

      Share
      Improve this answer

        3

        You can use IntelliJ plugin JS GraphQL then IDEA will ask you create two files “graphql.config.json” and “graphql.schema.json”

        Then you can edit “graphql.config.json” to point to your local or remote GraphQL server:

        "schema": {
        "README_request" : "To request the schema from a url instead, remove the 'file' JSON property above (and optionally delete the default graphql.schema.json file).",
        "request": {
          "url" : "https://localhost:4000",
          "method" : "POST",
          "README_postIntrospectionQuery" : "Whether to POST an introspectionQuery to the url. If the url always returns the schema JSON, set to false and consider using GET",
          "postIntrospectionQuery" : true,
          "README_options" : "See the 'Options' section at https://github.com/then/then-request",
          "options" : {
            "headers": {
              "user-agent" : "JS GraphQL"
            }
          }
        }
        

        After that IDEA plugin will auto load schema from GraphQL server and show the schema json in the console like this:

        Loaded schema from 'https://localhost:4000': {"data":{"__schema":{"queryType":{"name":"Query"},"mutationType":{"name":"Mutation"},"subscriptionType":null,"types":[{"kind":"OBJECT","name":"Query","description":"","fields":[{"name":"launche
        

        Share
        Improve this answer

        1

        • 2

          Version 2 of this plugin will be soon available (now it’s beta: github.com/jimkyndemeyer/js-graphql-intellij-plugin/releases/… ). Instead of graphql.config.json file, there is .graphqlconfig file. You have to set field schemaPath to non-existing file (it will be auto created after downloading schema) and url to GraphQL remote server. Next, in tab “Schemas and project structure” (in “GraphQL” tab), double click on selected “Endpoint” and click “Get GraphQL Schema from Endpoint (introspection)”. In previously mentioned file will be downloaded schema.

          – mkczyk

          Mar 21, 2019 at 20:24


        2

        Refer to https://stackoverflow.com/a/42010467/10189759

        Would like to point out that if authentications are needed, that you probably cannot just use the config file generated from graphql init

        You might have to do something like this, for example, using the github graphql API

        {
          "projects": {
            "graphqlProjectTestingGraphql": {
              "schemaPath": "schema.graphql",
              "extensions": {
                "endpoints": {
                  "dev": {
                    "url": "https://api.github.com/graphql",
                    "headers": {
                      "Authorization": "Bearer <Your token here>"
                    }
                  }
                }
              }
            }
          }
        }
        

        Share
        Improve this answer

          0

          If you want to do it by your self, read these code:

          There is a modular state-of-art tool уАМgraphql-cliуАН, consider looking at it. It uses package уАМgraphqlуАН’s buildClientSchema to build IDL .graphql file from introspection data.

          Share
          Improve this answer

          1

          0

          The graphql npm package’s IntrospectionQuery does

          query IntrospectionQuery {
              __schema {
                  queryType {
                      name
                  }
                  mutationType {
                      name
                  }
                  subscriptionType {
                      name
                  }
                  types {
                      ...FullType
                  }
                  directives {
                      name
                      description
          
                      locations
                      args {
                          ...InputValue
                      }
                  }
              }
          }
          
          fragment FullType on __Type {
              kind
              name
              description
          
              fields(includeDeprecated: true) {
                  name
                  description
                  args {
                      ...InputValue
                  }
                  type {
                      ...TypeRef
                  }
                  isDeprecated
                  deprecationReason
              }
              inputFields {
                  ...InputValue
              }
              interfaces {
                  ...TypeRef
              }
              enumValues(includeDeprecated: true) {
                  name
                  description
                  isDeprecated
                  deprecationReason
              }
              possibleTypes {
                  ...TypeRef
              }
          }
          
          fragment InputValue on __InputValue {
              name
              description
              type {
                  ...TypeRef
              }
              defaultValue
          }
          
          fragment TypeRef on __Type {
              kind
              name
              ofType {
                  kind
                  name
                  ofType {
                      kind
                      name
                      ofType {
                          kind
                          name
                          ofType {
                              kind
                              name
                              ofType {
                                  kind
                                  name
                                  ofType {
                                      kind
                                      name
                                      ofType {
                                          kind
                                          name
                                      }
                                  }
                              }
                          }
                      }
                  }
              }
          }
          

          source

          Share
          Improve this answer

            -1

            You could use apollo codegen:client. See https://github.com/apollographql/apollo-tooling#apollo-clientcodegen-output

            Share
            Improve this answer



              Your Answer


              Post as a guest

              Required, but never shown


              By clicking тАЬPost Your AnswerтАЭ, you agree to our terms of service, privacy policy and cookie policy

              Not the answer you’re looking for? Browse other questions tagged

              or ask your own question.

              Leave a Reply

              Your email address will not be published. Required fields are marked *