TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท web ยท apis ยท graphql

GraphQL

A query language and runtime for APIs. A typed schema describes all the data, and each client sends one request, usually a POST to a single endpoint, naming exactly the fields it wants back.

15 min6 animations

๐Ÿ“š Builds on๐Ÿ“ฎ HTTP๐Ÿฌ REST API design

๐Ÿ–จ๏ธ Cheat sheet

One form, one box

Mia wants lunch: some rice, a piece of fish and one sweet. At the old food hall she queues at the rice counter, then the fish counter, then the sweets counter. Each counter only sells its own fixed tray, so she also gets soup, pickles and a salad she never wanted. Three queues, and half the food goes to waste.

The bento shop works differently. There is one window and one order form. Mia ticks exactly the three things she wants, hands in the form once, and gets back one box with three compartments, filled with exactly what she ticked. Behind the window, helpers fetch each item from the right counter. Nothing missing, nothing extra.

That's GraphQL: the shopper says exactly what goes in the box, instead of taking whatever each counter's tray holds.

Ask for exactly the fields you need

GraphQL is a query language for APIs plus a runtime that executes it. Instead of many endpoints that each return a fixed shape, a GraphQL server exposes one endpoint and the client describes the shape of the response it wants:

1query {2  user(id: "7") {3    name4    orders(last: 3) { dish }5    reviews { stars }6  }7}

The response is JSON with the same shape as the query, under a data key. That fixes two common problems of resource-based HTTP APIs (REST):

  • Over-fetching: GET /users/7 returns the whole user, twenty fields, when the screen needs one.
  • Under-fetching: the screen also needs orders and reviews, so the client makes more round trips (/users/7/orders, /users/7/reviews), often one after another.

The trade-off is that the server now runs whatever combination of fields clients ask for, which moves work (and risk) from the client to the server. REST is still simpler for plain resources, file downloads and anything that benefits from HTTP caching; GraphQL shines when many different screens need different slices of connected data.

One order instead of three queues5 steps
๐Ÿ™‹Mia๐ŸšRice counter๐ŸŸFish counter๐ŸกSweets counter
Press play and watch it happen!

The printed menu

Next to the window hangs a printed menu, called the schema. It lists every box you can order and every item that can go in each compartment, and what kind of thing each item is: a number of pieces, a word, a yes or no. If it isn't on the menu, you can't order it.

So when Mia ticks "dragon roll", which the shop has never made, the window hands the form straight back before anyone starts cooking. And anyone can ask the window for a copy of the menu, so new customers can see what exists.

The menu has three sections. The first is for getting food. The second is for changes, such as "save this box as my favourite". The third is for "tell me whenever there's a new special", and the shop keeps shouting to Mia each time one comes out.

The schema, mutations and subscriptions

Every GraphQL API is described by a schema, usually written in the Schema Definition Language (SDL):

1type Query {2  user(id: ID!): User3}4 5type Mutation {6  saveFavourite(dishId: ID!): User!7}8 9type Subscription {10  newSpecial: Dish!11}12 13type User {14  id: ID!15  name: String!16  orders(last: Int): [Order!]!17}

Object types have fields, and every field has a type: scalars (Int, Float, String, Boolean, ID), other object types, lists [T], and ! for non-null. Enums, interfaces, unions and input types complete the type system.

Three root types are the entry points. Query fields read. Mutation fields change data; top-level mutation fields in one request run one after another, in order. Subscription fields deliver a stream of results over a long-lived connection, typically a WebSocket or server-sent events.

Every request is validated against the schema before anything runs: an unknown field or a wrong argument type is rejected with an error and no data. The schema is also queryable through introspection (__schema, __type), which is what powers autocompletion in tools like GraphiQL and code generators.

The schema decides what can be asked4 steps
๐Ÿ™‹Mia๐ŸชŸOrder window๐Ÿ“œ Printed menu๐Ÿฅซ Storeroom
Press play and watch it happen!

Kitchen stations

Behind the window, the box isn't filled by one cook. Each compartment has its own station, called a resolver: the fish station fills the fish, the sweets station fills the sweet.

The head cook reads the form from the top. First the account desk finds Mia's account, then each station gets told "this is for Mia" and fills its compartment. Simple things, like writing Mia's name on the lid, need no station at all: it's already on her account card. When every compartment is full, the box goes out.

