📣 GraphQLConf 2024 • Sept 10-12 • San Francisco • Check out the Schedule & Get Your Ticket • Read more

Code Using GraphQL

Sort by:
graphql-java
A Java library for building GraphQL APIs.
Last release 1 day ago6kMIT License
README

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
A strongly-typed, caching GraphQL client for the JVM, Android, and Kotlin multiplatform.
Last release 6 days ago4kMIT License
README

Apollo Kotlin (formerly known as Apollo Android) is a GraphQL client with support for Android, Java8+, iOS and Kotlin multiplatform in general. It features:

  • Java and Kotlin Multiplatform code generation
  • Queries, Mutations and Subscriptions
  • Reflection-free parsing
  • Normalized cache
  • Custom scalar types
  • HTTP cache
  • Auto Persisted Queries
  • Query batching
  • File uploads
  • Espresso IdlingResource
  • Fake models for tests
  • AppSync and graphql-ws websockets
  • GraphQL AST parser
Domain Graph Service (DGS) Framework
The DGS Framework (Domain Graph Service) is a GraphQL server framework for Spring Boot, developed by Netflix.
Last release 1 week ago3kApache License 2.0
README

The DGS Framework (Domain Graph Service) is a GraphQL server framework for Spring Boot, developed by Netflix.

Features include:

  • Annotation based Spring Boot programming model
  • Test framework for writing query tests as unit tests
  • Gradle Code Generation plugin to create types from schema
  • Easy integration with GraphQL Federation
  • Integration with Spring Security
  • GraphQL subscriptions (WebSockets and SSE)
  • File uploads
  • Error handling
  • Many extension points

See DGS Framework Getting Started for how to get started.

graphql-kotlin
A set of libraries for running GraphQL client and server in Kotlin.
Last release 2 months ago2kApache License 2.0
README

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
A set of libraries for running GraphQL client and server in Kotlin.
Last release 2 months ago2kApache License 2.0
README

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.

GraphQL Spring Boot
GraphQL Spring Boot from GraphQL Java Kickstart
Last release 3 months ago2kMIT License
README

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.

Spring for GraphQL
Spring for GraphQL provides support for Spring applications built on GraphQL Java.
Last release 1 month ago1kApache License 2.0
README

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.

  • It is a joint collaboration between the GraphQL Java team and Spring engineering.
  • Our shared philosophy is to provide as little opinion as we can while focusing on comprehensive support for a wide range of use cases.
  • It aims to be the foundation for all Spring, GraphQL applications.

Features:

  • Server handling of GraphQL requests over HTTP, WebSocket, and RSocket.
  • An annotation-based programming model where @Controller components use annotations to declare handler methods with flexible method signatures to fetch the data for specific GraphQL fields. For example:
@Controller
public class GreetingController {
 
    @QueryMapping
    public String hello() {
        return "Hello, world!";
    }
 
}
  • Client support for executing GraphQL requests over HTTP, WebSocket, and RSocket.
  • Dedicated support for testing GraphQL requests over HTTP, WebSocket, and RSocket, as well as for testing directly against a server.

To get started, check the Spring GraphQL starter on https://start.spring.io and the samples in this repository.

Jimmer
A revolutionary ORM framework for both java and kotlin, it also provides specialized API for rapid development of Spring GraphQL-based applications.
Last release 2 days ago1kApache License 2.0
README

Introduce

  1. SpringBoot has introduced Spring GraphQL since 2.7. Jimmer provides specialized API for rapid development of Spring GraphQL-based applications.

  2. Support two APIs: Java API & kotlin API.

  3. Powerful and GraphQL friendly caching support.

  4. Faster than other popular ORM solutions, please see the benchmark: https://babyfish-ct.github.io/jimmer/docs/benchmark/

  5. 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.

Links

Nodes
A GraphQL JVM Client designed for constructing queries from standard model definitions. By American Express.
Last release 4 years ago305Apache License 2.0
KGraphQL
KGraphQL is a Kotlin implementation of GraphQL. It provides a rich DSL to set up the GraphQL schema.
Last release 1 year ago292MIT License
README

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.

Ktor Plugin

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
A lightweight graphql calculation engine.
Last release 2 years ago104Apache License 2.0
README

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
MP GraphQL is a code-first specification for building GraphQL applications. It uses annotations and design patterns similar to JAX-RS to enable rapid development.
Last release 2 years ago94Apache License 2.0
README

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:

  • Annotation-based APIs
  • Integration with Jakarta CDI
  • Type-safe and dynamic client APIs
  • Exception handling
  • Easy integration with Jakarta and MicroProfile technologies

Want to get started? Check out these resources:

Or these videos:

GraphQL Java Generator
GraphQL Java Generator is a tool that generates Java code to speed up development for Client and Server of GraphQL APIs
51MIT License
README
  • GraphQL Java client: it generates the Java classes that call the GraphQL endpoint, and the POJO that will contain the data returned by the server. The GraphQL endpoint can then be queried by using a simple call to a Java method (see sample below)
  • GraphQL Java server: it is based on graphql-java (listed here above). It generates all the boilerplate code. You’ll only have to implement what’s specific to your server, which are the joins between the GraphQL types. GraphQL Java Generator is available as a Maven Plugin. A Gradle plugin is coming soon. Please note that GraphQL Java Generator is an accelerator: the generated code doesn’t depend on any library specific to GraphQL Java Generator. So, it helps you to start building application based on graphql-java. Once the code is generated, you can decide to manually edit it as any standard java application, and get rid of GraphQL Java Generator. Of course you can, and should, according to us :), continue using GraphQL Java Generator when your project evolves.