Spring Boot GraphQL Example

SpringBoot provides excellent support for GraphQL applications built on GraphQL Java. Let's create a sample Spring Boot GraphQL Example project.

package org.wesome.graphql;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class GraphqlProjectApplication {
    public static void main(String[] args) {
        SpringApplication.run(GraphqlProjectApplication.class, args);
    }
}
package org.wesome.graphql.controllers;

import org.springframework.beans.factory.annotation.Autowired;
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.wesome.graphql.entity.Apple;
import org.wesome.graphql.entity.AppleVO;
import org.wesome.graphql.service.AppleService;

import java.util.List;

@Controller
public class AppleGraphQLController {
    @Autowired
    private AppleService appleService;

    @QueryMapping("findApple")
    Apple findApple(@Argument int appleId) {
        return appleService.findApple(appleId);
    }

    @QueryMapping("findAllApple")
    List<Apple> findAllApple() {
        return appleService.findAllApple();
    }

    @MutationMapping("addApple")
    Apple addApple(@Argument AppleVO appleVO) {
        return appleService.addApple(appleVO);
    }

    @MutationMapping("updateApple")
    Apple updateApple(@Argument Apple apple) {
        return appleService.updateApple(apple);
    }
}
package org.wesome.graphql.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.wesome.graphql.entity.Apple;
import org.wesome.graphql.entity.AppleVO;
import org.wesome.graphql.service.AppleService;

import java.util.List;

@RestController
public class AppleRestController {
    @Autowired
    private AppleService appleService;

    @GetMapping(path = "/findApple/{appleId}", produces = "application/json")
    Apple findApple(@PathVariable("appleId") int appleId) {
        return appleService.findApple(appleId);
    }

    @GetMapping(path = "/findAllApple", produces = "application/json")
    List<Apple> findAllApple() {
        return appleService.findAllApple();
    }

    @PutMapping(path = "/addApple", produces = "application/json")
    Apple addApple(@RequestBody AppleVO appleVO) {
        return appleService.addApple(appleVO);
    }

    @PostMapping(path = "/updateApple", produces = "application/json")
    Apple updateApple(@Argument Apple apple) {
        return appleService.updateApple(apple);
    }
}
package org.wesome.graphql.entity;

import java.util.Objects;

public record Apple(int appleId, String appleName, String taste) {

    @Override
    public boolean equals(Object obj) {
        if (obj == this) return true;
        if (obj == null || obj.getClass() != this.getClass()) return false;
        var that = (Apple) obj;
        return this.appleId == that.appleId &&
                Objects.equals(this.appleName, that.appleName) &&
                Objects.equals(this.taste, that.taste);
    }

    @Override
    public String toString() {
        return "Apple[" +
                "appleId=" + appleId + ", " +
                "appleName=" + appleName + ", " +
                "taste=" + taste + ']';
    }

}
package org.wesome.graphql.entity;

import java.util.Objects;

public record AppleVO(int appleId, String appleName, String taste) {

    @Override
    public boolean equals(Object obj) {
        if (obj == this) return true;
        if (obj == null || obj.getClass() != this.getClass()) return false;
        var that = (AppleVO) obj;
        return this.appleId == that.appleId && Objects.equals(this.appleName, that.appleName) && Objects.equals(this.taste, that.taste);
    }

    @Override
    public String toString() {
        return "AppleVO[" + "appleId=" + appleId + ", " + "appleName=" + appleName + ", " + "taste=" + taste + ']';
    }
}
package org.wesome.graphql.service;

import org.wesome.graphql.entity.Apple;
import org.wesome.graphql.entity.AppleVO;

import java.util.List;

public interface AppleService {
    Apple findApple(int id);

    List<Apple> findAllApple();

    Apple addApple(AppleVO appleVO);

    Apple updateApple(Apple apple);
}
package org.wesome.graphql.service;


import org.springframework.stereotype.Service;
import org.wesome.graphql.entity.Apple;
import org.wesome.graphql.entity.AppleVO;

