Introspection

Intermediate · 2 min

Query a GraphQL schema with __schema and __type, understand how GraphiQL and code generators use it, and why production servers often restrict it.

Before thisFields and selection setsDirectivesSchema definition language

Jamie Barton · 2 min

Introspection

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Jamie BartonReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Introspection lets a client ask the server to describe its own schema, using ordinary queries on the meta-fields __schema, __type, and __typename.
  • GraphiQL's docs panel and autocomplete, code generators, and schema registries all build on introspection results.
  • Type references in introspection are nested: a field type of [Int!]! appears as NON_NULL wrapping LIST wrapping NON_NULL wrapping Int, so you follow ofType to unwrap it.
  • Deprecated fields and enum values are hidden by default and shown with includeDeprecated: true.
  • The full introspection result is enough to rebuild the schema exactly, which is why servers that must hide their schema disable it.

A schema that can describe itself

When you opened GraphiQL, the docs panel already knew every type and field of the server. Nobody sent it a file. It asked. GraphQL builds this in: every server answers queries about its own schema, using meta-fields whose names start with two underscores. This is introspection.

You already know one meta-field. __typename works anywhere: { book(id: "10") { __typename title } } returned "__typename":"Book" alongside the title. The other two work at the root of a query: __schema and __type.

Asking about the schema

On graphql-js 17.1.0 with the bookshelf schema:

{ __schema { queryType { name } types { name kind } } }

returns the query root, Query, then every type with its kind: OBJECT for Author, Book and Query, ENUM for Genre, SCALAR for ID, String, Int, Float and Boolean. It also lists the introspection types themselves, __Schema, __Type, __Field, and so on, because introspection is part of the schema.

For one type, use __type:

{ __type(name: "Genre") { enumValues { name } } }
{"data":{"__type":{"enumValues":[{"name":"FICTION"},{"name":"SCIENCE"},{"name":"HISTORY"}]}}}

A name that does not exist is null, not an error: { __type(name: "Nope") { name } } returned {"data":{"__type":null}}.

Directives are described too:

{ __schema { directives { name locations } } }

On this schema that lists include, skip, deprecated, specifiedBy and oneOf, each with the places it is allowed.

Reading a type

Fields and their types are reachable from __type:

{
  __type(name: "Book") {
    fields { name type { name kind ofType { name kind } } }
  }
}

Here is part of the response, for three fields:

{"name":"title","type":{"name":null,"kind":"NON_NULL","ofType":{"name":"String","kind":"SCALAR"}}}
{"name":"year","type":{"name":"Int","kind":"SCALAR","ofType":null}}
{"name":"author","type":{"name":null,"kind":"NON_NULL","ofType":{"name":"Author","kind":"OBJECT"}}}

Look at title: String!. Its type has kind: NON_NULL and no name. String! is not a type of its own; it is String wrapped in a modifier, and the real type is under ofType. Lists work the same way with LIST. A field of type [Int!]! is NON_NULL of LIST of NON_NULL of Int, which means three ofType levels. Tools that print types write a small recursive function to unwrap this. If you have wondered why generated code looks so loop-heavy, this is why.

Arguments are included with their defaults:

{ __type(name: "Query") { fields { name args { name defaultValue type { kind name } } } } }

For books, that returned limit with defaultValue: "10", a string, since introspection prints defaults in GraphQL literal syntax. genre had defaultValue: null.

Deprecated things are hidden

I added oldIsbn: String @deprecated(reason: "Use isbn13.") to Book. Plain fields omitted it. This brought it back:

{ __type(name: "Book") { fields(includeDeprecated: true) { name isDeprecated deprecationReason } } }

with oldIsbn flagged isDeprecated: true and the reason “Use isbn13.”. Enum values behave the same way through enumValues(includeDeprecated: true).

Who uses introspection

  • GraphiQL and Apollo Sandbox: the docs panel, autocomplete and inline validation. Their first request on loading is a large introspection query.
  • Code generators: tools like GraphQL Code Generator fetch the schema (or read it from a file) and write types (code generation and typed operations).
  • Gateways and registries: they compare schema versions to catch breaking changes (schema registry and CI checks).
  • Linters, mock servers, test tools.

graphql-js ships getIntrospectionQuery(), which returns the standard big query. I ran it against the bookshelf schema. The result was about 23 KB of JSON for this tiny schema, and buildClientSchema(result.data) rebuilt a schema whose printed SDL was identical to the original. That round trip is the key fact: the introspection result is the whole schema minus resolver code.

Introspection and security

Because introspection hands out the full map of an API, including types and fields meant only for internal clients, some teams turn it off in production. graphql-js provides NoSchemaIntrospectionCustomRule; adding it to the validation rules for a query containing __schema produced errors reading “GraphQL introspection has been disabled, but the requested query contained the field “__schema”.” Servers such as Yoga offer plugins for the same thing.

Be careful about what this buys you. Disabling introspection does not make a field private. A client that already knows or guesses a field name can still query it, and servers often “suggest” corrections in error messages (“Did you mean …?”), which leak names too. Real protection is authorization on fields (authentication and authorization). The decision, with its costs, is in disabling introspection and hardening.

What the video covers

Jamie Barton’s “GraphQL Introspection” is about two minutes, published January 2022. Its description says it covers the built-in introspection system and how to find out more about the schema using GraphQL queries. That is a good short intro. I could not read a transcript, so I do not know which queries it runs. The type-wrapper walk-through, the deprecated flag and the security notes above come from my own runs and are not claimed for the video. Several other results I found for “GraphQL introspection” were security-testing videos aimed at attackers, which suit the hardening lesson later, not this one.

Where this fits

That closes the querying group: you can now write any read operation and ask the server to describe itself. The next group moves to operations that change data. Next: mutations.

Check yourself

  1. 01What is the difference between __schema and __type?

    __schema returns the whole schema's root types, types, and directives, while __type(name:) returns one type by name or null if it does not exist.

  2. 02Why does a field of type String! show up as kind NON_NULL with name null?

    Introspection represents modifiers as wrapper types, so NON_NULL has no name of its own and its ofType is the real type, String.

  3. 03How do you see deprecated fields through introspection?

    Pass includeDeprecated: true to the fields or enumValues selection, otherwise they are omitted.

  4. 04Why might a production API disable introspection?

    Because it hands anyone a full map of the API, which helps attackers find fields, though hiding it is not a substitute for authorization.

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark