use ktor like retrofit.
Add the dependency in your common module's commonMain sourceSet
plugins {
kotlin("multiplatform")
id("com.google.devtools.ksp").version("$ksp_version")
// ...
}
kotlin {
// ...
sourceSets {
dependencies {
api("io.github.qdsfdhvh:ktor-fit-annotation:$ktorfit_version")
}
}
}
dependencies {
// add("kspCommonMainMetadata", "io.github.qdsfdhvh:ktor-fit-ksp:$ktorfit_version")
add("kspJvm", "io.github.qdsfdhvh:ktor-fit-ksp:$ktorfit_version")
// add("kspMacosX64", "io.github.qdsfdhvh:ktor-fit-ksp:$ktorfit_version")
// add("kspIosX64", "io.github.qdsfdhvh:ktor-fit-ksp:$ktorfit_version")
// add("kspJs","io.github.qdsfdhvh:ktor-fit-ksp:$ktorfit_version")
//...
}
You can create a kotlin expect class, ksp will generate the actual class.
@Suppress("NO_ACTUAL_FOR_EXPECT")
@GenerateApi
expect class TestService(client: HttpClient) : TestOtherApi1, TestOtherApi2 {
@GET("get/{id}")
suspend fun getData(@Path("id") id: String, @Query("name") name: String): String
}
interface TestOtherApi1 {
@GET("get1/{id}")
suspend fun getOtherData1(): String
}
interface TestOtherApi2 {
@GET("get2/{id}")
suspend fun getOtherData2(): String
}
And then create api:
val client = HttpClient {
defaultRequest {
url("https://example.api/")
}
}
val api = TestService(client)
This way is still experimental:
plugins {
id("io.github.qdsfdhvh.ktor-fit-plugin") version $ktorfit_version
}
@GenerateApi
interface TestService {
//...
}
ksp will auto generate code like:
class _TestServiceImpl(private val client: HttpClient) : TestService {
//...
}
and kcp will auto generate code like:
interface TestService {
//...
companion object {
fun create(client: HttpClient): TestService {
return _TestServiceImpl(client)
}
}
}
so, you can use like this:
val client = HttpClient {
defaultRequest {
url("https://example.api/")
}
}
val api = TestService.create(client)
however, at the moment you need the ktor-fit-extensions plugin to get the IDE to prompt for the create(client)
function.
![image](https://private-user-images.githubusercontent.com/17807925/301740308-5b64ce86-d145-40ef-b727-0f01a422f50c.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MjM5NzQ4MzgsIm5iZiI6MTcyMzk3NDUzOCwicGF0aCI6Ii8xNzgwNzkyNS8zMDE3NDAzMDgtNWI2NGNlODYtZDE0NS00MGVmLWI3MjctMGYwMWE0MjJmNTBjLnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNDA4MTglMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjQwODE4VDA5NDg1OFomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPWI1MWI2YTNiYmY5MTBhYmQ3ODUyNDRkNTNiMDZhYzA3YzU2N2MzZWYzY2M4Y2FjMjQxM2EyODZiOWMxMmVkYmUmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0JmFjdG9yX2lkPTAma2V5X2lkPTAmcmVwb19pZD0wIn0.zInpDT4SmXvdAVcFlZmg8jIGzLesmhFnaTfKh7A2rLw)