GraphQL and Kotlin
a short demo pairing these two technologies
Assuming you know a few things about GraphQL, the purpose of reading this is to quickly have a single /graphql endpoint which we can use to query relational data in a flexible structure — given the fields we want to use may change.
In this demo we will be using:
The good part… both of these libraries are written natively in Kotlin! 👌
First off we need to have the correct dependencies
Make sure to check the latest versions in the documentation of both libraries mentioned and linked above ☝️
Schema
To read/write data in GraphQL, we need a schema we can refer to when executing the query we receive from the client.
The most basic one would be…
query
is a read-only fetch operation, and resolver
is where we put the logic that returns that specific collection of data, which is required to resolve the graph response. In our case we have a “TestRepo” that sends back in-memory objects we have in code — GraphQL is data source agnostic.
For this example we are using this domain…
Route
For a simple read-only fetch graphl endpoint, we use a simple GET request at (by convention) /graphql having required a query parameter which will hold the query sent back from the client.
GET /graphql?query={ query {} }
A quick HTTP server with just the graphql endpoint we mentioned above is implemented like so…
Query
Now to test if everything works correctly, we will be making a request to our /graphql?query=
endpoint, passing in the parameter the GraphQL query.
To learn more about query language, read the spec.
In our example, to fetch all the writers we will query…
we can either separate the fields by commas, or not use them at all — we like flexibility.
Code:
and the response…
And that is pretty much the bare minimum to get you up and running!
More examples
We can have a look at a little more complex query…
Let’s say we would like to get books by a writer; and maybe with a limit, not all of them everytime. So if the client supplies the query with a limit on the books, then that number of books is returned, but if none then all of the books are returned by that writer. The Writer
data class already contains a books
field, so that won’t be an issue.
we need a new query logic in our schema as previously…
Now we do need to pass in some arguments to that callback function in resolver
. In the previous example we just had the function without parameters. This query will work if we just want to look at the books stored, without any given writer.
The GraphQL query will be…
and response from one those possible queries…
Last but not least, the magic of GraphQL, we can easily remove the id
if we don’t need it in the response, and just leave the title
when requesting the query in our endpoint.
Code on Github: https://github.com/pagidas/kgraphql-http4k-demo
Thanks for reading, if you did… I hope it helped 😃