Skip to Content
Course content

121: Building a GraphQL Server with Kotlin

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I was working on a mobile app for a logistics company. We had a standard REST API, but the frontend team was hitting a wall. To show a simple "Shipment Summary" screen, they had to call /shipments/{id}, then /customers/{id}, and then /locations/{id}. The network tab looked like a waterfall of requests, and the app felt sluggish on slow 4G connections. When we finally switched to GraphQL, that "waterfall" collapsed into a single request. The frontend team stopped asking me for "just one more field" in the REST response because they could now just grab it themselves.

In the Kotlin ecosystem, we have a huge advantage: our strong type system. Instead of manually writing a schema file in a separate .graphqls document and trying to keep it in sync with our data classes (which is a recipe for runtime crashes), we can use a "code-first" approach. By using libraries like graphql-kotlin, the schema is generated directly from your Kotlin source code.

Deriving Schemas from Kotlin Types

The magic happens when you define your queries as simple Kotlin classes. The library uses reflection to look at your functions and properties and maps them to GraphQL types. If you define a function that returns a Book object, GraphQL knows that Book is a type and its properties are fields.

data class Book(val id: String, val title: String, val author: Author)
data class Author(val name: String, val bio: String)

class BookQuery : Query {
    fun getBook(id: String): Book {
        // In a real app, this would hit a database
        return Book("1", "Kotlin in Action", Author("Dmitry Jemerov", "Kotlin expert"))
    }
}

Notice that I didn't write a single line of GraphQL SDL (Schema Definition Language). Because Book and Author are data classes, they automatically become GraphQL Objects. If you want to hide a specific field from the API—say, a internal database ID—you can simply mark it as @GraphQLIgnore. It's much more intuitive than maintaining a separate mapping layer.

Implementing Resolvers with Coroutines

One of the biggest mistakes I see developers make when moving to GraphQL is blocking the main execution thread during data fetching. GraphQL queries can be deeply nested, and if each level of the nest performs a synchronous database call, your server will crawl to a halt.

Since we are in Kotlin, we should be using suspend functions. The graphql-kotlin library is built to handle coroutines natively. When you mark a query function as suspend, the engine handles the asynchronous execution without blocking the thread.

class ShipmentQuery : Query {
    suspend fun shipmentDetails(id: String): Shipment {
        return shipmentService.findById(id) // This is a suspending DB call
    }
}

I highly recommend keeping your logic thin in these query classes. Treat the Query class as a controller; it should delegate the heavy lifting to a service layer. This keeps your API definition clean and makes unit testing your business logic much easier since you aren't fighting the GraphQL engine.

Handling the N+1 Problem with DataLoaders

Here is a warning: GraphQL makes it very easy to accidentally kill your database. Imagine a query that asks for 10 books and, for each book, asks for the author's name. Without optimization, your server will execute one query for the books, and then 10 separate queries for the authors. This is the classic N+1 problem.

To fix this, we use DataLoaders. Instead of fetching the author immediately inside the Book object, the DataLoader collects all the requested author IDs and fetches them in a single batch query (e.g., SELECT * FROM authors WHERE id IN (...)). While the setup is a bit more verbose, it's non-negotiable for any production-grade server. If you skip this, your logs will eventually be filled with thousands of redundant SQL queries that will bring your DB to its knees.




📋 Practical Task

Build a Movie Catalog GraphQL API

Your task is to implement a GraphQL server for a movie catalog. You need to create a schema that allows a client to fetch a movie and its associated director in a single request.

Requirements:

  • Create a Movie data class with id, title, and releaseYear.
  • Create a Director data class with id and name.
  • Implement a MovieQuery class that inherits from Query.
  • Add a suspend function getMovie(id: String) that returns a Movie object.
  • Ensure the Movie class contains a reference to a Director object so that the relationship is navigable in the GraphQL schema.
  • Use the @GraphQLIgnore annotation on a dummy internalNotes field within the Movie class to ensure it isn't exposed to the API.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.