Spring for GraphQL: schema-first APIs

Spring for GraphQL connects a GraphQL schema to annotated controller methods, on top of graphql-java. The schema decides what clients may ask for, and your methods supply the data field by field. This page explains that model, then runs complete Spring Boot 4.1 applications over HTTP: queries, mutations, batch loading, errors, schema inspection and the Java client.

Contents

How a GraphQL request is executed

A REST API offers fixed endpoints, each returning a fixed shape. A GraphQL API offers one endpoint and a typed schema, and each request is a query that names exactly the fields the client wants, however deeply nested. The server answers with JSON in the same shape as the query.

Spring for GraphQL builds on graphql-java, the engine that parses, validates and executes queries. Spring adds the HTTP and WebSocket transports, the connection between schema fields and your methods, and Spring Boot auto-configuration. A request goes through these steps:

  1. The transport, here Spring MVC at POST /graphql, reads the JSON body with query, variables and operationName.
  2. graphql-java parses the query and validates it against the schema. A field that does not exist, or an argument of the wrong type, is rejected before any of your code runs.
  3. Execution walks the query field by field. Each field has a data fetcher; for fields mapped with @QueryMapping or @SchemaMapping, the data fetcher calls your method. Fields without a mapping read a property of the parent object with the same name.
  4. The results, and any errors, are written as {"data": ..., "errors": [...]}, normally with HTTP status 200 even when errors occurred.
Controller annotations in Spring for GraphQL
AnnotationMaps a method toBest for
@QueryMappingA field of QueryEntry points for reading
@MutationMappingA field of MutationWrites
@SubscriptionMappingA field of Subscription, returning a FluxStreams over WebSocket or SSE
@SchemaMappingA field of any type, called once per parent objectCheap derived or related fields
@BatchMappingA field of any type, called once for all parentsRelated data from a database or service
@ArgumentA method parameter bound from a field argumentArguments and input types

The examples are Spring Boot 4.1 applications with spring-boot-starter-graphql and spring-boot-starter-webmvc, which bring Spring for GraphQL 2.0 and graphql-java 25. Each starts Tomcat on a random port and sends GraphQL requests to itself. In a real project the schema lives in src/main/resources/graphql/ as .graphqls files, where Boot finds it on its own; to keep each program in one file, the schema here is a text block registered with a GraphQlSourceBuilderCustomizer bean.

A first schema and queries

The book schema has two queries and a Book type. The controller returns plain Java records, and the program sends five requests as raw JSON, to show what goes over the wire:

Java
package demo.graphql.first;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.graphql.autoconfigure.GraphQlSourceBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.stereotype.Controller;

@SpringBootApplication
public class FirstQuery {

    // usually src/main/resources/graphql/schema.graphqls; inline here to keep one file
    static final String SCHEMA = """
            type Query {
                books: [Book!]!
                book(id: ID!): Book
            }
            type Book {
                id: ID!
                title: String!
                pages: Int
                year: Int
            }
            """;

    record Book(String id, String title, int pages, int year) { }

    @Bean
    GraphQlSourceBuilderCustomizer schema() {
        return builder -> builder.schemaResources(new ByteArrayResource(SCHEMA.getBytes()));
    }

    @Controller
    static class BookController {
        private final List<Book> books = List.of(new Book("1", "Dune", 412, 1965),
                new Book("2", "Emma", 474, 1815));

        @QueryMapping
        List<Book> books() {
            return books;
        }

        @QueryMapping
        Book book(@Argument String id) {
            return books.stream().filter(b -> b.id().equals(id)).findFirst().orElse(null);
        }
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(FirstQuery.class);
        app.setDefaultProperties(Map.of("server.port", "0",
                "spring.main.banner-mode", "off", "logging.level.root", "WARN"));
        try (var context = app.run(args)) {
            String url = "http://localhost:"
                    + context.getEnvironment().getProperty("local.server.port") + "/graphql";
            post(url, "{\"query\": \"{ books { title } }\"}");
            post(url, "{\"query\": \"{ books { id title year } }\"}");
            post(url, "{\"query\": \"query One($id: ID!) { book(id: $id) { title pages } }\","
                    + " \"variables\": {\"id\": \"2\"}}");
            post(url, "{\"query\": \"{ book(id: 9) { title } }\"}");
            post(url, "{\"query\": \"{ books { title isbn } }\"}");
        }
    }

