Quickly Build a GraphQL API with Spring Boot: Step‑by‑Step Guide

This article walks through creating a Spring Boot project, adding GraphQL dependencies, defining schema files, implementing resolvers and a controller, and testing queries and mutations, providing a quick and flexible way to integrate GraphQL into a Java backend.

Java Backend Technology
Java Backend Technology
Java Backend Technology
Quickly Build a GraphQL API with Spring Boot: Step‑by‑Step Guide

Quick Start

Create Spring Boot project

Use Spring Initializr to generate a project with JDK 1.8 and Spring Boot 2.4.6. The generated structure is shown.

Click the Generate button.

Replace application.properties with application.yml for YAML configuration.

Add dependencies

The pom.xml includes Spring Boot starter, web, test, Lombok, graphql‑java‑tools, and Gson.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.6</version>
        <relativePath/>
    </parent>
    <groupId>com.xuxd</groupId>
    <artifactId>graphql.demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <java.version>1.8</java.version>
        <lombok.version>1.18.20</lombok.version>
        <graphql-java-tools.version>11.0.1</graphql-java-tools.version>
        <gson.version>2.8.7</gson.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.graphql-java-kickstart</groupId>
            <artifactId>graphql-java-tools</artifactId>
            <version>${graphql-java-tools.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>${gson.version}</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Initialize GraphQL instance

Create a GraphQLProvider component that loads schema files and registers a GraphQL bean.

@Component
public class GraphQLProvider {
    private GraphQL graphQL;
    @Autowired
    private IItemService itemService;
    @Bean
    public GraphQL graphQL() {
        return graphQL;
    }
    @PostConstruct
    public void init() throws IOException {
        GraphQLSchema graphQLSchema = SchemaParser.newParser()
            .file("graphql/base.graphqls")
            .resolvers(new Query(), new Mutation())
            .file("graphql/item.graphqls")
            .resolvers(new ItemResolver(itemService))
            .build()
            .makeExecutableSchema();
        this.graphQL = GraphQL.newGraphQL(graphQLSchema).build();
    }
}

Schema files

base.graphqls defines the root Query and Mutation types.

schema {
    query: Query
    mutation: Mutation
}

type Query {
    version: String
}

type Mutation {
    version: String
}

item.graphqls adds queries, mutations, and the Item domain model.

extend type Query {
    queryItemList: ItemList  # Get list of items
    queryById(id: ID): Item
}

extend type Mutation {
    updateName(param: Param): Item
}

type Item {
    id: ID!
    code: String!
    name: String!
}

type ItemList {
    itemList: [Item!]!
    total: Int!
}

input Param {
    id: ID!
    name: String!
}

Resolver implementation

public class ItemResolver implements GraphQLQueryResolver, GraphQLMutationResolver {
    private IItemService itemService;
    public ItemResolver(IItemService itemService) { this.itemService = itemService; }
    public ItemList queryItemList() { return itemService.queryItemList(); }
    public Item queryById(Long id) { return itemService.queryById(id); }
    public Item updateName(Param param) { return itemService.updateName(param); }
}

Expose API

Create a GraphqlController to handle POST requests at /graphql.

@RestController
@RequestMapping("/graphql")
public class GraphqlController {
    @Autowired private GraphQL graphQL;
    @PostMapping
    public Object execute(@RequestBody GraphqlRequest request) {
        ExecutionInput executionInput = ExecutionInput.newExecutionInput()
            .query(request.getQuery())
            .variables(request.getVariables())
            .build();
        ExecutionResult executionResult = graphQL.execute(executionInput);
        List<GraphQLError> errors = executionResult.getErrors();
        if (errors != null && !errors.isEmpty()) {
            Map<String, Object> result = new HashMap<>();
            result.put("errors", errors);
            return result;
        }
        return executionResult.getData();
    }
}

After these steps the basic GraphQL functionality is ready; you can start the application and test the three operations: queryItemList, queryById, and updateName.

Conclusion

The project now has a complete GraphQL setup and is ready for further business development.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javabackend-developmentSpring BootAPITutorialGraphQL
Java Backend Technology
Written by

Java Backend Technology

Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.