How do you retrieve GraphQL schema

Just recording my amazement here. Suppose you have a GraphQL server. How do you ask it what’s the query schema?

You would expect something like calling https://myserver/graphql/schema? Nah, that would be too REST’y.

So, maybe it’s sending something like query { __schema } to the GraphQL endpoint? Well, sort of, but it’s much more complicated than that. With GraphQL you need to tell it exactly what you want. And you want a bunch of things, including query names, field names, and recursive description of the types involved.

Actually, GraphQL can’t really handle recursive, the best you can do is to ask for types N levels down. The actual schema query is below, it goes 8 levels deep when querying for types. Fascinating, no?

Source: https://stackoverflow.com/questions/37397886/get-graphql-whole-schema-query

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
              }
            }
          }
        }
      }
    }
  }
}

Leave a Reply

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