    static void post(String url, String body) throws Exception {
        try (HttpClient client = HttpClient.newHttpClient()) {
            HttpResponse<String> response = client.send(HttpRequest.newBuilder(URI.create(url))
                            .header("Content-Type", "application/json")
                            .POST(HttpRequest.BodyPublishers.ofString(body)).build(),
                    HttpResponse.BodyHandlers.ofString());
            System.out.println("POST " + body);
            System.out.println("  -> " + response.statusCode() + " " + response.body());
        }
    }
}
Output
POST {"query": "{ books { title } }"}
  -> 200 {"data":{"books":[{"title":"Dune"},{"title":"Emma"}]}}
POST {"query": "{ books { id title year } }"}
  -> 200 {"data":{"books":[{"id":"1","title":"Dune","year":1965},{"id":"2","title":"Emma","year":1815}]}}
POST {"query": "query One($id: ID!) { book(id: $id) { title pages } }", "variables": {"id": "2"}}
  -> 200 {"data":{"book":{"title":"Emma","pages":474}}}
POST {"query": "{ book(id: 9) { title } }"}
  -> 200 {"data":{"book":null}}
POST {"query": "{ books { title isbn } }"}
  -> 200 {"errors":[{"message":"Validation error (FieldUndefined@[books/isbn]) : Field 'isbn' in type 'Book' is undefined","locations":[{"line":1,"column":17}],"extensions":{"classification":"ValidationError"}}]}
  • { books { title } } returned only titles. The pages and year fields exist, but the client did not ask for them, so they were not sent.
  • The second query picked three fields. id, title and year have no mapping methods: graphql-java read them from the record's accessor methods.
  • The third request used a named operation with a $id variable, passed separately in variables. Variables avoid building query strings by hand and let servers cache parsed queries.
  • Book 9 does not exist, so the method returned null, and the nullable Book type allowed "book":null without an error.
  • Asking for isbn, which is not in the schema, failed validation: there is no data at all, only an error classified as ValidationError, and the status is still 200.

The method name matches the schema field name, so @QueryMapping needs no arguments, and @Argument String id binds the argument by parameter name. That relies on the -parameters compiler flag, which the Spring Boot build plugins set; these programs are compiled with it.

The N+1 problem and @BatchMapping

Each book has an author, loaded from a repository. With @SchemaMapping, the author method runs once per book in the response: one query for the books and then N queries for their authors. The repository below counts its calls, and the schema offers the same author twice, once per approach:

Java
package demo.graphql.batch;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.graphql.autoconfigure.GraphQlSourceBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.graphql.data.method.annotation.BatchMapping;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.graphql.data.method.annotation.SchemaMapping;
import org.springframework.stereotype.Controller;

@SpringBootApplication
public class NPlusOne {

    static final String SCHEMA = """
            type Query { books: [Book!]! }
            type Book {
                title: String!
                author: Author
                authorBatched: Author
            }
            type Author { name: String! }
            """;

    record Book(String title, String authorId) { }

    record Author(String id, String name) { }

    // stands in for an author table or service; counts how often it is called
    static class AuthorRepository {
        final AtomicInteger calls = new AtomicInteger();
        private final Map<String, Author> authors = Map.of(
                "a1", new Author("a1", "Frank Herbert"), "a2", new Author("a2", "Jane Austen"));

        Author findById(String id) {
            calls.incrementAndGet();
            return authors.get(id);
        }

        List<Author> findAllById(List<String> ids) {
            calls.incrementAndGet();
            return ids.stream().distinct().map(authors::get).toList();
        }
    }

    @Bean
    GraphQlSourceBuilderCustomizer schema() {
        return builder -> builder.schemaResources(new ByteArrayResource(SCHEMA.getBytes()));
    }

    @Bean
    AuthorRepository authorRepository() {
        return new AuthorRepository();
    }

    @Controller
    static class BookController {
        private final AuthorRepository repository;

        BookController(AuthorRepository repository) {
            this.repository = repository;
        }

        @QueryMapping
        List<Book> books() {
            return List.of(new Book("Dune", "a1"), new Book("Dune Messiah", "a1"),
                    new Book("Emma", "a2"), new Book("Persuasion", "a2"),
                    new Book("Children of Dune", "a1"));
        }

        // called once per book
        @SchemaMapping
        Author author(Book book) {
            return repository.findById(book.authorId());
        }