import java.util.ArrayList;
import java.util.List;

@Service
public class AppleServiceImpl implements AppleService {

    private static final List<Apple> apples = new ArrayList<>(List.of(new Apple(1, "Macintosh", "sweet"), new Apple(2, "Fuji", "tangy"), new Apple(3, "Gala", "bitter"), new Apple(4, "Jonagold", "sour")));

    @Override
    public Apple findApple(int id) {
        return apples.get(id);
    }

    @Override
    public List<Apple> findAllApple() {
        return apples;
    }

    @Override
    public Apple addApple(AppleVO appleVO) {
        Apple apple = new Apple(apples.size(), appleVO.appleName(), appleVO.taste());
        apples.add(apple);
        return apple;
    }

    @Override
    public Apple updateApple(Apple apple) {
        return apples.set(apple.appleId(), apple);
    }
}

\src\main\resources\graphql\schema.graphqls

# Apple Object
type Apple{
    # primary key of apple
    appleId:ID!
    # apple Name
    appleName:String
    # apple Taste
    taste:String
}
# Apple Input Object
input AppleVO{
    # primary key of apple
    appleId:ID
    # apple Name
    appleName:String
    # apple Taste
    taste:String
}
# Apple Mutation
type Mutation{
    # mutation to add an apple
    addApple(appleVO:AppleVO):Apple
    # query to update an apple
    updateApple(appleVO:AppleVO):Apple
}

# Apple Query
type Query{
    # query to get all apples
    findAllApple:[Apple]
    # query to get apple by id
    findApple(appleId:Int):Apple
}

\src\main\resources\application.properties

spring.graphql.graphiql.enabled=true

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         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>3.1.5</version>
        <relativePath/>
    </parent>
    <groupId>org.wesome</groupId>
    <artifactId>spring-boot-graphql</artifactId>
    <version>0.0.1-snapshot</version>
    <name>spring boot graphql</name>
    <description>implementing graphql in spring boot</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-graphql</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webflux</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.graphql</groupId>
            <artifactId>spring-graphql-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

build.gradle

plugins {
    id 'java'
    id 'org.springframework.boot' version '3.1.5'
    id 'io.spring.dependency-management' version '1.1.3'
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'

java {
    sourceCompatibility = '17'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-graphql'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework:spring-webflux'
    testImplementation 'org.springframework.graphql:spring-graphql-test'
}

tasks.named('test') {
    useJUnitPlatform()
}

how to access Rest API

cURL

cURL command is very useful for checking the API endpoint. The rest endpoint can be accessed via curl localhost:8080/findAllApple

how to access GraphQL API

GraphQL provides multiple ways to access the API, let's see them 

cURL

The GraphQL can be accessed via the below cURL command.

curl --location 'http://localhost:8080/graphql' \
--header 'Content-Type: application/json' \
--data '{"query":"query FindAllApple {\r\n    findAllApple {\r\n        appleId\r\n        appleName\r\n        taste\r\n    }\r\n}","variables":{}}'

GraphiQL

GraphQL provides an inbuild UserInterface GraphiQL, which can be accessed via http://localhost:8080/graphiql in the query section add the below query

query FindAllApple {
    findAllApple {
        appleId
        appleName
        taste
    }
}

Postman Post Method

GraphQL can be accessed via Postman as well, open Postman-> file-> import and paste the below curl

curl --location 'http://localhost:8080/graphql' \
--header 'Content-Type: application/json' \
--data '{"query":"query FindAllApple {\r\n    findAllApple {\r\n        appleId\r\n        appleName\r\n        taste\r\n    }\r\n}","variables":{}}'

Postman GraphQL Request Type

Postman provides a GraphQL request type UI, Open Postman-> file-> new->GraphQL and add the URL  http://localhost:8080/graphql in the query section add the below query

query FindAllApple {
    findAllApple {
        appleId
        appleName
        taste
    }
}

follow us on