See the Getting Started tutorial on the GraphQL Java website.
Code that executes a hello world GraphQL query with graphql-java
:
import graphql.ExecutionResult;
import graphql.GraphQL;
import graphql.schema.GraphQLSchema;
import graphql.schema.StaticDataFetcher;
import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
import static graphql.schema.idl.RuntimeWiring.newRuntimeWiring;
public class HelloWorld {
public static void main(String[] args) {
String schema = "type Query{hello: String}";
SchemaParser schemaParser = new SchemaParser();
TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);
RuntimeWiring runtimeWiring = newRuntimeWiring()
.type("Query", builder -> builder.dataFetcher("hello", new StaticDataFetcher("world")))
.build();
SchemaGenerator schemaGenerator = new SchemaGenerator();
GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);
GraphQL build = GraphQL.newGraphQL(graphQLSchema).build();
ExecutionResult executionResult = build.execute("{hello}");
System.out.println(executionResult.getData().toString());
// Prints: {hello=world}
}
}
See the graphql-java docs for further information.
Apollo Kotlin (formerly known as Apollo Android) is a GraphQL client with support for Android, Java8+, iOS and Kotlin multiplatform in general. It features:
The DGS Framework (Domain Graph Service) is a GraphQL server framework for Spring Boot, developed by Netflix.
Features include:
See DGS Framework Getting Started for how to get started.
GraphQL Kotlin provides a set of lightweight type-safe GraphQL HTTP clients. The library provides Ktor HTTP client and Spring WebClient based reference implementations as well as allows for custom implementations using other engines. Jackson and kotlinx-serialization type-safe data models are generated at build time by the provided Gradle and Maven plugins.
To generate Jackson models that will be used with GraphQL Kotlin Spring WebClient, add following to your Gradle build file:
// build.gradle.kts
import com.expediagroup.graphql.plugin.gradle.graphql
plugins {
id("com.expediagroup.graphql") version $latestGraphQLKotlinVersion
}
dependencies {
implementation("com.expediagroup:graphql-kotlin-spring-client:$latestGraphQLKotlinVersion")
}
graphql {
client {
// target GraphQL endpoint
endpoint = "http://localhost:8080/graphql"
// package for generated client code
packageName = "com.example.generated"
}
}
By default, GraphQL Kotlin plugins will look for query files under src/main/resources
. Given HelloWorldQuery.graphql
sample query:
query HelloWorldQuery {
helloWorld
}
Plugin will generate classes that are simple POJOs implementing GraphQLClientRequest interface and represent a GraphQL request.
package com.example.generated
import com.expediagroup.graphql.client.types.GraphQLClientRequest
import kotlin.String
import kotlin.reflect.KClass
const val HELLO_WORLD_QUERY: String = "query HelloWorldQuery {\n helloWorld\n}"
class HelloWorldQuery: GraphQLClientRequest<HelloWorldQuery.Result> {
override val query: String = HELLO_WORLD_QUERY
override val operationName: String = "HelloWorldQuery"
override fun responseType(): KClass<HelloWorldQuery.Result> = HelloWorldQuery.Result::class
data class Result(
val helloWorld: String
}
}
We can then execute our queries using target client.
package com.example.client
import com.expediagroup.graphql.client.spring.GraphQLWebClient
import com.expediagroup.graphql.generated.HelloWorldQuery
import kotlinx.coroutines.runBlocking
fun main() {
val client = GraphQLWebClient(url = "http://localhost:8080/graphql")
runBlocking {
val helloWorldQuery = HelloWorldQuery()
val result = client.execute(helloWorldQuery)
println("hello world query result: ${result.data?.helloWorld}")
}
}
See graphql-kotlin client docs for additional details.
GraphQL Kotlin follows a code first approach for generating your GraphQL schemas. Given the similarities between Kotlin and GraphQL, such as the ability to define nullable/non-nullable types, a schema can be generated from Kotlin code without any separate schema specification. To create a reactive GraphQL web server add following dependency to your Gradle build file:
// build.gradle.kts
implementation("com.expediagroup", "graphql-kotlin-spring-server", latestVersion)
We also need to provide a list of supported packages that can be scanned for exposing your schema objects through reflections. Add following configuration to your application.yml
file:
graphql:
packages:
- "com.your.package"
With the above configuration we can now create our schema. In order to expose your queries, mutations and/or subscriptions in the GraphQL schema you simply need to implement corresponding marker interface and they will be automatically picked up by graphql-kotlin-spring-server
auto-configuration library.
@Component
class HelloWorldQuery : Query {
fun helloWorld() = "Hello World!!!"
}
This will result in a reactive GraphQL web application with following schema:
type Query {
helloWorld: String!
}
See graphql-kotlin docs for additial details.
Spring for GraphQL provides support for Spring applications built on GraphQL Java. See the official Spring guide for how to build a GraphQL service in 15 minutes.
Features:
@Controller
public class GreetingController {
@QueryMapping
public String hello() {
return "Hello, world!";
}
}
To get started, check the Spring GraphQL starter on https://start.spring.io and the samples in this repository.
The GraphQL Spring Boot turns any Spring Boot application into a GraphQL Server
Started includes features such as:
See GraphQL Java Kickstart Getting Started for how to get started.
SpringBoot has introduced Spring GraphQL since 2.7. Jimmer provides specialized API for rapid development of Spring GraphQL-based applications.
Support two APIs: Java API & kotlin API.
Powerful and GraphQL friendly caching support.
Faster than other popular ORM solutions, please see the benchmark: https://babyfish-ct.github.io/jimmer/docs/benchmark/
More powerful than other popular ORM solutions.
Three aspects should be considered in ORM design:
a. Query. b. Update. c. Cache.
Each aspect is aimed at object trees with arbitrary depth rather than simple objects. This distinctive design brings convenience unmatched by other popular solutions.
Youtube video: https://www.youtube.com/watch?v=Rt5zNv0YR2E
Documentation: https://babyfish-ct.github.io/jimmer/
Project Home: https://github.com/babyfish-ct/jimmer
GraphQL example for Java: https://github.com/babyfish-ct/jimmer/tree/main/example/java/jimmer-sql-graphql
GraphQL example for Kotlin: https://github.com/babyfish-ct/jimmer/tree/main/example/kotlin/jimmer-sql-graphql-kt
Here’s an example on how to create a simple schema based on a kotlin data class plus a property resolver that gets applied onto your class.
data class Article(val id: Int, val text: String)
fun main() {
val schema = KGraphQL.schema {
query("article") {
resolver { id: Int?, text: String ->
Article(id ?: -1, text)
}
}
type<Article> {
property<String>("fullText") {
resolver { article: Article ->
"${article.id}: ${article.text}"
}
}
}
}
schema.execute("""
{
article(id: 5, text: "Hello World") {
id
fullText
}
}
""").let(::println)
}
KGraphQL is using coroutines behind the scenes to provide great asynchronous performance.
See KGraphQL docs for more in depth usage.
KGraphQL has a Ktor plugin which gives you a fully functional GraphQL server with a single install function call. Example below shows how to set up a GraphQL server within Ktor and it will give you a GraphQL Playground out of the box by entering localhost:8080/graphql
.
fun Application.module() {
install(GraphQL) {
playground = true
schema {
query("hello") {
resolver { -> "World!" }
}
}
}
}
You can follow the Ktor tutorial to set up a KGraphQL server with ktor from scratch up.
GraphQL Calculator is a lightweight graphql calculation engine, which is used to alter execution behavior of graphql query.
Here are some examples on how to use GraphQL Calculator on graphql query.
query basicMapValue($userIds: [Int]) {
userInfoList(userIds: $userIds) {
id
age
firstName
lastName
fullName: stringHolder @map(mapper: "firstName + lastName")
}
}
query filterUserByAge($userId: [Int]) {
userInfoList(userIds: $userId) @filter(predicate: "age>=18") {
userId
age
firstName
lastName
}
}
query parseFetchedValueToAnotherFieldArgumentMap($itemIds: [Int]) {
itemList(itemIds: $itemIds) {
# save sellerId as List<Long> with unique name "sellerIdList"
sellerId @fetchSource(name: "sellerIdList")
name
saleAmount
salePrice
}
userInfoList(userIds: 1)
# transform the argument of "userInfoList" named "userIds" according to expression "sellerIdList" and expression argument,
# which mean replace userIds value by source named "sellerIdList"
@argumentTransform(
argumentName: "userIds"
operateType: MAP
expression: "sellerIdList"
dependencySources: ["sellerIdList"]
) {
userId
name
age
}
}
See graphql-calculator README for more information.
MicroProfile GraphQL is a GraphQL server and client specification for building GraphQL applications. It’s unique annotation-based API approach enables rapid application development. Applications coded to the MP GraphQL APIs are portable, and can be deployed into Java server runtimes such as Open Liberty, Quarkus, Helidon and Wildfly. This means that your applications can make use of other Jakarta and MicroProfile technologies.
MP GraphQL features include:
Want to get started? Check out these resources:
Or these videos: