Skip to content
Tutorials Center
My learning

Topics

Lesson 84 of 119 ยท Spring Boot

GraphQL with Spring

Learn how GraphQL schemas, queries and resolvers work by building a mini executor, then use Spring for GraphQL with @QueryMapping, @SchemaMapping and batching.

A REST API gives every resource a fixed shape. GET /books/2 returns whatever the server decided a book looks like. A mobile screen that needs only the title wastes bandwidth, and a screen that needs the book and its author and the author's other books needs three round trips. Teams answer this with more endpoints (/books/2/with-author), and the API slowly becomes a pile of special cases.

GraphQL turns this around. The server publishes a typed schema describing what exists. The client sends a query naming exactly the fields it wants, in the shape it wants them, and gets back JSON with exactly that shape, in a single request. This lesson explains the three core ideas (schema, queries, resolvers) by building a tiny GraphQL executor in plain Java you can run, then shows how Spring for GraphQL maps the same ideas onto annotated controller methods. It assumes you know REST controllers and Spring Data JPA.

The schema

A GraphQL service is described by a schema written in the Schema Definition Language (SDL). It declares object types, their fields and the entry points:

GRAPHQL
type Query {
  book(id: ID!): Book
  books: [Book!]!
}

type Mutation {
  addBook(input: NewBook!): Book!
}

type Book {
  id: ID!
  title: String!
  year: Int
  author: Author!
}

type Author {
  id: ID!
  name: String!
  books: [Book!]!
}

input NewBook {
  title: String!
  year: Int
  authorId: ID!
}

String, Int, Float, Boolean and ID are the built-in scalars. A ! means non-null, and [Book!]! is a non-null list of non-null books. The special type Query lists everything a client can read, and Mutation lists the operations that change data. An input type is how a client sends structured arguments.

There is usually one endpoint (POST /graphql) for everything. Because the schema is typed, tools can validate queries before they run, generate client code and autocomplete fields.

Queries and resolvers

A query is a tree of field selections. The server walks the tree, and for each field it runs a resolver: a function that produces the value for that field from its parent object.

flowchart TD
  Q["query { book(id: 2) { title author { name } } }"] --> P["Parse and validate against the schema"]
  P --> R1["Resolver Query.book(id) returns a Book"]
  R1 --> R2["Default resolver Book.title"]
  R1 --> R3["Resolver Book.author returns an Author"]
  R3 --> R4["Default resolver Author.name"]
  R2 --> J["Assemble JSON: only requested fields"]
  R4 --> J

Each field has a resolver. Simple fields use a default (read the property); relationships use your own code.

The next example is a miniature GraphQL engine. It has a tokenizer, a parser for selection sets with arguments, a table of resolvers and a type map playing the role of the schema. Real engines (graphql-java, which Spring uses) do much more, but the execution model is the same. Read the output carefully: every response contains exactly the fields that were asked for:

Java A mini GraphQL executor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Three things to notice. The fourth query follows relationships in both directions (book to author to books) in one request, which would need several REST calls. The unknown book returns null rather than an error, because the schema says book is nullable. And asking for a field that does not exist produces an errors entry; a real server rejects this during validation, before any resolver runs. GraphQL always answers with HTTP 200 and a JSON body containing data and, when something went wrong, errors.

The N+1 problem and batching

Resolvers run per object. If books returns 100 books and each Book.author resolver runs one SQL query, you execute 101 queries: the classic N+1 problem, familiar from JPA fetching. GraphQL makes it easy to trigger accidentally, because the client decides which fields are requested.

The cure is batching. Each resolver says which author it needs (a key); a loader collects all keys requested in the same level of the query and loads them with one query. Java GraphQL libraries call this a DataLoader. The example builds one in a dozen lines:

Java From 5 queries to 2 with a batch loader

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice that the loader asked for author 1 twice but loaded it once: keys are de-duplicated. With 1,000 books the naive version runs 1,001 queries and the batched one still runs two.

Spring for GraphQL

Spring for GraphQL (dependency spring-boot-starter-graphql, built on graphql-java) turns the ideas above into annotations that look like the controllers you already know. It reads every *.graphqls file under src/main/resources/graphql/, serves POST /graphql, and matches controller methods to schema fields by name:

Java
record NewBook(String title, Integer year, String authorId) {}

@Controller
class BookGraphqlController {

    private final BookRepository books;
    private final AuthorRepository authors;

    BookGraphqlController(BookRepository books, AuthorRepository authors) {
        this.books = books;
        this.authors = authors;
    }

    @QueryMapping                                   // Query.book
    Optional<Book> book(@Argument String id) {
        return books.findById(id);
    }

