Model a REST API Response in Kotlin Data Classes
Convert a typical REST API JSON response with data envelope, pagination, and error handling into well-structured Kotlin data classes. Includes success and error response patterns.
Detailed Explanation
REST API Response Modeling in Kotlin
Most REST APIs wrap data in a standard envelope with status, data, pagination, and error fields. Converting this to Kotlin requires careful structuring of multiple data classes.
Typical API Response JSON
{
"status": "success",
"data": {
"users": [
{ "id": 1, "name": "Alice", "email": "alice@example.com" },
{ "id": 2, "name": "Bob", "email": "bob@example.com" }
]
},
"pagination": {
"currentPage": 1,
"perPage": 20,
"total": 152,
"totalPages": 8
}
}
Generated Kotlin
@Serializable
data class ApiResponse(
val status: String,
val data: UserListData,
val pagination: Pagination? = null
)
@Serializable
data class UserListData(
val users: List<User>
)
@Serializable
data class User(
val id: Int,
val name: String,
val email: String
)
@Serializable
data class Pagination(
val currentPage: Int,
val perPage: Int,
val total: Int,
val totalPages: Int
)
Error Response Handling
APIs return different structures on errors:
{
"status": "error",
"error": {
"code": "NOT_FOUND",
"message": "User not found"
}
}
@Serializable
data class ApiErrorResponse(
val status: String,
val error: ApiError
)
@Serializable
data class ApiError(
val code: String,
val message: String
)
Unified Response with Sealed Class
sealed class ApiResult<out T> {
data class Success<T>(
val data: T,
val pagination: Pagination? = null
) : ApiResult<T>()
data class Failure(
val error: ApiError
) : ApiResult<Nothing>()
}
Retrofit Integration
interface UserApi {
@GET("users")
suspend fun getUsers(
@Query("page") page: Int
): ApiResponse
}
Ktor Client Integration
val response: ApiResponse = client.get("https://api.example.com/users") {
parameter("page", 1)
}.body()
Both Retrofit (with kotlinx.serialization converter) and Ktor automatically deserialize the JSON into your Kotlin data classes.
Use Case
Every Android or Kotlin Multiplatform app that consumes a REST API needs response models. Properly structured data classes with pagination and error handling enable clean ViewModel logic, consistent error display, and easy unit testing.
Try It — JSON to Kotlin
Related Topics
Use Kotlin Generics for Reusable JSON Response Wrappers
Advanced Patterns
Model Polymorphic JSON with Kotlin Sealed Classes
Advanced Patterns
Convert Nested JSON Objects to Kotlin Data Classes
Basic Data Classes
Convert JSON Arrays to Kotlin Lists
Collections
Handle Nullable JSON Fields in Kotlin Data Classes
Basic Data Classes