Search Tutorials


Spring Boot + GraphQL Hello World Example | JavaInUse



Spring Boot + GraphQL Hello World Example

In previous tutorial we looked at what is GraphQL and need for it. In this tutorial we will be implementing Spring Boot + GraphQL Hello World Example.

Implementation

We will be creating Spring Boot Maven Project as follows -

The pom.xml we will be adding the GraphQL dependencies
<?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.3.0.RELEASE</version>
		<relativePath />
	</parent>
	<groupId>com.javainuse</groupId>
	<artifactId>boot-graphql</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>boot-qraphql</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>com.graphql-java-kickstart</groupId>
			<artifactId>graphql-spring-boot-starter</artifactId>
			<version>7.0.1</version>
		</dependency>
		<dependency>
			<groupId>com.graphql-java-kickstart</groupId>
			<artifactId>graphiql-spring-boot-starter</artifactId>
			<version>7.0.1</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>
Create the Spring Boot bootstrap class as follows-
package com.javainuse;

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

@SpringBootApplication
public class BootGraphqlApplication {

	public static void main(String[] args) {
		SpringApplication.run(BootGraphqlApplication.class, args);
	}

}
Next create the GraphQL class=
package com.javainuse.query;

import org.springframework.stereotype.Component;

import graphql.kickstart.tools.GraphQLQueryResolver;

@Component
public class Query implements GraphQLQueryResolver {

	public String helloWorld() {
		return "Hello World";
	}

}

Create the schema file-
type Query{
helloWorld : String
}
Start the Spring Boot Application. And go to http://localhost:8080/graphiql as follows-

Now use the following GraphQL query as follows-
query{
  helloWorld
}