Skip to main content
Version: pre-release

Ktor Server Overview

graphql-kotlin-ktor-server is a Ktor Server Plugin that simplifies setup of your GraphQL server.

Setup

The simplest way to create a new Ktor Server app is by generating one using https://start.ktor.io/.

Image of https://start.ktor.io/

Once you get the sample application setup locally, you will need to add graphql-kotlin-ktor-server dependency:

implementation("com.expediagroup", "graphql-kotlin-ktor-server", latestVersion)

Configuration

graphql-kotlin-ktor-server is a Ktor Server Plugin, and you need to manually install it in your module.

class HelloWorldQuery : Query {
fun hello(): String = "Hello World!"
}

fun Application.graphQLModule() {
install(GraphQL) {
schema {
packages = listOf("com.example")
queries = listOf(
HelloWorldQuery()
)
}
}
install(Routing) {
graphQLPostRoute()
}
install(StatusPages) {
defaultGraphQLStatusPages()
}
}

If you use EngineMain to start your Ktor server, you can specify your module configuration in your application.conf (default) or application.yaml (requires additional ktor-server-config-yaml dependency) file.

ktor {
application {
modules = [ com.example.ApplicationKt.graphQLModule ]
}
}

Content Negotiation

caution

graphql-kotlin-ktor-server automatically configures ContentNegotiation plugin with Jackson serialization for GraphQL GET/POST routes. kotlinx-serialization is currently not supported.

Routing

graphql-kotlin-ktor-server plugin DOES NOT automatically configure any routes. You need to explicitly configure Routing plugin with GraphQL routes. This allows you to selectively enable routes and wrap them in some additional logic (e.g. Authentication).

GraphQL plugin provides following Route extension functions

  • Route#graphQLGetRoute - GraphQL route for processing GET query requests
  • Route#graphQLPostRoute - GraphQL route for processing POST query requests
  • Route#graphQLSDLRoute - GraphQL route for exposing schema in Schema Definition Language (SDL) format
  • Route#graphiQLRoute - GraphQL route for exposing an official IDE from the GraphQL Foundation

StatusPages

graphql-kotlin-ktor-server plugin differs from Spring as it relies on Ktor's StatusPages plugin to perform error handling. It is recommended to use the default settings, however, if you would like to customize your error handling you can create your own handler. One example might be if you need to catch a custom Authorization error to return a 401 status code. Please see Ktor's Official Documentation for StatusPages

GraalVm Native Image Support

GraphQL Kotlin Ktor Server can be compiled to a native image using GraalVM Ahead-of-Time compilation. See Gradle plugin and/or Maven plugin documentation for details.