Introspection
A GraphQL server can describe itself. Through introspection, a client can query the schema with ordinary GraphQL: which types exist, what fields they have, which arguments they take, what's deprecated. This is what powers GraphiQL's autocomplete and documentation explorer, editor plugins and code generators.
Meta fields
Introspection lives in a few fields that every schema has automatically:
| Field | Available on | Returns |
|---|---|---|
__schema |
Query |
the whole schema: types, root types, directives |
__type(name: "X") |
Query |
one type by name |
__typename |
every object | the concrete type name |
Their names start with two underscores, which is reserved for introspection: you can't define your own __-fields.
Asking about one type
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
"A recipe that can be cooked at home."
type Recipe {
title: String!
minutes: Int
ingredients(limit: Int = 10): [String!]!
}
type Query { recipes: [Recipe!]! }
`);
const query = `{
__type(name: "Recipe") {
name
kind
description
fields {
name
args { name defaultValue }
type { kind name ofType { kind name } }
}
}
}`;
const result = await graphql({ schema, source: query });
const type = result.data.__type;
console.log(type.name, type.kind, '-', type.description);
for (const field of type.fields) {
const args = field.args.map((a) => `${a.name}=${a.defaultValue}`).join(', ');
console.log(' ', field.name, JSON.stringify(field.type), args);
}Recipe OBJECT - A recipe that can be cooked at home.
title {"kind":"NON_NULL","name":null,"ofType":{"kind":"SCALAR","name":"String"}}
minutes {"kind":"SCALAR","name":"Int","ofType":null}
ingredients {"kind":"NON_NULL","name":null,"ofType":{"kind":"LIST","name":null}} limit=10
Wrapped types show up as nested ofTypes: String! is a NON_NULL whose ofType is the SCALAR String. [String!]! is three levels deep, so its inner ofType is cut off here; real tools query several levels.
Listing the whole schema
__schema returns every type, including the built-in scalars and the introspection types themselves (their names start with __):
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
enum Diet { VEGAN VEGETARIAN ANY }
type Recipe { title: String!, diet: Diet! }
type Query { recipes: [Recipe!]! }
type Mutation { addRecipe(title: String!): Recipe }
`);
const result = await graphql({
schema,
source: `{
__schema {
queryType { name }
mutationType { name }
types { name kind }
}
}`,
});
const { queryType, mutationType, types } = result.data.__schema;
console.log('query root:', queryType.name, '| mutation root:', mutationType.name);
console.log('own types:', types.filter((t) => !t.name.startsWith('__')).map((t) => `${t.name} (${t.kind})`).join(', '));
console.log('introspection types:', types.filter((t) => t.name.startsWith('__')).length);query root: Query | mutation root: Mutation
own types: Diet (ENUM), Recipe (OBJECT), String (SCALAR), Query (OBJECT), Mutation (OBJECT), Boolean (SCALAR)
introspection types: 8
Deprecations are visible
Deprecated fields are hidden from introspection by default and shown with includeDeprecated: true, together with the reason. That's how editors know to strike them through:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type User {
id: ID!
fullName: String!
name: String @deprecated(reason: "Use fullName.")
}
type Query { me: User }
`);
const result = await graphql({
schema,
source: `{
__type(name: "User") {
fields(includeDeprecated: true) { name isDeprecated deprecationReason }
}
}`,
});
for (const f of result.data.__type.fields) {
console.log(f.name.padEnd(9), f.isDeprecated, f.deprecationReason);
}id false null
fullName false null
name true Use fullName.
From introspection back to SDL
The full introspection query is long, so graphql-js provides it as getIntrospectionQuery(). A client can run it against a remote server, then rebuild a local copy of the schema with buildClientSchema and print it as SDL. This is how codegen tools download schemas:
import { graphql, buildSchema, getIntrospectionQuery, buildClientSchema, printSchema } from 'graphql';
const serverSchema = buildSchema(`
type Book { title: String!, year: Int }
type Query { books(first: Int = 5): [Book!]! }
`);
// 1. The client sends the standard introspection query (over HTTP in real life).
const { data } = await graphql({ schema: serverSchema, source: getIntrospectionQuery() });
console.log('introspection JSON size:', JSON.stringify(data).length, 'characters');
// 2. It rebuilds the schema locally, without any resolvers.
const clientSchema = buildClientSchema(data);
console.log(printSchema(clientSchema));introspection JSON size: 19154 characters
type Book {
title: String!
year: Int
}
type Query {
books(first: Int = 5): [Book!]!
}
Should production expose introspection?
Introspection is extremely useful in development. In production it's a judgement call:
- Public APIs (GitHub, Shopify) leave it on: it is their documentation.
- Private APIs behind your own apps often turn it off, so attackers can't map the schema easily. This is obscurity, not security: every field still needs proper authorization.
graphql-js includes a validation rule for this, NoSchemaIntrospectionCustomRule, which rejects queries that use __schema or __type.
Test yourself
Which field lets you query the description of a single type named Recipe?
__typename(Recipe)__type(name: "Recipe")__schema(type: Recipe)Recipe.__info
How does String! appear in introspection?
{ kind: SCALAR, name: "String!" }- A
NON_NULLtype whoseofTypeis theStringscalar - A
LISTofString - It is not shown
What does buildClientSchema do?
- Starts a GraphQL server
- Rebuilds a schema object from introspection results
- Validates a query
- Generates resolvers