Building a GraphQL Server with Spring Boot

Harry · 14 Sep 2026 · 1 views
Advertisement
Advertisement

Add the starter

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-graphql</artifactId>
</dependency>

Spring for GraphQL auto-configures a single endpoint at /graphql and, in development, a browser IDE (GraphiQL) to explore your API.

Define the schema

Put the schema in src/main/resources/graphql/schema.graphqls:

type Query {
  bookById(id: ID): Book
}

type Book {
  id: ID
  title: String
  author: String
}

Wire resolvers with annotations

Spring maps schema fields to controller methods with @QueryMapping and @SchemaMapping:

@Controller
public class BookController {

  private final BookRepository repo;
  public BookController(BookRepository repo) { this.repo = repo; }

  @QueryMapping
  public Book bookById(@Argument String id) {
    return repo.findById(id).orElse(null);
  }

  // resolves a nested/derived field on Book
  @SchemaMapping
  public String author(Book book) {
    return book.getAuthorName();
  }
}

@Argument binds a GraphQL field argument to a method parameter. @MutationMapping handles mutations the same way.

Query it

POST /graphql

query {
  bookById(id: "1") {
    title
    author
  }
}

Key points

  • The GraphQL starter exposes /graphql and GraphiQL in development.
  • Define the API in a .graphqls schema file.
  • Map fields to methods with @QueryMapping, @MutationMapping and @SchemaMapping.
  • @Argument binds query arguments to method parameters.
Share this post:

Comments (0)

Please login or register to comment.