REST APIs
suggest changeA REST API exposes your data as resources at URLs. Clients act on them with standard HTTP methods and exchange JSON. This article builds a complete books API with Ktor and kotlinx.serialization, then writes a typed Kotlin client for it. It covers:
- designing URLs, methods and status codes
- request and response DTOs
- validation with the
RequestValidationplugin - consistent JSON error responses with
StatusPages - pagination, filtering and sorting
- a typed client with error mapping, retries and a paging
Flow - testing the API in memory with
testApplication
This article assumes basic Ktor knowledge (see HTTP with Ktor for server and client basics). For JSON details see JSON, for other HTTP client libraries see HTTP client, and for cross-cutting concerns like logging and request IDs see HTTP middleware.
Designing the API
Name resources with plural nouns, and let the HTTP method say what happens. Put a version in the path so you can make breaking changes later:
| Method | URL | Meaning | Success status |
|---|---|---|---|
GET |
/api/v1/books |
list books (paged, filterable) | 200 OK |
GET |
/api/v1/books/{id} |
get one book | 200 OK |
POST |
/api/v1/books |
create a book | 201 Created + Location |
PUT |
/api/v1/books/{id} |
replace a book completely | 200 OK |
PATCH |
/api/v1/books/{id} |
change some fields | 200 OK |
DELETE |
/api/v1/books/{id} |
delete a book | 204 No Content |
GET, PUT and DELETE are idempotent: repeating the same request leaves the server in the same state. POST is not, because each call creates a new resource. This matters for retries. A client can safely retry a PUT after a timeout, but a retried POST may create a duplicate.
Use error status codes consistently:
| Status | When |
|---|---|
400 Bad Request |
malformed JSON, wrong types, invalid query parameters |
401 Unauthorized |
missing or invalid credentials |
403 Forbidden |
authenticated, but not allowed |
404 Not Found |
resource or route does not exist |
409 Conflict |
request conflicts with current state (duplicate, version mismatch) |
415 Unsupported Media Type |
body is not JSON |
422 Unprocessable Entity |
well-formed JSON that fails validation rules |
500 Internal Server Error |
a bug on the server; never leak details |
Setup
In build.gradle.kts:
plugins {
kotlin("jvm") version "2.4.21"
kotlin("plugin.serialization") version "2.4.21"
}
dependencies {
val ktor = "3.6.0"
implementation("io.ktor:ktor-server-core:$ktor")
implementation("io.ktor:ktor-server-cio:$ktor")
implementation("io.ktor:ktor-server-content-negotiation:$ktor")
implementation("io.ktor:ktor-server-request-validation:$ktor")
implementation("io.ktor:ktor-server-status-pages:$ktor")
implementation("io.ktor:ktor-serialization-kotlinx-json:$ktor")
implementation("io.ktor:ktor-client-core:$ktor")
implementation("io.ktor:ktor-client-cio:$ktor")
implementation("io.ktor:ktor-client-content-negotiation:$ktor")
implementation("ch.qos.logback:logback-classic:1.6.5")
testImplementation("io.ktor:ktor-server-test-host:$ktor")
testImplementation(kotlin("test"))
}
DTOs
Don't use one class for everything. The client doesn't send the id because the server assigns it. A PATCH body has all fields optional. Separate classes make each contract explicit:
import kotlinx.serialization.Serializable
@Serializable
data class Book(val id: Long, val title: String, val author: String, val year: Int)
// What clients send: no id, the server assigns it
@Serializable
data class BookInput(val title: String, val author: String, val year: Int)
// PATCH body: every field optional
@Serializable
data class BookPatch(val title: String? = null, val author: String? = null, val year: Int? = null)
@Serializable
data class Page<T>(val items: List<T>, val page: Int, val size: Int, val total: Int)
// Every error response has this shape
@Serializable
data class ApiError(
val status: Int,
val error: String,
val message: String,
val details: List<String> = emptyList(),
)
The same classes can be shared with a Kotlin client, for example through a common module.
A repository
The HTTP layer should not know how data is stored. Here a thread-safe in-memory store stands in for a database. It throws domain exceptions, and the HTTP layer maps them to status codes:
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicLong
class NotFoundException(message: String) : RuntimeException(message)
class ConflictException(message: String) : RuntimeException(message)
class BookRepository {
private val books = ConcurrentHashMap<Long, Book>()
private val nextId = AtomicLong(1)
fun all(): List<Book> = books.values.sortedBy { it.id }
fun find(id: Long): Book? = books[id]
fun create(input: BookInput): Book {
if (books.values.any { it.title.equals(input.title, ignoreCase = true) }) {
throw ConflictException("a book titled '${input.title}' already exists")
}
val book = Book(nextId.getAndIncrement(), input.title, input.author, input.year)
books[book.id] = book
return book
}
fun replace(id: Long, input: BookInput): Book {
find(id) ?: throw NotFoundException("book $id not found")
return Book(id, input.title, input.author, input.year).also { books[id] = it }
}
fun patch(id: Long, p: BookPatch): Book {
val old = find(id) ?: throw NotFoundException("book $id not found")
val new = old.copy(
title = p.title ?: old.title,
author = p.author ?: old.author,
year = p.year ?: old.year,
)
books[id] = new
return new
}
fun delete(id: Long): Boolean = books.remove(id) != null
}
For a real database see PostgreSQL or SQLite.
The server
The whole API is an Application extension function. Taking the repository as a parameter makes it easy to give each test its own instance:
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.plugins.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.plugins.requestvalidation.*
import io.ktor.server.plugins.statuspages.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.serialization.json.Json
fun validateBook(title: String?, author: String?, year: Int?): List<String> = buildList {
if (title != null && title.isBlank()) add("title must not be blank")
if (title != null && title.length > 200) add("title must be at most 200 characters")
if (author != null && author.isBlank()) add("author must not be blank")
if (year != null && year !in 1450..2100) add("year must be between 1450 and 2100")
}
fun Application.booksApi(repo: BookRepository = BookRepository()) {
install(ContentNegotiation) {
json(Json {
prettyPrint = true
ignoreUnknownKeys = true
})
}
install(RequestValidation) {
validate<BookInput> { b ->
val errors = validateBook(b.title, b.author, b.year)
if (errors.isEmpty()) ValidationResult.Valid else ValidationResult.Invalid(errors)
}
validate<BookPatch> { p ->
val errors = validateBook(p.title, p.author, p.year)
if (errors.isEmpty()) ValidationResult.Valid else ValidationResult.Invalid(errors)
}
}
install(StatusPages) {
exception<RequestValidationException> { call, e ->
call.respondError(HttpStatusCode.UnprocessableEntity, "validation failed", e.reasons)
}
exception<BadRequestException> { call, e ->
// malformed JSON, missing fields, wrong types, bad parameters
val cause = e.cause?.message?.lineSequence()?.first()
call.respondError(HttpStatusCode.BadRequest, cause ?: e.message ?: "bad request")
}
exception<NotFoundException> { call, e ->
call.respondError(HttpStatusCode.NotFound, e.message!!)
}
exception<ConflictException> { call, e ->
call.respondError(HttpStatusCode.Conflict, e.message!!)
}
exception<Throwable> { call, e ->
call.application.log.error("unhandled error", e)
call.respondError(HttpStatusCode.InternalServerError, "internal error")
}
status(HttpStatusCode.NotFound) { call, status ->
call.respondError(status, "no route for ${call.request.httpMethod.value} ${call.request.path()}")
}
}
routing {
route("/api/v1/books") {
// GET /api/v1/books?page=1&size=20&author=tolkien&sort=-year
get {
val q = call.request.queryParameters
val page = q["page"]?.toIntOrNull() ?: 1
val size = q["size"]?.toIntOrNull() ?: 20
if (page < 1 || size !in 1..100) {
throw BadRequestException("page must be >= 1 and size between 1 and 100")
}
var books = repo.all()
q["author"]?.let { a -> books = books.filter { it.author.contains(a, ignoreCase = true) } }
books = when (val sort = q["sort"]) {
null, "id" -> books
"year" -> books.sortedBy { it.year }
"-year" -> books.sortedByDescending { it.year }
"title" -> books.sortedBy { it.title }
else -> throw BadRequestException("unknown sort field '$sort'")
}
val items = books.drop((page - 1) * size).take(size)
call.respond(Page(items, page, size, books.size))
}
get("{id}") {
val id = call.bookId()
val book = repo.find(id) ?: throw NotFoundException("book $id not found")
call.respond(book)
}
post {
val book = repo.create(call.receive<BookInput>())
call.response.header(HttpHeaders.Location, "/api/v1/books/${book.id}")
call.respond(HttpStatusCode.Created, book)
}
put("{id}") {
call.respond(repo.replace(call.bookId(), call.receive<BookInput>()))
}
patch("{id}") {
call.respond(repo.patch(call.bookId(), call.receive<BookPatch>()))
}
delete("{id}") {
val id = call.bookId()
if (!repo.delete(id)) throw NotFoundException("book $id not found")
call.respond(HttpStatusCode.NoContent)
}
}
}
}
suspend fun ApplicationCall.respondError(
status: HttpStatusCode,
message: String,
details: List<String> = emptyList(),
) = respond(status, ApiError(status.value, status.description, message, details))
fun ApplicationCall.bookId(): Long =
parameters["id"]?.toLongOrNull() ?: throw BadRequestException("id must be a number")
Start it with:
import io.ktor.server.cio.*
import io.ktor.server.engine.*
fun main() {
embeddedServer(CIO, port = 8080) { booksApi() }.start(wait = true)
}
How the pieces fit together:
ContentNegotiationconvertscall.receive<BookInput>()andcall.respond(book)to and from JSON, based on theContent-TypeandAcceptheaders.ignoreUnknownKeyslets old servers accept requests from newer clients that send extra fields.RequestValidationruns right afterreceivedeserializes the body. AnInvalidresult throwsRequestValidationException, so route handlers only ever see valid data.StatusPagesturns exceptions into JSON error responses. Handlers just throw. They never build error responses by hand, so every error has the same shape.- If the body can't be deserialized, Ktor throws
BadRequestException, with the serialization error as itscause. Thestatus(NotFound)handler covers routes that don't exist.
Validation errors from the plugin are reported all at once, not one by one. That saves the client a round trip for each mistake.
Calling the API
testApplication from ktor-server-test-host runs the whole application in memory without opening a port. It's useful for quick experiments as well as tests:
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.testing.*
fun main() = testApplication {
application { booksApi() }
suspend fun show(resp: HttpResponse) {
println("${resp.request.method.value} ${resp.request.url.encodedPathAndQuery} -> ${resp.status}")
resp.headers[HttpHeaders.Location]?.let { println("Location: $it") }
val body = resp.bodyAsText()
if (body.isNotEmpty()) println(body)
println()
}
suspend fun post(json: String) = client.post("/api/v1/books") {
contentType(ContentType.Application.Json)
setBody(json)
}
show(post("""{"title": "The Hobbit", "author": "J.R.R. Tolkien", "year": 1937}"""))
post("""{"title": "Dune", "author": "Frank Herbert", "year": 1965}""")
post("""{"title": "The Silmarillion", "author": "J.R.R. Tolkien", "year": 1977}""")
show(client.get("/api/v1/books/1"))
show(client.get("/api/v1/books?author=tolkien&sort=-year&size=1"))
show(client.patch("/api/v1/books/2") {
contentType(ContentType.Application.Json)
setBody("""{"year": 1966}""")
})
show(client.delete("/api/v1/books/2"))
show(client.get("/api/v1/books/2"))
}
Output:
POST /api/v1/books -> 201 Created
Location: /api/v1/books/1
{
"id": 1,
"title": "The Hobbit",
"author": "J.R.R. Tolkien",
"year": 1937
}
GET /api/v1/books/1 -> 200 OK
{
"id": 1,
"title": "The Hobbit",
"author": "J.R.R. Tolkien",
"year": 1937
}
GET /api/v1/books?author=tolkien&sort=-year&size=1 -> 200 OK
{
"items": [
{
"id": 3,
"title": "The Silmarillion",
"author": "J.R.R. Tolkien",
"year": 1977
}
],
"page": 1,
"size": 1,
"total": 2
}
PATCH /api/v1/books/2 -> 200 OK
{
"id": 2,
"title": "Dune",
"author": "Frank Herbert",
"year": 1966
}
DELETE /api/v1/books/2 -> 204 No Content
GET /api/v1/books/2 -> 404 Not Found
{
"status": 404,
"error": "Not Found",
"message": "book 2 not found"
}
Notice that total counts all matching books, not only the ones on this page. The client needs it to know how many pages there are.
Error responses
Now the failure cases. Each one goes through StatusPages:
show(post("""{"title": " ", "author": "Anon", "year": 99}"""))
show(post("""{"title": "Emma", "year": 1815}"""))
show(post("""{"title": "Emma", "author": "Jane Austen", "year": "soon"}"""))
show(post("""{"title": "Emma", """))
show(post("""{"title": "The Hobbit", "author": "Someone", "year": 2000}"""))
show(client.get("/api/v1/books/abc"))
show(client.get("/api/v1/books?size=500"))
show(client.get("/api/v1/authors"))
Output:
POST /api/v1/books -> 422 Unprocessable Entity
{
"status": 422,
"error": "Unprocessable Entity",
"message": "validation failed",
"details": [
"title must not be blank",
"year must be between 1450 and 2100"
]
}
POST /api/v1/books -> 400 Bad Request
{
"status": 400,
"error": "Bad Request",
"message": "Illegal input: Field 'author' is required for type with serial name 'BookInput', but it was missing at path: $"
}
POST /api/v1/books -> 400 Bad Request
{
"status": 400,
"error": "Bad Request",
"message": "Illegal input: Unexpected JSON token at offset 52: Unexpected symbol 's' in numeric literal at path: $.year"
}
POST /api/v1/books -> 400 Bad Request
{
"status": 400,
"error": "Bad Request",
"message": "Illegal input: Unexpected JSON token at offset 17: Trailing comma before the end of JSON object at path: $.title"
}
POST /api/v1/books -> 409 Conflict
{
"status": 409,
"error": "Conflict",
"message": "a book titled 'The Hobbit' already exists"
}
GET /api/v1/books/abc -> 400 Bad Request
{
"status": 400,
"error": "Bad Request",
"message": "id must be a number"
}
GET /api/v1/books?size=500 -> 400 Bad Request
{
"status": 400,
"error": "Bad Request",
"message": "page must be >= 1 and size between 1 and 100"
}
GET /api/v1/authors -> 404 Not Found
{
"status": 404,
"error": "Not Found",
"message": "no route for GET /api/v1/authors"
}
A few design notes:
- Returning the parser's message for
400helps API users find their mistake. Never do the same for500: log the exception and return a generic message, because stack traces and SQL errors reveal internals. - The
ApiErrorshape here is a simple custom format. RFC 9457 "Problem Details" defines a standard one (type,title,status,detail,instance) served asapplication/problem+json. If you have outside consumers, it's a good default. - The order of
exception<...>handlers doesn't matter. Ktor picks the handler for the most specific exception type, so the catch-allexception<Throwable>only handles what nothing else matches.
Pagination
The API above uses offset pagination (page and size). It's simple and lets clients jump to any page. It has two weaknesses on large or changing tables: OFFSET 100000 in SQL is slow, and inserts between requests shift items so that some are skipped or seen twice.
Cursor (keyset) pagination fixes both. The server returns an opaque token that points just past the last item, and the client sends it back:
import java.util.Base64
@Serializable
data class CursorPage<T>(val items: List<T>, val nextCursor: String?)
get("/api/v1/books-by-cursor") {
val q = call.request.queryParameters
val size = (q["size"]?.toIntOrNull() ?: 20).coerceIn(1, 100)
val afterId = q["cursor"]?.let { c ->
runCatching { String(Base64.getUrlDecoder().decode(c)).toLong() }
.getOrElse { throw BadRequestException("invalid cursor") }
} ?: 0L
// SQL equivalent: WHERE id > :afterId ORDER BY id LIMIT :size + 1
val rows = repo.all().filter { it.id > afterId }.take(size + 1)
val items = rows.take(size)
val next = if (rows.size > size) {
Base64.getUrlEncoder().encodeToString(items.last().id.toString().toByteArray())
} else null
call.respond(CursorPage(items, next))
}
With 5 books, GET /api/v1/books-by-cursor?size=2 returns books 1 and 2 with "nextCursor": "Mg==" (the base64 of 2). Passing cursor=Mg== returns books 3 and 4, and so on. The last page has "nextCursor": null. A tampered cursor gets a 400.
Fetching size + 1 rows tells you whether another page exists without a separate COUNT query. Encoding the cursor keeps clients from building it themselves, so you can change what's inside it later.
A typed client
On the consumer side, wrap the HTTP calls in a class that speaks in domain types. Callers then never deal with URLs, status codes or JSON:
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.serialization.json.Json
class ApiException(val status: HttpStatusCode, val error: ApiError?) :
RuntimeException("HTTP ${status.value}: ${error?.message ?: status.description}")
class BooksClient(baseUrl: String) : AutoCloseable {
private val http = HttpClient(CIO) {
expectSuccess = true // throw on 4xx and 5xx
install(ContentNegotiation) {
json(Json { ignoreUnknownKeys = true }) // tolerate new fields added by the server
}
install(HttpTimeout) {
requestTimeoutMillis = 10_000
}
install(HttpRequestRetry) {
retryOnServerErrors(maxRetries = 3) // 5xx only
exponentialDelay()
}
defaultRequest {
url(baseUrl)
contentType(ContentType.Application.Json)
accept(ContentType.Application.Json)
}
HttpResponseValidator {
handleResponseExceptionWithRequest { cause, _ ->
val e = cause as? ResponseException ?: return@handleResponseExceptionWithRequest
val body = runCatching { e.response.body<ApiError>() }.getOrNull()
throw ApiException(e.response.status, body)
}
}
}
suspend fun list(page: Int = 1, size: Int = 20, author: String? = null): Page<Book> =
http.get("books") {
parameter("page", page)
parameter("size", size)
parameter("author", author) // null values are skipped
}.body()
suspend fun get(id: Long): Book? =
try {
http.get("books/$id").body()
} catch (e: ApiException) {
if (e.status == HttpStatusCode.NotFound) null else throw e
}
suspend fun create(input: BookInput): Book = http.post("books") { setBody(input) }.body()
suspend fun update(id: Long, patch: BookPatch): Book = http.patch("books/$id") { setBody(patch) }.body()
suspend fun delete(id: Long) {
http.delete("books/$id")
}
// Walks all pages lazily; the next page is fetched only when needed
fun all(pageSize: Int = 2): Flow<Book> = flow {
var page = 1
while (true) {
val p = list(page, pageSize)
p.items.forEach { emit(it) }
if (page * pageSize >= p.total) break
page++
}
}
override fun close() = http.close()
}
Notes on the client:
- With
expectSuccess = true, any non-2xx response throws. The validator turns it into anApiExceptionthat carries the server's parsedApiError, so callers can showdetailsto users. getreturnsnullfor404. "Not found" is an expected outcome, not an exceptional one.- The base URL ends with
/and the paths don't start with one. Ktor resolves them like links:books/1is appended tohttp://host/api/v1/, while/books/1would replace the whole path. HttpRequestRetryretries on 5xx and network errors. Only use automatic retries for idempotent requests, or makePOSTidempotent with anIdempotency-Keyheader that the server checks.- Create one
HttpClientand reuse it. Each instance owns a connection pool and threads.
Let's use it against a real server on a random free port:
import io.ktor.server.cio.CIO as ServerCIO
import io.ktor.server.engine.*
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val server = embeddedServer(ServerCIO, port = 0) { booksApi() }.start(wait = false)
val port = server.engine.resolvedConnectors().first().port
BooksClient("http://localhost:$port/api/v1/").use { api ->
val hobbit = api.create(BookInput("The Hobbit", "J.R.R. Tolkien", 1937))
println("created: $hobbit")
api.create(BookInput("Dune", "Frank Herbert", 1965))
api.create(BookInput("Emma", "Jane Austen", 1815))
api.create(BookInput("Beloved", "Toni Morrison", 1987))
api.create(BookInput("Ulysses", "James Joyce", 1922))
println("updated: ${api.update(hobbit.id, BookPatch(title = "The Hobbit, or There and Back Again"))}")
println("first page: ${api.list(page = 1, size = 2).items.map { it.title }}")
println("all titles: ${api.all().toList().map { it.title }}")
api.delete(2)
println("book 2: ${api.get(2)}")
try {
api.create(BookInput("", "Nobody", 3000))
} catch (e: ApiException) {
println("${e.message} ${e.error?.details}")
}
try {
api.delete(42)
} catch (e: ApiException) {
println("status=${e.status.value} error=${e.error?.error}")
}
}
server.stop()
}
Output:
created: Book(id=1, title=The Hobbit, author=J.R.R. Tolkien, year=1937)
updated: Book(id=1, title=The Hobbit, or There and Back Again, author=J.R.R. Tolkien, year=1937)
first page: [The Hobbit, or There and Back Again, Dune]
all titles: [The Hobbit, or There and Back Again, Dune, Emma, Beloved, Ulysses]
book 2: null
HTTP 422: validation failed [title must not be blank, year must be between 1450 and 2100]
status=404 error=Not Found
all() made three requests (pages of 2, 2 and 1 books), but the caller just sees a stream of books.
Testing
testApplication runs routing, plugins, serialization and error handling in memory, so tests exercise the real HTTP contract quickly and without ports. Use createClient to get a client that serializes your DTOs:
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.testing.*
import kotlin.test.*
class BooksApiTest {
// Shared setup: a fresh repository and a JSON-aware client for every test
private fun apiTest(block: suspend ApplicationTestBuilder.(HttpClient) -> Unit) =
testApplication {
application { booksApi(BookRepository()) }
val client = createClient {
install(ContentNegotiation) { json() }
defaultRequest { contentType(ContentType.Application.Json) }
}
block(client)
}
@Test
fun `POST creates a book and returns 201 with Location`() = apiTest { client ->
val resp = client.post("/api/v1/books") { setBody(BookInput("Dune", "Frank Herbert", 1965)) }
assertEquals(HttpStatusCode.Created, resp.status)
val book = resp.body<Book>()
assertEquals("/api/v1/books/${book.id}", resp.headers[HttpHeaders.Location])
assertEquals(book, client.get("/api/v1/books/${book.id}").body<Book>())
}
@Test
fun `invalid input returns 422 with all problems`() = apiTest { client ->
val resp = client.post("/api/v1/books") { setBody(BookInput("", "", 1000)) }
assertEquals(HttpStatusCode.UnprocessableEntity, resp.status)
assertEquals(3, resp.body<ApiError>().details.size)
}
@Test
fun `unknown id returns 404 json error`() = apiTest { client ->
val resp = client.get("/api/v1/books/999")
assertEquals(HttpStatusCode.NotFound, resp.status)
assertEquals("book 999 not found", resp.body<ApiError>().message)
}
@Test
fun `pagination returns requested slice and total`() = apiTest { client ->
repeat(5) { i -> client.post("/api/v1/books") { setBody(BookInput("Book $i", "Author", 2000 + i)) } }
val page = client.get("/api/v1/books?page=2&size=2").body<Page<Book>>()
assertEquals(listOf("Book 2", "Book 3"), page.items.map { it.title })
assertEquals(5, page.total)
}
@Test
fun `DELETE returns 204 then 404`() = apiTest { client ->
val book = client.post("/api/v1/books") { setBody(BookInput("Emma", "Jane Austen", 1815)) }.body<Book>()
assertEquals(HttpStatusCode.NoContent, client.delete("/api/v1/books/${book.id}").status)
assertEquals(HttpStatusCode.NotFound, client.delete("/api/v1/books/${book.id}").status)
}
}
Running the tests with JUnit 6:
BooksApiTest ✔
├─ pagination returns requested slice and total() ✔
├─ invalid input returns 422 with all problems() ✔
├─ POST creates a book and returns 201 with Location() ✔
├─ unknown id returns 404 json error() ✔
└─ DELETE returns 204 then 404() ✔
Test status codes and error bodies, not only the happy path. They are part of the contract clients depend on. To test the BooksClient without a server, give it a MockEngine from ktor-client-mock that returns canned responses.
Best practices
- Version from day one (
/api/v1). Adding fields is backward compatible. Renaming or removing fields, or changing their types, needs a new version. - Be strict in what you validate, tolerant in what you parse. Use
ignoreUnknownKeyson both sides so either one can add fields first. - Return the created or updated resource from
POST,PUTandPATCH. This saves a follow-upGETand shows server-assigned values likeid. - One error format everywhere, produced by
StatusPages, never assembled by hand in handlers. - Bound every list. Always paginate, and cap
size, so one request can't load the whole table. - Don't expose database entities directly. DTOs let the storage schema change without breaking clients and keep fields like password hashes from leaking.
- Document the API. Write an OpenAPI spec, or generate one, so consumers in other languages can generate clients.
- Secure it with Authentication or JWT, serve it over TLS, and configure CORS if browsers on other origins call it.