Resolvers, field by field

The server executes a query by calling a resolver (in graphql-java, a DataFetcher) for each field. Execution starts at the root: Query.user runs first and returns a user object. Then each selected child field is resolved with that object as its parent (source): User.orders and User.reviews each receive the user and fetch their own data, possibly from different databases or services.

Fields without a custom resolver use a default resolver, which reads a property of the same name from the parent object, so name simply becomes user.getName(). The engine assembles the results into a response that mirrors the query.

Because each field resolves independently, a GraphQL server is a natural place to stitch together several backends. It also means one innocent-looking query can trigger a lot of calls, which is the next topic.

A resolver for every field4 steps
๐Ÿ™‹Mia๐Ÿง‘โ€๐ŸณHead cook๐Ÿ—‚๏ธAccount desk๐ŸŸFish station๐ŸกSweets station
Press play and watch it happen!

One trip to the storeroom

Ten customers each order a box with fish. The fish station gets ten tickets. A careless cook walks to the storeroom for the first piece of fish, comes back, walks again for the second, and so on: ten trips, plus the one to find the orders in the first place.

A smart shop has a runner, called a DataLoader. Each ticket tells the runner "I need fish number 3". The runner waits a moment, collects all ten requests, makes one trip with one list, and hands each station its piece. Two trips instead of eleven.

The N+1 problem and DataLoader

Field-by-field resolution has a classic trap. A query for the last 10 orders and the dish of each runs one query for the orders, then Order.dish once per order: 1 + N database calls. Nested lists multiply it further.

The fix is batching. A DataLoader collects the keys requested by every Order.dish resolver during one level of execution, then calls a batch function once with all of them (WHERE id IN (...)) and hands each resolver its own result. It also caches per request, so the same key is loaded only once. The batch function must return results in the same order as the keys, or as a map keyed by them.

DataLoaders should be created per request, so their cache never leaks one user's data to another. The same problem exists with ORMs and REST; see JPA's N+1 for the database side.

From eleven trips to two4 steps
๐Ÿ‘ฅTen customers๐ŸŸFish station๐Ÿฅซ Storeroom
Press play and watch it happen!

One window, sealed forms

Every order goes through the same window, on a folded form. That makes life hard for the shop's ready-made shelf, a cache where popular boxes wait already packed: the shelf can't see inside a folded form, so it can't tell that two forms ask for the same box. The fix is a numbered set order: "the usual, number 12". A number on the outside is easy for the shelf to recognise.

If one compartment can't be filled, the shop doesn't send the whole box back. You get the box with that compartment empty and a note tucked inside: "sorry, no fish today". So always read the note, even when the box arrives.

And the window refuses silly forms, like a box inside a box inside a box, a hundred times over, which would keep every station busy all day.

GraphQL over HTTP: caching, errors and limits

Most GraphQL APIs use a single endpoint such as /graphql, with the query sent as JSON in a POST body: query, operationName and variables. Because the URL never changes and POST responses aren't cached by default, browser and CDN caching (Cache-Control, ETag) doesn't work out of the box. Clients make up for it with normalized caches keyed by type and id (Apollo Client, Relay).

Persisted queries restore HTTP caching: the client sends a hash or id of a query the server already knows, often as a GET with the id and variables in the URL, so CDNs can cache it when the response carries Cache-Control (Spring for GraphQL accepts GET only once you enable it). They also shrink requests, and an allow-list of persisted queries can block every query you didn't ship.

Errors don't map to status codes the way REST does. Once the operation executes, the reply is a success status (in practice 200 OK, which is what Spring for GraphQL sends) even if some fields failed. Each failed field is null in data (or, if the field is non-null, its nearest nullable parent is), and an errors array explains each one with a message, a path and often extensions.code. Clients must check errors, not just the status. A body that isn't valid JSON gets a 400. A query that fails to parse or validate gets a 4xx when the client accepts the newer application/graphql-response+json media type, but still a 200 with plain application/json.

Safety limits matter because clients write the queries: cap query depth and query complexity (a cost per field, multiplied by list sizes), set timeouts and pagination limits, and consider disabling introspection on public production APIs.

