agentleFS
KushpawanKushpawan/kmp-mobile-skills/skills/kmp-api-endpoint/SKILL.md

kmp-api-endpoint

Skill15 starsChanged 22 days agoApache-2.0View on GitHub

Use when adding, wiring or fixing one REST endpoint in a Kotlin Multiplatform shared module — "add a GET/POST/PUT/DELETE call", "integrate this API", "call /orders from shared code" — covering the Ktor request, @Serializable DTOs, mapper, repository, use case, Koin wiring and MockEngine tests, or when a new endpoint crashes with MissingFieldException, returns 404 because of a wrong path, or works on Android but not iOS.

The file

We split this skill into the rules it gives an agent

6 rules. About 0 are common, 2 are distinctive, and 4 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Check whether files already exist: If OrdersApi exists, add a method.

    line 56
  2. Very specific:

    If the project has none of this, set up the data layer with kmp-data-layer first.

    line 58
  3. Very specific:

    Every response field nullable, = null, explicit @SerialName.

    line 87
  4. Distinctive:

    If the project's ViewModels call repositories directly, skip this file — a pass-through use case adds a layer and tests nothing.

    line 195
  5. Very specific:

    Add ordersModule to the app's module list (or the feature aggregator's includes(...)).

    line 208
  6. Distinctive:

    Write these four, using the templates in references/test-templates.md:

    line 214

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Add one REST endpoint to a KMP app

A concrete recipe: one endpoint, from wire contract to tested repository, in the project's own shape. The architecture behind each step — untrusted DTOs, one shared client, typed errors — is in kmp-data-layer; this skill applies it file by file.

When to use

  • Adding a new GET, POST, PUT, PATCH or DELETE call to shared code.
  • Adding a method to an existing API service, repository and use case.
  • Fixing a freshly added endpoint: parse failures, wrong URL, missing auth header, untested errors.

When not to use

  • Designing the data layer, HttpClient, auth refresh or result type from scratch — use kmp-data-layer first.
  • Caching the response in a database or syncing offline writes — kmp-data-layer (offline-first) and kmp-room-database.
  • DI start-up problems (NoDefinitionFoundException at launch) — kmp-koin-di.

Inputs — get these before writing code

InputExampleIf missing
Method and pathGET orders/{orderId}Ask.
Path and query parametersorderId: String, ?expand=itemsAsk which are optional.
Request body sampleJSONRequired for POST/PUT/PATCH.
Response sampleReal JSON, ideally from the API docs or a recorded callAsk. Never invent field names.
Error statuses404 unknown id, 409 already cancelledUse the defaults in the error mapping.
Authbearer / nonePicks the authenticated or plain client.
Paginationcursor / page+size / noneShapes the domain return type.

Step 0 — Read the project first

  1. Find the closest existing endpoint and copy its shape.
    grep -rln "client.get\|client.post\|HttpClient" --include=*.kt */src/commonMain | head
    Open one complete vertical (API → repository → use case → DI → tests). Note package layout, file names, the toDomain() style, whether use cases exist, and how tests are written.
  2. Detect the building blocks — reuse each one, never add a parallel version:
    grep -rnE "sealed (class|interface) [A-Za-z]*(Result|Outcome)" --include=*.kt .    # result type
    grep -rnE "suspend fun <T> [A-Za-z]*(Call|Request)" --include=*.kt .               # error-boundary helper
    grep -rn "named(" --include=*.kt . | grep -i client                                 # client qualifiers
    grep -rnE "DispatcherProvider|MockEngine|class Fake" --include=*.kt . | head -20    # dispatchers, test helpers
  3. Check whether files already exist. If OrdersApi exists, add a method; don't create OrdersApi2.

If the project has none of this, set up the data layer with kmp-data-layer first. The examples below use its defaults: ApiResult / DataError, safeApiCall, DispatcherProvider, Koin with named("authenticated"), package com.example.app.

Workflow

Example endpoint: GET orders/{orderId} → one order with line items.

1. Response DTOs — orders/data/remote/dto/OrderDto.kt

@Serializable
data class OrderDto(
    @SerialName("id") val id: String? = null,
    @SerialName("status") val status: String? = null,
    @SerialName("total_minor") val totalMinor: Long? = null,
    @SerialName("currency") val currency: String? = null,
    @SerialName("placed_at") val placedAtEpochMillis: Long? = null,
    @SerialName("items") val items: List<OrderItemDto>? = null,
)

@Serializable
data class OrderItemDto(
    @SerialName("sku") val sku: String? = null,
    @SerialName("name") val name: String? = null,
    @SerialName("quantity") val quantity: Int? = null,
)

Every response field nullable, = null, explicit @SerialName. Enums arrive as String?. Request DTOs (for POST/PUT) may be non-null. Done when the DTO round-trips the sample JSON in a test.

