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 transport, here Spring MVC at
, reads the JSON body withPOST /graphql ,query andvariables .operationName 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.graphql-java- Execution walks the query field by field. Each field has a data fetcher; for fields mapped with
or@QueryMapping , the data fetcher calls your method. Fields without a mapping read a property of the parent object with the same name.@SchemaMapping - The results, and any errors, are written as
, normally with HTTP status 200 even when errors occurred.{"data": ..., "errors": [...]}
| Annotation | Maps a method to | Best for |
|---|---|---|
@QueryMapping | A field of Query | Entry points for reading |
@MutationMapping | A field of Mutation | Writes |
@SubscriptionMapping | A field of SubscriptionFlux | Streams over WebSocket or SSE |
@SchemaMapping | A field of any type, called once per parent object | Cheap derived or related fields |
@BatchMapping | A field of any type, called once for all parents | Related data from a database or service |
@Argument | A method parameter bound from a field argument | Arguments and input types |
The examples are Spring Boot 4.1 applications with spring-boot-starter-graphqlspring-boot-starter-webmvcgraphql-javasrc/main/resources/graphql/.graphqlsGraphQlSourceBuilderCustomizer
A first schema and queries
The book schema has two queries and a Book
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());
}
}
}
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"}}]}
returned only titles. The{ books { title } } andpages fields exist, but the client did not ask for them, so they were not sent.year- The second query picked three fields.
,id andtitle have no mapping methods: graphql-java read them from the record's accessor methods.year - The third request used a named operation with a
variable, passed separately in$id . Variables avoid building query strings by hand and let servers cache parsed queries.variables - Book 9 does not exist, so the method returned
, and the nullablenull type allowedBook without an error."book":null - Asking for
, which is not in the schema, failed validation: there is noisbn at all, only an error classified asdata , and the status is still 200.ValidationError
The method name matches the schema field name, so @QueryMapping@Argument String id-parameters
The N+1 problem and @BatchMapping
Each book has an author, loaded from a repository. With @SchemaMapping
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();
}
}
}
@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
, 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.@SchemaMapping - With
, the method received all five books at once and made one repository call for the distinct author ids. It returns a@BatchMapping from each book to its author.Map - 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.
@BatchMappingDataLoaderMapequalshashCodeDataLoaderBatchLoaderRegistry
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 HttpSyncGraphQlClientRestClient
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() + "]"));
}
}
}
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
variable was ainput on the client and arrived as aMap record in the controller:NewTask binds input objects to Java types by field name.@Argument - The second task omitted
, so the schema defaultpriority applied before the method was called.priority: Int = 3 decoded one field of the response into Java objects. The query selected onlyretrieveSync("tasks").toEntityList(...) andid , so the client used atitle record with just those fields.TaskTitle- The last request sent a priority but no title, which breaks the
rule. Validation rejected it before the controller ran, andString! returned a response that is not valid, with aexecuteSync() .ValidationError
Decoding a partial selection into the full Taskprioritynullnullint
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:
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>"));
}
}
}
{ 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
entry.errors - For account 9, the controller threw
. TheAccountNotFound turned it into an error with the classificationNotFoundResolver , our message and the pathNOT_FOUND . The["account"] field still returned 250: a partial result.balance - The
fromIllegalStateException had no resolver, so Spring returned a genericexchangeRate 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.INTERNAL_ERROR - All three responses had HTTP status 200. Clients must check the
array, not the status code.errors
A DataFetcherExceptionResolverAdapternull@GraphQlExceptionHandler@ControllerAdviceErrorTypeBAD_REQUESTUNAUTHORIZEDFORBIDDENNOT_FOUNDINTERNAL_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
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));
}
}
}
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
is listed as unmapped: there is noQuery.featured for it, so every request for it would return@QueryMapping .null is unmapped because the record calls itProduct.priceCents , andprice has no Java counterpart at all. The inspector found this by comparing the schema with the return type ofProduct.rating .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/graphqlspring.graphql.http.path
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;
serves it atspring.graphql.graphiql.enabled=true . Enable it only where it is wanted./graphiql - Introspection: clients can ask the API for its own schema.
turns that off for public APIs that should not reveal their schema.spring.graphql.schema.introspection.enabled=false - Schema printing:
serves the schema atspring.graphql.schema.printer.enabled=true ./graphql/schema - Security: with
, protectspring-boot-starter-security like any endpoint, and secure individual fields with/graphql on controller methods. A denied field becomes an@PreAuthorize orUNAUTHORIZED error, while the rest of the response is returned.FORBIDDEN - Query cost: a client can nest fields deeply and ask for large lists in one request. graphql-java offers instrumentations such as
andMaxQueryDepthInstrumentation ; Spring Boot applies anyMaxQueryComplexityInstrumentation bean to the engine.Instrumentation
These settings are configuration and were not exercised by the programs on this page.
Choosing how to map fields
| Need | Use |
|---|---|
| A top-level read operation | @QueryMapping |
| A write operation with structured input | @MutationMapping@Argument |
| A field that is a plain property of the parent | No mapping: a matching getter or record component |
| A cheap computed field | @SchemaMapping |
| Related data from a database or another service | @BatchMapping |
| Domain exceptions as client-visible errors | DataFetcherExceptionResolverAdapter@GraphQlExceptionHandler |
| Calling a GraphQL API from Java | HttpSyncGraphQlClientHttpGraphQlClient |
| Catching schema and code drift | The 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