GraphQL

Installation (Gradle)

implementation group: "org.http4k", name: "http4k-graphql", version: "3.280.0"

About

This module provides http4k integration for the excellent GraphQL-java library, allowing you to either serve or consume [GraphQL] services using a simple adapter API.

As with the ethos of http4k, the uniform Server/Client GraphQLHandler model means that you can test applications entirely in-memory without binding to a port.

Code

package guide.modules.graphql

import com.expediagroup.graphql.SchemaGeneratorConfig
import com.expediagroup.graphql.toSchema
import graphql.GraphQL.newGraphQL
import org.http4k.client.JavaHttpClient
import org.http4k.client.asGraphQLHandler
import org.http4k.core.HttpHandler
import org.http4k.core.Uri
import org.http4k.graphql.GraphQLHandler
import org.http4k.graphql.GraphQLRequest
import org.http4k.graphql.GraphQLResponse
import org.http4k.routing.bind
import org.http4k.routing.graphQL
import org.http4k.routing.routes
import org.http4k.server.SunHttp
import org.http4k.server.asServer

object MyGraphQLHandler : GraphQLHandler {
    private val graphQL = newGraphQL(
        toSchema(
            SchemaGeneratorConfig(supportedPackages = listOf("guide.modules.graphql")),
            listOf(),
            listOf()
        )).build()


    override fun invoke(request: GraphQLRequest) = GraphQLResponse.from(graphQL.execute(request.query))
}

fun main() {
    val app: HttpHandler = routes(
        "/graphql" bind graphQL(MyGraphQLHandler)
    )

    // serve GQL queries/mutations at /graphql
    val server = app.asServer(SunHttp(8000)).start()

    // for clients, just convert any app into a GQL handler
    val gql: GraphQLHandler = JavaHttpClient().asGraphQLHandler(Uri.of("http://localhost:8000/graphql"))
    val response: GraphQLResponse = gql(GraphQLRequest("some query goes here.."))
}