Installation (Gradle)

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

// for the example below you will also need this dependency...
implementation group: "com.expediagroup", name: "graphql-kotlin-schema-generator", version: "3.7.0"


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.


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(
            SchemaGeneratorConfig(supportedPackages = listOf("guide.modules.graphql")),

    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.."))