        // called once for all books in the response
        @BatchMapping
        Map<Book, Author> authorBatched(List<Book> books) {
            Map<String, Author> byId = repository.findAllById(
                    books.stream().map(Book::authorId).toList()).stream()
                    .collect(Collectors.toMap(Author::id, Function.identity()));
            return books.stream().collect(Collectors.toMap(Function.identity(),
                    b -> byId.get(b.authorId())));
        }
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(NPlusOne.class);
        app.setDefaultProperties(Map.of("server.port", "0",
                "spring.main.banner-mode", "off", "logging.level.root", "WARN"));
        try (var context = app.run(args)) {
            String url = "http://localhost:"
                    + context.getEnvironment().getProperty("local.server.port") + "/graphql";
            AuthorRepository repository = context.getBean(AuthorRepository.class);

            String body = post(url, "{ books { title author { name } } }");
            System.out.println("@SchemaMapping: " + repository.calls.getAndSet(0)
                    + " repository calls for 5 books");
            System.out.println("  " + body);

            post(url, "{ books { title authorBatched { name } } }");
            System.out.println("@BatchMapping : " + repository.calls.getAndSet(0)
                    + " repository call for 5 books");

            post(url, "{ books { title } }");
            System.out.println("no author field requested: " + repository.calls.get()
                    + " repository calls");
        }
    }

    static String post(String url, String query) throws Exception {
        try (HttpClient client = HttpClient.newHttpClient()) {
            return client.send(HttpRequest.newBuilder(URI.create(url))
                            .header("Content-Type", "application/json")
                            .POST(HttpRequest.BodyPublishers.ofString(
                                    "{\"query\": \"" + query + "\"}")).build(),
                    HttpResponse.BodyHandlers.ofString()).body();
        }
    }
}
Output
@SchemaMapping: 5 repository calls for 5 books
  {"data":{"books":[{"title":"Dune","author":{"name":"Frank Herbert"}},{"title":"Dune Messiah","author":{"name":"Frank Herbert"}},{"title":"Emma","author":{"name":"Jane Austen"}},{"title":"Persuasion","author":{"name":"Jane Austen"}},{"title":"Children of Dune","author":{"name":"Frank Herbert"}}]}}
@BatchMapping : 1 repository call for 5 books
no author field requested: 0 repository calls
  • With @SchemaMapping, five books caused five repository calls, although only two distinct authors exist. With a real database that is five round trips, and a list of 100 books would make 100.
  • With @BatchMapping, the method received all five books at once and made one repository call for the distinct author ids. It returns a Map from each book to its author.
  • When the query did not ask for an author at all, neither method ran: zero calls. Fields are resolved only when they are requested, which is the main efficiency gain of GraphQL.

@BatchMapping is built on graphql-java's DataLoader: during execution, Spring collects the keys for a field across the whole response and calls your method once for the batch. The keys must work as Map keys, so records with correct equals and hashCode, or ids, suit them best. For the full DataLoader API, register a batch loader with BatchLoaderRegistry.

Mutations, input types and the Java client

Writes are mutations, and their arguments are usually input types: objects defined in the schema that clients send as variables. This task API adds tasks and lists them by status. It is called with HttpSyncGraphQlClient, Spring's blocking GraphQL client over RestClient, added in Spring for GraphQL 1.3:

Java
package demo.graphql.mutation;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.graphql.autoconfigure.GraphQlSourceBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.graphql.client.ClientGraphQlResponse;
import org.springframework.graphql.client.HttpSyncGraphQlClient;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.MutationMapping;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.client.RestClient;

@SpringBootApplication
public class Mutations {

    static final String SCHEMA = """
            type Query { tasks(status: Status): [Task!]! }
            type Mutation { addTask(input: NewTask!): Task! }
            enum Status { OPEN, DONE }
            input NewTask {
                title: String!
                priority: Int = 3
            }
            type Task {
                id: ID!
                title: String!
                priority: Int!
                status: Status!
            }
            """;

    enum Status { OPEN, DONE }

    record NewTask(String title, int priority) { }

    record Task(String id, String title, int priority, Status status) { }

    // a client-side view with only the fields the query selects
    record TaskTitle(String id, String title) { }

    @Bean
    GraphQlSourceBuilderCustomizer schema() {
        return builder -> builder.schemaResources(new ByteArrayResource(SCHEMA.getBytes()));
    }