    @QueryMapping                                   // Query.books
    List<Book> books() {
        return books.findAll();
    }

    @SchemaMapping                                  // Book.author, called only if the client asks for it
    Author author(Book book) {
        return authors.findById(book.authorId()).orElseThrow();
    }

    @MutationMapping                                // Mutation.addBook
    Book addBook(@Argument NewBook input) {
        return books.save(new Book(null, input.title(), input.year(), input.authorId()));
    }
}

@QueryMapping is a shortcut for @SchemaMapping(typeName = "Query"), and the method name selects the field. A parameter that is a Book tells Spring this is a field of Book, with the parent object passed in. @Argument binds query arguments (and input objects) to Java types, much like @RequestParam and @RequestBody. Fields such as title or year need no code: the default resolver reads the matching property. Returning Optional.empty() or null gives a GraphQL null.

To avoid N+1, replace the per-book resolver with a batch mapping. Spring calls it once with all the parent objects of the current level and expects a map back:

Java
@BatchMapping                                       // Book.author for the whole list at once
Map<Book, Author> author(List<Book> bookList) {
    Set<String> ids = bookList.stream().map(Book::authorId).collect(Collectors.toSet());
    Map<String, Author> byId = authors.findAllById(ids).stream()
            .collect(Collectors.toMap(Author::id, a -> a));
    return bookList.stream().collect(Collectors.toMap(b -> b, b -> byId.get(b.authorId())));
}

Enable the in-browser explorer for development with spring.graphql.graphiql.enabled=true and open /graphiql. Keep it off in production, together with schema introspection if the API is not public.

Errors, security and limits

An exception in a resolver becomes an entry in errors while the rest of the data is still returned. By default Spring hides internal details; customize the mapping with a DataFetcherExceptionResolverAdapter. Secure fields and mutations with method security (@PreAuthorize on the controller methods), as covered in Spring Security. Because clients write the queries, a hostile client can write an expensive one, such as authors, their books, those books' authors and so on, ten levels deep. Production services therefore set query depth and complexity limits and a request timeout, and do not expose unbounded lists: use pagination (first/after cursor "connections", which Spring can generate from Window results of Spring Data).

Testing

@GraphQlTest(BookGraphqlController.class) loads only the GraphQL layer, and GraphQlTester runs documents against it without HTTP:

Java
@GraphQlTest(BookGraphqlController.class)
class BookGraphqlControllerTest {

    @Autowired GraphQlTester graphQl;
    @MockitoBean BookRepository books;
    @MockitoBean AuthorRepository authors;

    @Test
    void returnsTitleOnly() {
        when(books.findById("b2")).thenReturn(Optional.of(new Book("b2", "Dune", 1965, "a2")));

        graphQl.document("{ book(id: \"b2\") { title } }")
                .execute()
                .path("book.title").entity(String.class).isEqualTo("Dune");
    }
}

For deciding between the styles: choose GraphQL when many different clients need different slices of a connected graph; choose REST (see REST API design) when resources are simple, HTTP caching matters, or the API is consumed by many third parties who expect conventional endpoints.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a GraphQL client send to choose which data comes back?

    The query is a tree of field selections, and the response has the same shape. Usually there is one endpoint for everything.
  2. 2. In the schema, what does the type [Book!]! mean?

    Each ! means non-null. The outer one applies to the list, the inner one to its elements.
  3. 3. Why does a resolver per book for Book.author often cause performance problems?

    Resolvers run per parent object. A DataLoader or Spring's @BatchMapping collects the keys and loads them with a single query.
  4. 4. In Spring for GraphQL, how is a controller method connected to a schema field?

    The method name (or the annotation's name attribute) selects the field, and the annotation or the parameter type selects the parent type.
  5. 5. Which HTTP status does a GraphQL server normally use when a resolver throws an exception?

    GraphQL reports field errors in the response body. HTTP-level errors are reserved for transport problems such as authentication failures or malformed requests.

Summary

  • A GraphQL schema describes types, fields and entry points (Query, Mutation); clients send queries that select exactly the fields they need and get JSON of the same shape.
  • Every field has a resolver; plain properties use a default resolver and relationships use your own code. Responses contain data and optionally errors.
  • Per-object resolvers cause N+1 queries; batch them with a DataLoader or @BatchMapping.
  • Spring for GraphQL maps *.graphqls files to controllers with @QueryMapping, @MutationMapping, @SchemaMapping and @Argument, and tests them with @GraphQlTest.
  • Protect public APIs with authorization, depth and complexity limits, pagination and a disabled GraphiQL/introspection setup in production.

Next: Server-side Views with Thymeleaf returns to classic HTML pages rendered on the server.