Študijné materiály

Teraz si ukážeme, ako spracovať POST požiadavky - prijatie dát z klienta:

import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.serialization.Serializable
import java.util.concurrent.atomic.AtomicInteger

@Serializable
data class User(val id: Int? = null, val name: String, val email: String)

val users = mutableListOf<User>()
val nextId = AtomicInteger(1)

fun main() {
    embeddedServer(Netty, port = 8080) {
        install(ContentNegotiation) { json() }
        routing {
            get("/users") {
                call.respond(users)
            }

            post("/users") {
                val newUser = call.receive<User>()
                val savedUser = newUser.copy(id = nextId.getAndIncrement())
                users.add(savedUser)
                call.respond(HttpStatusCode.Created, savedUser)
            }
        }
    }.start(wait = true)
}

18.3.1 Testovanie cez curl

# Vytvorenie noveho uzivatela
curl -X POST http://localhost:8080/users \
  -H "Content-Type: application/json" \
  -d '{"name":"Novy","email":"novy@example.com"}'

# Zobrazenie vsetkych
curl http://localhost:8080/users

18.3.2 Ďalšie HTTP metódy

routing {
    put("/users/{id}") {
        val id = call.parameters["id"]?.toIntOrNull()
        val updatedUser = call.receive<User>()
        // aktualizacia...
        call.respond(HttpStatusCode.OK)
    }

    delete("/users/{id}") {
        val id = call.parameters["id"]?.toIntOrNull()
        // vymazanie...
        call.respond(HttpStatusCode.NoContent)
    }
}

call.receive<T>() parí prijaté telo požiadavky do typu T.

Úlohy

Úloha 1

Pridaj endpoint POST /produkty, ktorý prijme JSON produktu a pridelí mu identifikátor.

Úloha 2

Po úspešnom vytvorení vráť stav 201 Created aj uložený objekt.

Úloha 3

Vytvorenie produktu otestuj cez curl a následne ho over cez GET endpoint.