    @Controller
    static class TaskController {
        private final List<Task> tasks = new ArrayList<>(List.of(
                new Task("1", "write schema", 1, Status.DONE)));

        @QueryMapping
        List<Task> tasks(@Argument Status status) {
            return tasks.stream().filter(t -> status == null || t.status() == status).toList();
        }

        // the input object is bound to the NewTask record by its field names
        @MutationMapping
        synchronized Task addTask(@Argument NewTask input) {
            Task task = new Task(String.valueOf(tasks.size() + 1), input.title(),
                    input.priority(), Status.OPEN);
            tasks.add(task);
            return task;
        }
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Mutations.class);
        app.setDefaultProperties(Map.of("server.port", "0",
                "spring.main.banner-mode", "off", "logging.level.root", "WARN"));
        try (var context = app.run(args)) {
            HttpSyncGraphQlClient client = HttpSyncGraphQlClient.create(RestClient.create(
                    "http://localhost:" + context.getEnvironment()
                            .getProperty("local.server.port") + "/graphql"));
            String add = """
                    mutation Add($input: NewTask!) {
                        addTask(input: $input) { id title priority status }
                    }""";

            Task urgent = client.document(add)
                    .variable("input", Map.of("title", "fix login bug", "priority", 1))
                    .retrieveSync("addTask").toEntity(Task.class);
            System.out.println("added: " + urgent);

            Task defaulted = client.document(add)
                    .variable("input", Map.of("title", "update docs"))
                    .retrieveSync("addTask").toEntity(Task.class);
            System.out.println("added without priority: " + defaulted);

            List<TaskTitle> open = client.document("{ tasks(status: OPEN) { id title } }")
                    .retrieveSync("tasks").toEntityList(TaskTitle.class);
            System.out.println("open tasks: " + open);

            ClientGraphQlResponse bad = client.document(add)
                    .variable("input", Map.of("priority", "high"))
                    .executeSync();
            System.out.println("invalid input, valid response: " + bad.isValid());
            bad.getErrors().forEach(e -> System.out.println("  error: " + e.getMessage()
                    + " [" + e.getErrorType() + "]"));
        }
    }
}
Output
added: Task[id=2, title=fix login bug, priority=1, status=OPEN]
added without priority: Task[id=3, title=update docs, priority=3, status=OPEN]
open tasks: [TaskTitle[id=2, title=fix login bug], TaskTitle[id=3, title=update docs]]
invalid input, valid response: false
  error: Variable 'input' has an invalid value: Field 'title' has coerced Null value for NonNull type 'String!' [ValidationError]
  • The input variable was a Map on the client and arrived as a NewTask record in the controller: @Argument binds input objects to Java types by field name.
  • The second task omitted priority, so the schema default priority: Int = 3 applied before the method was called.
  • retrieveSync("tasks").toEntityList(...) decoded one field of the response into Java objects. The query selected only id and title, so the client used a TaskTitle record with just those fields.
  • The last request sent a priority but no title, which breaks the String! rule. Validation rejected it before the controller ran, and executeSync() returned a response that is not valid, with a ValidationError.

Decoding a partial selection into the full Task record fails on the client: the missing priority arrives as null, and Jackson 3, which Spring Boot 4 uses, refuses null for a primitive int by default. Match client types to the fields each query selects, or use nullable wrapper types.

Errors and partial results

A GraphQL response can contain data and errors at the same time: one failing field does not fail the whole request. The account schema below has a lookup that can fail with our own exception, a balance that always works, and an exchange rate whose service throws an unexpected exception:

Java
package demo.graphql.errors;