2. Domain model — orders/domain/Order.kt

data class Order(
    val id: String,
    val status: OrderStatus,
    val total: Money,
    val placedAtEpochMillis: Long,
    val items: List<OrderItem>,
)

data class Money(val amountMinor: Long, val currency: String)
data class OrderItem(val sku: String, val name: String, val quantity: Int)
enum class OrderStatus { Pending, Shipped, Delivered, Cancelled, Unknown }

Plain, non-null, no annotations. Money as minor units plus currency, never Double.

3. Mapper — orders/data/OrderMappers.kt

internal fun OrderDto.toDomainOrNull(): Order? {
    val id = id?.takeIf { it.isNotBlank() } ?: return null
    val amount = totalMinor ?: return null            // never default money to 0
    val currency = currency?.takeIf { it.length == 3 } ?: return null
    return Order(
        id = id,
        status = status.toOrderStatus(),
        total = Money(amountMinor = amount, currency = currency.uppercase()),
        placedAtEpochMillis = placedAtEpochMillis ?: 0L,
        items = items.orEmpty().mapNotNull { it.toDomainOrNull() },
    )
}

internal fun OrderItemDto.toDomainOrNull(): OrderItem? {
    val sku = sku?.takeIf { it.isNotBlank() } ?: return null
    val quantity = quantity?.takeIf { it > 0 } ?: return null
    return OrderItem(sku = sku, name = name.orEmpty(), quantity = quantity)
}

private fun String?.toOrderStatus(): OrderStatus = when (this?.lowercase()) {
    "pending" -> OrderStatus.Pending
    "shipped" -> OrderStatus.Shipped
    "delivered" -> OrderStatus.Delivered
    "cancelled" -> OrderStatus.Cancelled
    else -> OrderStatus.Unknown                       // new server values must not crash old apps
}

List each field as required (drop or fail) or cosmetic (fall back). Each rule gets a test.

4. API service — orders/data/remote/OrdersApi.kt

interface OrdersApi {
    suspend fun getOrder(orderId: String): OrderDto
}

internal class KtorOrdersApi(private val client: HttpClient) : OrdersApi {
    override suspend fun getOrder(orderId: String): OrderDto =
        client.get("orders/${orderId.encodeURLPathPart()}").body()
}
  • Relative path, no leading / — it resolves against the client's base URL.
  • Encode path parameters. encodeURLPathPart() (from io.ktor.http) escapes /, ? and #; raw interpolation lets an id like ../admin or a?b=c change the request.
  • No try/catch, no mapping, no headers the shared client already adds.

5. Repository — orders/domain/OrdersRepository.kt + orders/data/OrdersRepositoryImpl.kt

interface OrdersRepository {
    suspend fun getOrder(orderId: String): ApiResult<Order>
}

class OrdersRepositoryImpl(
    private val ordersApi: OrdersApi,
    private val dispatchers: DispatcherProvider,
) : OrdersRepository {

    override suspend fun getOrder(orderId: String): ApiResult<Order> =
        safeApiCall(dispatchers.default) {
            ordersApi.getOrder(orderId).toDomainOrNull()
                ?: throw SerializationException("Order response is missing required fields")
        }
}

The error boundary maps HTTP status, transport and parse failures to DataError and rethrows cancellation. An order missing required fields becomes DataError.Serialization, not a crash and not a half-empty screen.

6. Use case — only if the project uses them

// orders/domain/GetOrderUseCase.kt
class GetOrderUseCase(private val ordersRepository: OrdersRepository) {
    suspend operator fun invoke(orderId: String): ApiResult<Order> {
        if (orderId.isBlank()) return ApiResult.Failure(DataError.Validation(serverMessage = null))
        return ordersRepository.getOrder(orderId)
    }
}

If the project's ViewModels call repositories directly, skip this file — a pass-through use case adds a layer and tests nothing.

7. DI — orders/di/OrdersModule.kt

val ordersModule = module {
    single<OrdersApi> { KtorOrdersApi(client = get(named("authenticated"))) }
    single<OrdersRepository> { OrdersRepositoryImpl(ordersApi = get(), dispatchers = get()) }
    factoryOf(::GetOrderUseCase)
}

Add ordersModule to the app's module list (or the feature aggregator's includes(...)). Use the plain client for endpoints that must not carry a token. Done when the DI verification test passes (see kmp-koin-di) or the app starts and resolves the screen's ViewModel.

8. Tests — commonTest/.../orders/

Write these four, using the templates in references/test-templates.md:

FileCovers
OrderMapperTestevery required-field drop, every fallback, unknown enum value
KtorOrdersApiTestmethod, encoded path, query, headers, body; parses the sample JSON through the real client
OrdersRepositoryImplTestsuccess; 404 → NotFound; 401 → Unauthorized; malformed body → Serialization; offline → NoConnection
FakeOrdersRepositorya fake for ViewModel and use-case tests (not a test itself)

