How can I get the arguments and types of graphql mutations via introspection?

Viewed 2737

With a GraphQL introspection query like the following I get all the field names on the mutation type of a GraphQL schema. In addition I'd like to get the arguments and their types. How can I query these in addition?

query {
  __schema {
    mutationType {
      name
      fields {
        name
      }
    }
  }
}
2 Answers
query {
  __schema {
    mutationType {
      name
      fields {
        name
        args {
          name
          defaultValue
          type {
            ...TypeRef
          }
        }
      }
    }
  }
}

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

Read the GraphQL Spec. It is really helpful to find out about the types you can introspect.

The recursive ofType is necessary to "unwrap" any wrapper types (i.e. List and Non-Null). You can look here for an example of a "complete" introspection query. You can also use GraphiQL's or GraphQL Playground's autocompletion feature to help you write these sort of queries.

If you would like to get the arguments of a specific mutation, you can use an introspection query to get its InputObject type.

Say you have a create user mutation that looks something like this

mutation createUser($input: CreateUserInput!) {
  create_user(input: $input) {
    user {
     id
     name
    }
  }
}

You can then use an introspection query to get the CreateUserInput

query createUserInput {   
  __type(name: "CreateUserInput") {
    name
    inputFields {
      name
      description
      defaultValue
    }
  }
}

and use the inputFields from that query to see the mutations arguments. gql introspection docs

Related