import graphql.GraphQLError;
import graphql.GraphqlErrorBuilder;
import graphql.schema.DataFetchingEnvironment;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.graphql.autoconfigure.GraphQlSourceBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.graphql.execution.DataFetcherExceptionResolverAdapter;
import org.springframework.graphql.execution.ErrorType;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class ErrorHandling {

    static final String SCHEMA = """
            type Query {
                account(id: ID!): Account
                balance(id: ID!): Int
                exchangeRate: Float
            }
            type Account { id: ID!, owner: String! }
            """;

    record Account(String id, String owner) { }

    static class AccountNotFound extends RuntimeException {
        AccountNotFound(String id) {
            super("no account " + id);
        }
    }

    @Bean
    GraphQlSourceBuilderCustomizer schema() {
        return builder -> builder.schemaResources(new ByteArrayResource(SCHEMA.getBytes()));
    }

    @Controller
    static class AccountController {
        @QueryMapping
        Account account(@Argument String id) {
            if (!id.equals("1")) {
                throw new AccountNotFound(id);
            }
            return new Account("1", "Ann");
        }

        @QueryMapping
        Integer balance(@Argument String id) {
            return 250;
        }

        @QueryMapping
        Double exchangeRate() {
            throw new IllegalStateException("rates service password expired");
        }
    }

    // turns our exception into a GraphQL error with a classification and a message
    @Component
    static class NotFoundResolver extends DataFetcherExceptionResolverAdapter {
        @Override
        protected GraphQLError resolveToSingleError(Throwable ex, DataFetchingEnvironment env) {
            if (ex instanceof AccountNotFound) {
                return GraphqlErrorBuilder.newError(env).errorType(ErrorType.NOT_FOUND)
                        .message(ex.getMessage()).build();
            }
            return null; // not ours: let the next resolver or the default handle it
        }
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(ErrorHandling.class);
        app.setDefaultProperties(Map.of("server.port", "0",
                "spring.main.banner-mode", "off", "logging.level.root", "OFF"));
        try (var context = app.run(args)) {
            String url = "http://localhost:"
                    + context.getEnvironment().getProperty("local.server.port") + "/graphql";
            post(url, "{ account(id: 1) { owner } balance(id: 1) }");
            post(url, "{ account(id: 9) { owner } balance(id: 9) }");
            post(url, "{ balance(id: 1) exchangeRate }");
        }
    }

    static void post(String url, String query) throws Exception {
        try (HttpClient client = HttpClient.newHttpClient()) {
            HttpResponse<String> response = client.send(HttpRequest.newBuilder(URI.create(url))
                            .header("Content-Type", "application/json")
                            .POST(HttpRequest.BodyPublishers.ofString(
                                    "{\"query\": \"" + query + "\"}")).build(),
                    HttpResponse.BodyHandlers.ofString());
            System.out.println(query);
            // the internal error message ends with a random id; replace it to keep output stable
            System.out.println("  -> " + response.statusCode() + " " + response.body()
                    .replaceAll("[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}", "<id>"));
        }
    }
}
Output
{ account(id: 1) { owner } balance(id: 1) }
  -> 200 {"data":{"account":{"owner":"Ann"},"balance":250}}
{ account(id: 9) { owner } balance(id: 9) }
  -> 200 {"errors":[{"message":"no account 9","locations":[{"line":1,"column":3}],"path":["account"],"extensions":{"classification":"NOT_FOUND"}}],"data":{"account":null,"balance":250}}
{ balance(id: 1) exchangeRate }
  -> 200 {"errors":[{"message":"INTERNAL_ERROR for <id>","locations":[{"line":1,"column":18}],"path":["exchangeRate"],"extensions":{"classification":"INTERNAL_ERROR"}}],"data":{"balance":250,"exchangeRate":null}}
  • The first request succeeded fully, with no errors entry.
  • For account 9, the controller threw AccountNotFound. The NotFoundResolver turned it into an error with the classification NOT_FOUND, our message and the path ["account"]. The balance field still returned 250: a partial result.
  • The IllegalStateException from exchangeRate had no resolver, so Spring returned a generic INTERNAL_ERROR with an id instead of the message. The message, which mentions a password, never reached the client; the id lets you find the full exception in the server log.
  • All three responses had HTTP status 200. Clients must check the errors array, not the status code.

A DataFetcherExceptionResolverAdapter returning null passes the exception on, so several resolvers can each handle their own types. Methods annotated with @GraphQlExceptionHandler in a controller or a @ControllerAdvice class are the annotation-based alternative. ErrorType offers BAD_REQUEST, UNAUTHORIZED, FORBIDDEN, NOT_FOUND and INTERNAL_ERROR.

Schema inspection at startup

A schema and its controllers can drift apart: a field is added to the schema but never implemented, or a Java property is renamed. Such a field silently returns null. Spring for GraphQL inspects the mappings when the schema is built, and Spring Boot logs the report. This program has a schema with a field the controller does not map and two fields the Java record does not have. The log pattern is set to the message alone, so that the report prints without timestamps:

