All You (n)ever Wanted to Know about Introspection

Rate this content
Bookmark

With only an HTTP endpoint provided you get autocompletion and client-side validation. Isn't it magic? No, it is introspection. Whether you have heard about it or not, you have most likely already utilized it. Let's uncover together what it is, how it works and why it is the fuel to power the GraphQL ecosystem.

FAQ

GraphQL introspection is a feature that allows you to query a GraphQL server about the types it supports and the queries it can execute. It is important because it provides self-awareness and self-discoverability of the API, enabling tools like auto-completion in API tooling and helping developers understand the schema without needing access to the server code.

Unlike REST, where API documentation can vary and may not always adhere to standards like OpenAPI, GraphQL's introspection is built into the language specification itself. This means it provides a standardized way to understand the API schema directly from the server, ensuring consistent and reliable access to schema details.

In GraphQL, __schema and __type are special fields used for introspection queries. They allow you to fetch details about the schema and types used by the GraphQL server. These fields are part of the GraphQL specification and are used internally to provide information about the API structure.

Yes, introspection can be disabled in GraphQL. This is typically done through server configuration to prevent clients from querying schema information, which might be desirable for security reasons. However, even with introspection disabled, certain information might still be inferred from errors or other API interactions.

GraphQL introspection provides several benefits, including the ability to automatically generate documentation, facilitate API tooling and testing, and enable dynamic query building. It also helps in schema validation and can be used to ensure that API changes are consistent and backward compatible.

In automated testing, GraphQL introspection can be used to verify that the API schema matches expected definitions. Developers can write custom introspection queries to check for specific types or fields, ensuring that the schema generation process adheres to the business requirements and that modifications do not break existing functionality.

__typename is a meta field in GraphQL used to obtain the name of the type at runtime. This is particularly useful when working with polymorphic types where the type might differ depending on the context, allowing developers to conditionally handle different types returned by the API.

Stephan Schneider
Stephan Schneider
20 min
10 Dec, 2021

Comments

Sign in or register to post your comment.

Video Summary and Transcription

Introspection in GraphQL allows APIs to be self-aware and self-discoverable. It eliminates the need for external standards or documentation and provides detailed information about types and fields. The introspection query provides insights into the schema, and GraphQL Tools allows schema transformation. The introspection result can be used for generating powerful tooling and detecting breaking changes in CI/CD pipelines.

1. Introduction to Introspection in GraphQL

Short description:

Hello and welcome. In this talk, I'll be discussing introspection in GraphQL. Introspection allows your API to be self-aware and self-discoverable, providing information about the types it works with. Unlike REST, GraphQL has built-in support for introspection, eliminating the need for relying on external standards or documentation. With introspection, you can easily query your GraphQL server and retrieve information about the available types and their fields. Let's take a look at a real-world example using GraphiQL, a popular graphical interface for issuing queries against GraphQL servers. GraphiQL provides auto-completion and detailed information about the schema, types, and fields.

Hello and welcome. Thank you for joining me on my GraphQL Galaxy talk, and I'll be talking about introspection, how it can be useful and all those things. The idea for this talk actually came from when a colleague dragged me into a live stream where they wanted to figure out how they can get GraphQL query autocompletion into some API tooling. And I thought it might be interesting to just share some of the learnings with other folks as well.

So who am I? My name is Stephan Schneider and I have been working with APIs for roughly five years now and have started working with GraphQL in 2018 when our company was building our first GraphQL API. Since then, I basically have never stopped working with it and want to give you some more details about introspection. So, we do have this slight distinction that we have a thousand schemas every month that we generate at Contentful because our customers can define their own content model, and based on that, we generate them a GraphQL API. And for that, we also use introspection in some of our tests and that will be quite interesting.

What is introspection and why should I care? Introspection is also a term used in psychology and I really like those two terms about self-awareness and self-discoverability and basically took them now to the technical part of introspection as well. So self-awareness means that your API knows which type it is working with and can give you those information about them. Self-discoverability means it's a standardised way that the server can make assumptions about your types and that you can use to actually fetch those types from the server. In comparison to REST, this is an upfront design decision of the language itself. On REST, you have to rely on that there might be some standard that an API is following like the OpenAPI spec, for example. If it doesn't comply to it, you basically have no more information about what kind of types it provided and have to rely on a good developer documentation being written.

So let's look at a real world example. Most of you have probably worked with it beforehand. Graphical. The graphical interfaces ship with most of the server implementation that you have, and it allows you to issue queries against your GraphQL server. So here, for example, you can see we have all the types available that our Contentful schema knows about, for example, the Contentful Metadata or the Contentful Tag. Then for all of those types, it also knows about which fields you have available. As you can see here, for example, also the descriptions of them. Not only that, you also have for all those fields, their types and their arguments to the types as well. So in the end, GraphQL knows about everything that your schema contains and can give you auto-completion for it. How does it work? Let me introduce you to a couple of types that you might have never seen before, because they're actually not part of your schema, but they are part of your schema. They are there implicitly. So here, for example, we have on the query type, we have two more fields called __schema and __type. The two underscores mean they are meant for internal use, and you are not allowed to create types that start with two underscores. They are owned by GraphQL as a language. We also have the type schema, which is returned when you query the __schema type. The schema type then contains more fields that you can use for querying, you will see those later.