One endpoint over HTTP5 steps
๐Ÿ™‹Mia๐Ÿ—„๏ธReady-made shelf๐ŸชŸOrder window
Press play and watch it happen!

A bento shop in Java

In a Java shop, the manager doesn't wire up every station by hand. They pin the printed menu on the wall and stick a label, called an annotation, on each cook: "you make the boxes". The fish cook's label says "fill all the fish compartments in one go", so that cook gets every waiting box at once, just like the runner.

Spring for GraphQL

Spring for GraphQL builds on graphql-java. Spring Boot loads schema files (.graphqls or .gqls) from src/main/resources/graphql/ and exposes the API at POST /graphql by default. Resolvers are methods on a @Controller:

1// interface AuthorRepository extends ListCrudRepository<Author, String> {}2 3@Controller4class BookController {5 6    private final BookRepository books;7    private final AuthorRepository authors;8 9    BookController(BookRepository books, AuthorRepository authors) {10        this.books = books;11        this.authors = authors;12    }13 14    @QueryMapping                       // Query.books15    List<Book> books() {16        return books.findAll();17    }18 19    @QueryMapping                       // Query.bookById(id: ID!)20    Optional<Book> bookById(@Argument String id) {21        return books.findById(id);22    }23 24    @MutationMapping                    // Mutation.addBook25    Book addBook(@Argument String title, @Argument String authorId) {26        return books.save(new Book(null, title, authorId));27    }28 29    @BatchMapping                       // Book.author, once for all books30    Map<Book, Author> author(List<Book> bookList) {31        var ids = bookList.stream().map(Book::authorId).toList();32        var byId = authors.findAllById(ids).stream()33                .collect(Collectors.toMap(Author::id, a -> a));34        return bookList.stream()35                .filter(b -> byId.containsKey(b.authorId()))36                .collect(Collectors.toMap(b -> b, b -> byId.get(b.authorId())));37    }38}

@QueryMapping and @MutationMapping bind a method to a field of Query or Mutation, named after the method unless you say otherwise. @SchemaMapping binds any field of any type: @SchemaMapping(typeName = "Book", field = "author") on Author author(Book book) would be called once per book, the N+1 pattern. @BatchMapping registers a DataLoader for you and is called once per batch with all the parent objects; it returns a Map from parent to value, or a List in the same order.

๐Ÿ”ง Going deeper

Introspection in production: Spring Boot has introspection on by default (tools need it). Set spring.graphql.schema.introspection.enabled=false to hide the schema on a public API. Disabling it isn't security on its own: your shipped client code still reveals the queries it sends, so every field still needs its own authorization check.

Depth and complexity: graphql-java ships MaxQueryDepthInstrumentation and MaxQueryComplexityInstrumentation. Expose one as a bean and Spring Boot adds it to the engine, so a query nested deeper than the limit is rejected before any resolver runs.

Errors: an exception thrown in a controller becomes an entry in errors. If nothing resolves it, Spring reports a generic INTERNAL_ERROR with only an execution id, on purpose, so internal details don't leak. To turn your own exceptions into clear messages and classifications such as NOT_FOUND, implement a DataFetcherExceptionResolver, or (since Spring for GraphQL 1.2) write a @GraphQlExceptionHandler method in a controller or @ControllerAdvice.

Spring for GraphQL controllers4 steps
๐Ÿ™‹Mia๐ŸชŸOrder window๐Ÿ“œ Printed menu๐Ÿง‘โ€๐ŸณBox cook๐ŸŸFish cook
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about GraphQL, told the same way as the story.
  1. At the old food hall, Mia gets soup and salad she never asked for, then queues at two more counters. What does the bento form fix?
  2. Ten boxes each need fish, and the cook walks to the storeroom once per box. What's the fix?
  3. Mia's box arrives, but one compartment is empty. What should she do?
  4. Mia ticks a dragon roll, which isn't on the printed menu. What happens?
  5. Why does the window refuse a box inside a box inside a box, a hundred times over?
Answer every question to check.Passing marks GraphQL as done.
Got the hang of GraphQL? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿ”Œ Designing APIsStep 3 of 5

โ† Previous on the path๐Ÿฌ REST API designNext on the path โ†’๐ŸŽง gRPC and Protocol Buffers