Ktor Generator 🚀
Ktor Generator is a powerful KSP (Kotlin Symbol Processing) library that automates the creation
of Ktor HTTP client implementations for your Kotlin Multiplatform projects. By simply annotating an
interface, you can eliminate the boilerplate code required for API service definitions.
It includes:
Versions
📦 Installation
Note: Please replace x.y.z with the latest version.
1. Add the KSP plugin and dependencies
In your module-level build.gradle.kts file (e.g., shared/build.gradle.kts):
plugins {
id("com.google.devtools.ksp")
}
dependencies {
implementation("io.github.the-best-is-best:ktorgenerator-annotations:x.y.z")
ksp("io.github.the-best-is-best:ktor-generator-processor:x.y.z")
}
2. Include Generated Code
Ensure the generated code is included in your source sets. This allows your project to see the code
created by the KSP processor.
kotlin {
sourceSets.all {
kotlin.srcDir("build/generated/ksp/$name/kotlin")
}
}
*Note: The path might need to be adjusted based on your project structure, but
build/generated/ksp/$name/kotlin covers most standard KMP setups._
🧩 Available Annotations
Core
@ApiService: Marks an interface to be processed. Ktor Generator will create an implementation
for it.
HTTP Methods
@GET(path: String)
@POST(path: String)
@PUT(path: String)
@DELETE(path: String)
@PATCH(path: String)
@HEAD(path: String)
Function-level Annotations
@Headers(vararg val value: String): Add multiple static headers to a request.
@Multipart: Denotes a multipart request.
@FormUrlEncoded: Denotes a URL-encoded form request.
@TextResponse: Makes the function return the raw response body as a String.
Parameter Annotations
🧪 Example Usage
1. Define Your API Interface
Create an interface and annotate it with @ApiService. Define your API endpoints as functions with
HTTP method and parameter annotations.
2. Configure the KtorGeneratorClient
In your application's setup code (e.g., in your DI setup or application entry point), configure the
KtorGeneratorClient with your base URL and a Ktor HttpClient instance.
package com.example.di
import io.github.tbib.ktorgenerator.annotations.engine.KtorGeneratorClient
io.ktor.client.*
io.ktor.client.plugins.contentnegotiation.*
io.ktor.serialization.kotlinx.json.*
kotlinx.serialization.json.Json
{
ktorClient = HttpClient {
install(ContentNegotiation) {
json(Json {
prettyPrint =
isLenient =
ignoreUnknownKeys =
})
}
}
KtorGeneratorClient.baseUrl =
KtorGeneratorClient.ktorClient = ktorClient
}
3. Create and Use Your Service
After building the project, KSP will generate the implementation and a create<YourInterfaceName>
extension function. You can then get your API service instance directly from KtorGeneratorClient.
val myApi: MyApiService = KtorGeneratorClient.createMyApiService()
suspend fun fetchSomeUser() {
val user = myApi.getUser("123")
println("Fetched user: $user")
}