2. Implicit Introspection Types

Short description:

You can query for types and get information about specific types and their fields. The __typename is useful for differentiating runtime types. Introspection types are implicit and cannot be removed from your schema. Disabling introspection does not guarantee schema safety. GraphQL provides helpful error messages, including did you mean completions, even with introspection disabled.

For example, you can query for all the types, or even for a single type on the query object, and you will get information about that specific type, like its fields. Those are implicit, they mean they are never actually showing up in your schema, you don't have to write them yourself.

Then there is also a bunch more, and this bunch more, I think the most interesting one is the __typename, you might have used them already when you have worked with interfaces or with union types. You can use them to differentiate which actual type is returned at runtime, so you and your result can reason about which of the two or three different types available you have actually received. They are also implicit, they are not part of your schema.

Those introspection types, what does it mean that they are implicit? It means you don't have to write them, they will be there, and there is no way for you to forget about implementing them or implement them differently. Every type object will always have a fields field, and that fields field cannot be differently implemented, it is part of the implementation of the server that you are using. If you don't stick to that implementation, you basically are not spec-compliant. They give you, therefore, a standardized interface, to work with the types in your system, and you can technically disable it, but you cannot remove them implicitly from your schema. Disabling here can be done in the GraphQL.js reference implementation for example, via a so-called no-schema introspection custom rule, quite a handy name, but it does imply it is a custom rule. With that, you are actually relying on the validation phase to disallow querying the schema or type properties or the other types that are there implicitly. By disallowing querying any of them, you have effectively removed them from your schema, but please take note that it doesn't mean your schema is now safe from being inspected. GraphQL is quite helpful when it comes to errors. Within those errors, you get some did you mean completions and those completions will still show up even if you have introspection disabled. You could brute force your API to return you those names, so don't take it as a security measurement.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

From GraphQL Zero to GraphQL Hero with RedwoodJS
GraphQL Galaxy 2021GraphQL Galaxy 2021
32 min
From GraphQL Zero to GraphQL Hero with RedwoodJS
Top Content
We all love GraphQL, but it can be daunting to get a server up and running and keep your code organized, maintainable, and testable over the long term. No more! Come watch as I go from an empty directory to a fully fledged GraphQL API in minutes flat. Plus, see how easy it is to use and create directives to clean up your code even more. You're gonna love GraphQL even more once you make things Redwood Easy!
Local State and Server Cache: Finding a Balance
Vue.js London Live 2021Vue.js London Live 2021
24 min
Local State and Server Cache: Finding a Balance
Top Content
How many times did you implement the same flow in your application: check, if data is already fetched from the server, if yes - render the data, if not - fetch this data and then render it? I think I've done it more than ten times myself and I've seen the question about this flow more than fifty times. Unfortunately, our go-to state management library, Vuex, doesn't provide any solution for this.For GraphQL-based application, there was an alternative to use Apollo client that provided tools for working with the cache. But what if you use REST? Luckily, now we have a Vue alternative to a react-query library that provides a nice solution for working with server cache. In this talk, I will explain the distinction between local application state and local server cache and do some live coding to show how to work with the latter.
Batteries Included Reimagined - The Revival of GraphQL Yoga
GraphQL Galaxy 2021GraphQL Galaxy 2021
33 min
Batteries Included Reimagined - The Revival of GraphQL Yoga
The Guild has recently released Envelop - a new, modern GraphQL Server Framework and plugin system. In this talk I’ll share a brief overview of Envelop and why you should probably upgrade your existing GraphQL server to it.
Rock Solid React and GraphQL Apps for People in a Hurry
GraphQL Galaxy 2022GraphQL Galaxy 2022
29 min
Rock Solid React and GraphQL Apps for People in a Hurry
In this talk, we'll look at some of the modern options for building a full-stack React and GraphQL app with strong conventions and how this can be of enormous benefit to you and your team. We'll focus specifically on RedwoodJS, a full stack React framework that is often called 'Ruby on Rails for React'.
Step aside resolvers: a new approach to GraphQL execution
GraphQL Galaxy 2022GraphQL Galaxy 2022
16 min
Step aside resolvers: a new approach to GraphQL execution
Though GraphQL is declarative, resolvers operate field-by-field, layer-by-layer, often resulting in unnecessary work for your business logic even when using techniques such as DataLoader. In this talk, Benjie will introduce his vision for a new general-purpose GraphQL execution strategy whose holistic approach could lead to significant efficiency and scalability gains for all GraphQL APIs.