Name tests should_<expected>_when_<condition> unless the project uses another convention.

9. Run the checks in Verify.

Variations

NeedDo this
Query parametersclient.get("orders") { parameter("status", status) } — a null value is skipped
Repeated query keyclient.get("orders") { url { parameters.appendAll("tag", tags) } }
POST with JSON bodyclient.post("orders") { contentType(ContentType.Application.Json); setBody(CreateOrderRequest(...)) }
PATCH (partial update)Request DTO with only the changed fields. With explicitNulls = false a null is omitted, so "clear this field" needs an explicit design (a JsonObject body or a dedicated flag)
204 No Contentclient.delete("orders/${id.encodeURLPathPart()}") and return Unit; do not call .body()
PaginationDTO carries next_cursor; domain returns Page<Order>(items, nextCursor); the ViewModel owns "load more"
Multipart uploadclient.submitFormWithBinaryData(url = "uploads", formData = formData { append("file", bytes, Headers.build { append(HttpHeaders.ContentDisposition, "filename=\"receipt.jpg\"") }) }) { timeout { requestTimeoutMillis = 120_000 } }
Pre-signed upload URL (third-party host)Absolute URL through a client without the bearer provider, or a bearer config whose sendWithoutRequest excludes that host
Retry-safe createIf the backend supports it, send a client-generated idempotency key header so a retried POST does not create a duplicate
Response wrapped in an envelope{"data": {...}} → an EnvelopeDto<T>(@SerialName("data") val data: T? = null); unwrap in the mapper

Quick reference — files for GET orders/{orderId}

LayerFile (commonMain)Contains
DTOorders/data/remote/dto/OrderDto.ktOrderDto, OrderItemDto
Domainorders/domain/Order.ktOrder, Money, OrderItem, OrderStatus
Mapperorders/data/OrderMappers.kttoDomainOrNull()
APIorders/data/remote/OrdersApi.ktinterface + KtorOrdersApi
Repositoryorders/domain/OrdersRepository.kt, orders/data/OrdersRepositoryImpl.ktApiResult<Order>
Use caseorders/domain/GetOrderUseCase.ktonly if the project uses them
DIorders/di/OrdersModule.ktbindings, added to the app module list
TestscommonTest/.../orders/*Test.ktmapper, API, repository, fake repository

Verify

Report each check as PASS, FAIL or NOT RUN (with the reason). Do not report a check you did not run. Read settings.gradle.kts for the real module name; the Android host-test task is testDebugUnitTest with com.android.library and testAndroidHostTest with com.android.kotlin.multiplatform.library.

./gradlew :shared:testDebugUnitTest --tests "com.example.app.orders.*"     # fast JVM loop
./gradlew :shared:iosSimulatorArm64Test --tests "com.example.app.orders.*" # Kotlin/Native
./gradlew :shared:allTests                                                 # everything before you finish
./gradlew :composeApp:assembleDebug                                        # app still builds

Static checks (adjust shared/src/commonMain to the module you changed; review every hit):

grep -rnE "val [A-Za-z0-9_]+: [^?=]+(,|$)" --include=*Dto.kt shared/src/commonMain           # non-null DTO fields
grep -rnE 'client\.(get|post|put|patch|delete)\("[^"]*\$' --include=*.kt shared/src/commonMain | grep -v encodeURLPathPart   # unencoded path params
grep -rn "HttpClient(" --include=*.kt shared/src/commonMain                                   # clients outside the network module

Common mistakes

MistakeWhy it bitesFix
DTO fields copied as non-null from the sampleThe sample had every field; production data does notNullable, = null, decide in the mapper
Money or quantity defaulted to 0A missing total renders as "free" and may be acted onTreat as required: drop or fail
"orders/$id"Ids containing /, ? or # rewrite the request"orders/${id.encodeURLPathPart()}"
Path starts with /Drops the base path (/v1/), request hits the wrong URL, 404Relative path
New HttpClient or install(...) in the featureNo auth, no timeouts, no log redactionInject the shared client by qualifier
try/catch in the API classErrors mapped in two places, differentlyOnly the repository's error boundary maps
Catching Exception without rethrowing CancellationExceptionCancelled screens keep running and report fake failuresUse the project's error boundary helper
Pass-through use case in a project without use casesExtra layer, extra DI, no behaviourFollow the project's layering
Tests with their own Json { } or a hand-built clientPass while production parsing failsBuild the test client with the production factory and MockEngine
Only the happy path tested404, 401 and malformed bodies ship untestedThe four repository error tests are mandatory
Endpoint added but module not registeredNoDefinitionFoundException at runtime, only on the screen that needs itAdd the module to the app's list; run the DI verification test

Related skills

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.