Java
package demo.graphql.inspection;

import java.util.List;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.graphql.autoconfigure.GraphQlSourceBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.graphql.execution.GraphQlSource;
import org.springframework.stereotype.Controller;

@SpringBootApplication
public class SchemaInspection {

    static final String SCHEMA = """
            type Query {
                products: [Product!]!
                featured: Product
            }
            type Product {
                sku: ID!
                name: String!
                priceCents: Int!
                rating: Float
            }
            """;

    // the Java type has no rating, and names the price differently
    record Product(String sku, String name, int price) { }

    @Bean
    GraphQlSourceBuilderCustomizer schema() {
        return builder -> builder.schemaResources(new ByteArrayResource(SCHEMA.getBytes()));
    }

    @Controller
    static class ProductController {
        @QueryMapping
        List<Product> products() {
            return List.of(new Product("p1", "lamp", 2500));
        }
        // no mapping for Query.featured
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(SchemaInspection.class);
        app.setDefaultProperties(Map.of("server.port", "0",
                "spring.main.banner-mode", "off", "logging.level.root", "WARN",
                // show only the inspection report, without timestamps
                "logging.level.org.springframework.boot.graphql", "INFO",
                "logging.pattern.console", "%msg%n"));
        try (var context = app.run(args)) {
            System.out.println("schema built: " + (context.getBean(GraphQlSource.class).schema()
                    .getQueryType() != null));
        }
    }
}
Output
GraphQL schema inspection:
	Unmapped fields: {Product=[priceCents, rating], Query=[featured]}
	Unmapped registrations: {}
	Unmapped arguments: {}
	Field nullness errors: {}
	Argument nullness errors: {}
	Skipped types: []
GraphQL endpoint HTTP POST /graphql
schema built: true
  • Query.featured is listed as unmapped: there is no @QueryMapping for it, so every request for it would return null.
  • Product.priceCents is unmapped because the record calls it price, and Product.rating has no Java counterpart at all. The inspector found this by comparing the schema with the return type of products().
  • The other categories, such as unmapped arguments and nullness errors, are empty here.

The report is on by default (spring.graphql.schema.inspection.enabled). It is only a log entry, so it is easy to overlook; check it in a test, or read it after every schema change. Boot also logs the endpoint path, /graphql, which spring.graphql.http.path changes.

Production settings and security

A few Spring Boot settings matter once a GraphQL API is public. The values below were checked against the Spring Boot 4.1 configuration metadata:

  • GraphiQL: the in-browser query editor is off by default; spring.graphql.graphiql.enabled=true serves it at /graphiql. Enable it only where it is wanted.
  • Introspection: clients can ask the API for its own schema. spring.graphql.schema.introspection.enabled=false turns that off for public APIs that should not reveal their schema.
  • Schema printing: spring.graphql.schema.printer.enabled=true serves the schema at /graphql/schema.
  • Security: with spring-boot-starter-security, protect /graphql like any endpoint, and secure individual fields with @PreAuthorize on controller methods. A denied field becomes an UNAUTHORIZED or FORBIDDEN error, while the rest of the response is returned.
  • Query cost: a client can nest fields deeply and ask for large lists in one request. graphql-java offers instrumentations such as MaxQueryDepthInstrumentation and MaxQueryComplexityInstrumentation; Spring Boot applies any Instrumentation bean to the engine.

These settings are configuration and were not exercised by the programs on this page.

Choosing how to map fields

Common needs and the mapping that fits them
NeedUse
A top-level read operation@QueryMapping
A write operation with structured input@MutationMapping with an input type and @Argument
A field that is a plain property of the parentNo mapping: a matching getter or record component
A cheap computed field@SchemaMapping
Related data from a database or another service@BatchMapping, to avoid N+1 calls
Domain exceptions as client-visible errorsDataFetcherExceptionResolverAdapter or @GraphQlExceptionHandler
Calling a GraphQL API from JavaHttpSyncGraphQlClient, or HttpGraphQlClient for reactive code
Catching schema and code driftThe schema inspection report, checked in tests

GraphQL suits clients that need different views of the same data, such as a web page and a mobile app. For fixed resources with simple caching, a REST API is usually simpler: see REST controllers with Spring MVC. For the reactive web stack, which Spring for GraphQL also supports, see Spring WebFlux, and for securing endpoints, Spring Security.