Workshops on related topic

Build with SvelteKit and GraphQL
GraphQL Galaxy 2021GraphQL Galaxy 2021
140 min
Build with SvelteKit and GraphQL
Top Content
Featured WorkshopFree
Scott Spence
Scott Spence
Have you ever thought about building something that doesn't require a lot of boilerplate with a tiny bundle size? In this workshop, Scott Spence will go from hello world to covering routing and using endpoints in SvelteKit. You'll set up a backend GraphQL API then use GraphQL queries with SvelteKit to display the GraphQL API data. You'll build a fast secure project that uses SvelteKit's features, then deploy it as a fully static site. This course is for the Svelte curious who haven't had extensive experience with SvelteKit and want a deeper understanding of how to use it in practical applications.

Table of contents:
- Kick-off and Svelte introduction
- Initialise frontend project
- Tour of the SvelteKit skeleton project
- Configure backend project
- Query Data with GraphQL
- Fetching data to the frontend with GraphQL
- Styling
- Svelte directives
- Routing in SvelteKit
- Endpoints in SvelteKit
- Deploying to Netlify
- Navigation
- Mutations in GraphCMS
- Sending GraphQL Mutations via SvelteKit
- Q&A
End-To-End Type Safety with React, GraphQL & Prisma
React Advanced Conference 2022React Advanced Conference 2022
95 min
End-To-End Type Safety with React, GraphQL & Prisma
Featured WorkshopFree
Sabin Adams
Sabin Adams
In this workshop, you will get a first-hand look at what end-to-end type safety is and why it is important. To accomplish this, you’ll be building a GraphQL API using modern, relevant tools which will be consumed by a React client.
Prerequisites: - Node.js installed on your machine (12.2.X / 14.X)- It is recommended (but not required) to use VS Code for the practical tasks- An IDE installed (VSCode recommended)- (Good to have)*A basic understanding of Node.js, React, and TypeScript
GraphQL for React Developers
GraphQL Galaxy 2022GraphQL Galaxy 2022
112 min
GraphQL for React Developers
Featured Workshop
Roy Derks
Roy Derks
There are many advantages to using GraphQL as a datasource for frontend development, compared to REST APIs. We developers in example need to write a lot of imperative code to retrieve data to display in our applications and handle state. With GraphQL you cannot only decrease the amount of code needed around data fetching and state-management you'll also get increased flexibility, better performance and most of all an improved developer experience. In this workshop you'll learn how GraphQL can improve your work as a frontend developer and how to handle GraphQL in your frontend React application.
Build a Headless WordPress App with Next.js and WPGraphQL
React Summit 2022React Summit 2022
173 min
Build a Headless WordPress App with Next.js and WPGraphQL
Top Content
WorkshopFree
Kellen Mace
Kellen Mace
In this workshop, you’ll learn how to build a Next.js app that uses Apollo Client to fetch data from a headless WordPress backend and use it to render the pages of your app. You’ll learn when you should consider a headless WordPress architecture, how to turn a WordPress backend into a GraphQL server, how to compose queries using the GraphiQL IDE, how to colocate GraphQL fragments with your components, and more.
Relational Database Modeling for GraphQL
GraphQL Galaxy 2020GraphQL Galaxy 2020
106 min
Relational Database Modeling for GraphQL
Top Content
WorkshopFree
Adron Hall
Adron Hall
In this workshop we'll dig deeper into data modeling. We'll start with a discussion about various database types and how they map to GraphQL. Once that groundwork is laid out, the focus will shift to specific types of databases and how to build data models that work best for GraphQL within various scenarios.
Table of contentsPart 1 - Hour 1      a. Relational Database Data Modeling      b. Comparing Relational and NoSQL Databases      c. GraphQL with the Database in mindPart 2 - Hour 2      a. Designing Relational Data Models      b. Relationship, Building MultijoinsTables      c. GraphQL & Relational Data Modeling Query Complexities
Prerequisites      a. Data modeling tool. The trainer will be using dbdiagram      b. Postgres, albeit no need to install this locally, as I'll be using a Postgres Dicker image, from Docker Hub for all examples      c. Hasura
Building GraphQL APIs on top of Ethereum with The Graph
GraphQL Galaxy 2021GraphQL Galaxy 2021
48 min
Building GraphQL APIs on top of Ethereum with The Graph
WorkshopFree
Nader Dabit
Nader Dabit
The Graph is an indexing protocol for querying networks like Ethereum, IPFS, and other blockchains. Anyone can build and publish open APIs, called subgraphs, making data easily accessible.

In this workshop you’ll learn how to build a subgraph that indexes NFT blockchain data from the Foundation smart contract. We’ll deploy the API, and learn how to perform queries to retrieve data using various types of data access patterns, implementing filters and sorting.

By the end of the workshop, you should understand how to build and deploy performant APIs to The Graph to index data from any smart contract deployed to Ethereum.