ktor-patterns
Skill66 starsChanged 6 months agoMITView on GitHub
Ktor client patterns for Android networking with content negotiation, error handling, and interceptors.
In this repository51 other files it gives its agents.
- AGENTS.mdAGENTS.md
- rules/agents.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- examples/CLAUDE.mdCLAUDE.md
- .github/copilot-instructions.mdCopilot instructions
- .cursor/rules/everything-mobile.mdcCursor rule
- accessibility-patternsSkill
- analytics-patternsSkill
- android-patternsSkill
- app-lifecycleSkill
- ci-cd-patternsSkill
- combine-frameworkSkill
- continuous-learningSkill
- continuous-learning-v2Skill
- core-dataSkill
- coroutines-patternsSkill
- deep-linkingSkill
- expect-actualSkill
- feature-builderSkill
- feature-flagsSkill
- gradle-patternsSkill
- image-loadingSkill
- ios-testingSkill
- jetpack-composeSkill
- kmp-diSkill
- kmp-navigationSkill
- kmp-networkingSkill
- kmp-repositoriesSkill
- koin-patternsSkill
- liquid-glassSkill
- localization-patternsSkill
- m3-expressiveSkill
- mobile-checkpointSkill
- mobile-compactionSkill
- mobile-instinct-v1Skill
- mobile-instinct-v2Skill
- mobile-memorySkill
- mobile-securitySkill
- mobile-testingSkill
- mobile-verificationSkill
- mvi-architectureSkill
- navigation-composeSkill
- offline-firstSkill
- pagination-patternsSkill
- push-notificationsSkill
- room-patternsSkill
- shared-coroutinesSkill
- shared-modelsSkill
- sqldelight-patternsSkill
- swift-patternsSkill
- swiftui-patternsSkill
The file
Files
Ktor Client Patterns
Modern HTTP client for Kotlin.
Client Setup
val httpClient = HttpClient(OkHttp) {
// JSON serialization
install(ContentNegotiation) {
json(Json {
ignoreUnknownKeys = true
isLenient = true
prettyPrint = false
})
}
// Timeouts
install(HttpTimeout) {
requestTimeoutMillis = 30_000
connectTimeoutMillis = 10_000
socketTimeoutMillis = 30_000
}
// Logging (debug only)
install(Logging) {
logger = Logger.ANDROID
level = if (BuildConfig.DEBUG) LogLevel.BODY else LogLevel.NONE
}
// Default request config
defaultRequest {
url("https://api.example.com")
contentType(ContentType.Application.Json)
}
// Auth
install(Auth) {
bearer {
loadTokens {
BearerTokens(tokenStorage.accessToken, tokenStorage.refreshToken)
}
refreshTokens {
val response = client.post("auth/refresh") {
setBody(RefreshRequest(tokenStorage.refreshToken))
}
tokenStorage.save(response.body())
BearerTokens(response.body<TokenResponse>().accessToken, response.body<TokenResponse>().refreshToken)
}
}
}
}API Definition
class UserApi(private val client: HttpClient) {
suspend fun getUsers(): List<UserDto> {
return client.get("users").body()
}
suspend fun getUser(id: String): UserDto {
return client.get("users/$id").body()
}
suspend fun createUser(request: CreateUserRequest): UserDto {
return client.post("users") {
setBody(request)
}.body()
}
suspend fun updateUser(id: String, request: UpdateUserRequest): UserDto {
return client.put("users/$id") {
setBody(request)
}.body()
}
suspend fun deleteUser(id: String) {
client.delete("users/$id")
}
}Error Handling
class ApiException(
val statusCode: Int,
override val message: String
) : Exception(message)
suspend inline fun <reified T> HttpClient.safeRequest(
block: HttpRequestBuilder.() -> Unit
): Result<T> = runCatching {
val response = request(block)
if (response.status.isSuccess()) {
response.body<T>()
} else {
throw ApiException(
statusCode = response.status.value,
message = response.bodyAsText()
)
}
}
// Usage
class UserRepository(private val api: UserApi, private val client: HttpClient) {
suspend fun getUser(id: String): Result<User> {
return client.safeRequest<UserDto> {
url("users/$id")
method = HttpMethod.Get
}.map { it.toDomain() }
}
}DTOs and Mapping
@Serializable
data class UserDto(
val id: String,
val email: String,
@SerialName("first_name")
val firstName: String,
@SerialName("created_at")
val createdAt: String
)
fun UserDto.toDomain(): User = User(
id = id,
email = email,
name = firstName,
createdAt = Instant.parse(createdAt)
)Interceptors
val client = HttpClient(OkHttp) {
// Request interceptor
install(HttpSend) {
intercept { request ->
request.headers.append("X-Client-Version", BuildConfig.VERSION_NAME)
execute(request)
}
}
}Certificate Pinning
val client = HttpClient(OkHttp) {
engine {
config {
certificatePinner(
CertificatePinner.Builder()
.add("api.example.com", "sha256/AAAA...")
.add("api.example.com", "sha256/BBBB...") // Backup pin
.build()
)
}
}
}Remember: Ktor is coroutine-first. Embrace suspend functions, handle errors properly.
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
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.

