What GraphQL is and why it exists

Beginner · 11 min

GraphQL is a typed query language for APIs where the client names the fields it wants, from the problem it solved at Facebook to a first run in graphql-js.

Net Ninja · 11 min

What GraphQL is and why it exists

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

Taught by Net NinjaReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • GraphQL is a query language for APIs plus a runtime that executes those queries against a typed schema; it is a specification, not a database or a library.
  • The client writes the shape of the response, and the response comes back in exactly that shape, so the client gets neither more nor fewer fields than it asked for.
  • A GraphQL service has three working parts: a schema that describes what exists, resolvers that fetch it, and a query that picks from it.
  • Fields that exist on the server but not in the schema are unreachable, so the schema is also the boundary of what the API exposes.
  • GraphQL does not dictate transport or storage; most servers speak it over a single HTTP endpoint and fetch data from anywhere.

The problem it was built for

Imagine a phone app with a profile screen. It needs the user’s name, an avatar, and the titles of their three latest posts. In a classic HTTP API that is usually GET /users/42 and then GET /users/42/posts. The first response also carries twenty fields the screen never shows. The second returns full post bodies when you wanted titles.

Two things go wrong here. You download more than you need (over-fetching), and you make more requests than you want (under-fetching, because one endpoint did not hold everything). The fix on the server side is a new endpoint shaped like that exact screen, and then another for the tablet layout, and another when the design team changes the profile page.

GraphQL came out of Facebook’s mobile work around 2012 and was open-sourced in 2015. Its idea is to move the choice of shape from the server to the client. The server publishes what it can provide. Each client says what it wants.

Think of it as the difference between a set menu and ordering from a kitchen that publishes its ingredients. The kitchen still decides what is possible. You decide the plate.

Three parts

A GraphQL service is built from three things, and each gets its own lesson later.

  1. A schema. A typed description of every kind of object, every field on it, and how you can enter the graph. You will write one in schema definition language.
  2. Resolvers. Functions that know how to fetch each field. They are where your database or other services get called.
  3. A query. A string the client sends, naming the fields it wants.

The “graph” in the name comes from the schema: a book has an author, an author has books, and a query can walk those links as far as you let it.

A first run

Install graphql (I used 17.1.0 on Node 26) and run this as an ES module. It builds a schema, supplies data, and executes a query. No server and no HTTP, just the reference implementation:

import { buildSchema, graphql } from 'graphql'

const schema = buildSchema(`
  type Author { name: String! }
  type Book { title: String! year: Int author: Author! }
  type Query { book(id: ID!): Book }
`)

const rootValue = {
  book: ({ id }) => ({
    title: 'The Dispossessed',
    year: 1974,
    author: { name: 'Ursula K. Le Guin' },
    pageCount: 387, // exists on the server, never in the schema
  }),
}

const result = await graphql({
  schema,
  rootValue,
  source: `{ book(id: "10") { title author { name } } }`,
})
console.log(JSON.stringify(result))

Output:

{"data":{"book":{"title":"The Dispossessed","author":{"name":"Ursula K. Le Guin"}}}}

Read the query and the result side by side. The query asked for title and author { name }. The result has exactly those, nested the same way. year was available and was not requested, so it is not there. pageCount is on the object in memory but not in the schema, so no client can ever reach it.

That last point matters. The schema is both documentation and a gate. If it is not declared, it is not part of the API.

Types make it checkable

Because every field has a type, the server can check a query before running anything. Ask for a field that does not exist:

{ book(id: "10") { title isbn } }

The server answers without calling a resolver:

{"errors":[{"message":"Cannot query field \"isbn\" on type \"Book\".","locations":[{"line":1,"column":26}]}]}

That is the output of the script above with that query, on graphql-js 17.1.0. The same type information is what powers editor autocompletion, generated TypeScript types, and API explorers. You will meet those in later lessons.

What GraphQL does not say

It is easy to read too much into the name.

  • It is not a database query language. There is no WHERE or JOIN. A resolver might run SQL, call a REST service, or read a file. The query language only describes which fields come back.
  • It is not tied to HTTP or JSON. In practice almost everyone uses one HTTP endpoint and JSON, which the GraphQL over HTTP lesson covers, but the language itself says nothing about transport.
  • It does not replace thinking about your API. A badly shaped schema is as hard to use as a badly shaped set of endpoints, which the schema design group returns to.
  • It does not make slow data fast. A query that makes the server hit twenty tables is still doing that work. It just does it behind one request.

What the video covers

Net Ninja’s first video in his GraphQL Crash Course is titled “What is GraphQL?” and runs about ten minutes. Its description says the series covers setting up a GraphQL server and making queries and mutations; I could not read a transcript or chapters for this part, so treat the video as an introduction to the idea and the terms, then use this lesson to run something yourself. It was published in 2023 and uses Apollo Server in later parts, which is one of several servers you will meet. The runner-up is Fireship’s 100-second version if you want the shortest possible orientation.

Where this fits

This lesson names the idea. The next question is the one everyone asks: how does it compare to what you already use? Next: GraphQL vs REST.

Check yourself

  1. 01What problem with fixed endpoints was GraphQL designed to remove?

    The server decides each response's shape, so a screen either receives fields it does not need or has to make extra requests to get fields it does, and the client cannot change that without a new endpoint.

  2. 02Is GraphQL a database technology?

    No. It is a specification for a query language and its execution rules, and the data behind it can live in SQL, a document store, another API, or memory.

  3. 03What happens if a client asks for a field that is not in the schema?

    The server rejects the query during validation with an error such as Cannot query field on type, before any resolver runs.

  4. 04Where does the shape of the response come from?

    From the query. The selection set of the query is mirrored one to one in the data object of the response.

Go deeper

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