Skip to main content

Response Entity Shortcuts

Kleuth provides helper functions to reduce ResponseEntity boilerplate.

Examples#

Http Status 200#

Before:

@Route
class GetPizzas(
private val service: PizzaService
) {
fun handler(): ResponseEntity<List<Pizza>> {
return ResponseEntity.ok(service.getAll())
}
}

After:

@Route
class GetPizzas(
private val service: PizzaService
) {
fun handler() = ok { service.getAll() }
}

Http Status 204#

Before:

@Route
class PutOrder(
private val service: OrderService
) {
fun put(@PathVariable id: UUID, @RequestBody body: Order): ResponseEntity<Unit> {
val existing = service.findById(id) ?: throw Exception("Not Found")
service.update(body)
return ResponseEntity(HttpStatus.NO_CONTENT)
}
}

After:

@Route
class PutOrder(
private val service: OrderService
) {
fun put(@PathVariable id: UUID, @RequestBody body: Order) = `no content` {
val existing = service.findById(id) ?: throw Exception("Not Found")
service.update(body)
}
}

Function References#

The functions can either be called with a body, or with a function reference:

val body = service.get()
return ok(body)

is equivalent to:

return ok { service.get() }

Headers#

Headers can also be passed in:

@Route
class PostOrder(
private val service: OrderService
) {
fun post(@PathVariable id: UUID, @RequestBody body: Order) =
if (service.findById(id) == null) {
val headers = HttpHeaders()
headers.add("existing-id", id.toString())
`no content`(headers)
} else {
created {
val existing = service.findById(id) ?: throw Exception("Not Found")
service.update(body)
}
}
}

Full List#

Http StatusFunction Name
200ok
201created
202accepted
204no content
206partial content
300multiple choices
301moved permanently
302found
303see other