I am writing API in Kotlin - this is my first code in this language. I implemented a very primitive 'player' endpoint. I was wondering if I am doing everything ok (please don't mind the static variables - I will put them in the database later)

import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import pl.domain.Player
import pl.rest.dto.PlayerDto

class PlayerController {

    var players: Map<Long, Player> = mapOf(
            1L to Player(1L, "user1", "password1"),
            2L to Player(2L, "user2", "password2"),
            3L to Player(3L, "user3", "password3")

    fun fetchPlayer(@PathVariable id : Long): ResponseEntity<Player> =
        players[id]?.let { ResponseEntity.ok(it) } ?: ResponseEntity.notFound().build()

    fun createPlayer(@RequestParam username: String, @RequestParam password : String): ResponseEntity<Player> {
        val playerId = (players.size + 1).toLong()
        val player = Player(playerId, username, password)
        players = players.plus(player.id to player)
        return ResponseEntity.ok(player)

    fun updatePlayer(@RequestBody playerDto: PlayerDto): ResponseEntity<Player> {
        return players[playerDto.id]
                ?.apply {
                    username = playerDto.username ?: username
                    password = playerDto.password ?: password
                }?.let { ResponseEntity.ok(it) } ?: ResponseEntity.badRequest().build()

    fun deletePlayer(@PathVariable id: Long): ResponseEntity<Nothing> {
        players = players.minus(id)
        return ResponseEntity.noContent().build()



class PlayerDto(var id: Long? = null, var username: String? = null, var password: String? = null)


data class Player(var id: Long, var username: String, var password: String)

1 Answer 1


I've two recommendations that probably have more to do with design rather than with code. The first one is to change the API path to players:


I personally like to pluralize resource path names even if it's widely discussed.

The other one is to modify your PUT endpoint in order to also accept resources to be created. That way you would have a single endpoint which accepts a list of players, where players might be new or already have an id. For the first case, the system must create them, for the second, update them. That's also a mather of disussion in the net.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.