11@file:JvmName(" APIServer" )
22
33
4-
54import io.ktor.application.call
65import io.ktor.application.install
76import io.ktor.features.CallLogging
87import io.ktor.features.ContentNegotiation
98import io.ktor.features.DefaultHeaders
109import io.ktor.gson.gson
11- import io.ktor.http.ContentType
1210import io.ktor.request.path
11+ import io.ktor.request.receive
1312import io.ktor.response.respond
14- import io.ktor.response.respondText
15- import io.ktor.routing.get
16- import io.ktor.routing.routing
13+ import io.ktor.routing.*
1714import io.ktor.server.engine.embeddedServer
1815import io.ktor.server.netty.Netty
1916import org.slf4j.event.Level
2017
2118data class Author (val name : String , val website : String )
19+ data class ToDo (var id : Int , val name : String , val description : String , val completed : Boolean )
20+
2221fun main (args : Array <String >) {
2322
23+ val toDoList = ArrayList <ToDo >();
2424 val jsonResponse = """ {
2525 "id": 1,
2626 "task": "Pay waterbill",
@@ -42,15 +42,31 @@ fun main(args: Array<String>) {
4242 setPrettyPrinting()
4343 }
4444 }
45- routing {
46- get(" /todo" ) {
47- call.respondText(jsonResponse, ContentType .Application .Json )
48- }
49- get(" /author" ) {
50- val author = Author (" baeldung" , " baeldung.com" )
51- call.respond(author)
45+ routing() {
46+ route(" /todo" ) {
47+ post {
48+ var toDo = call.receive<ToDo >();
49+ toDo.id = toDoList.size;
50+ toDoList.add(toDo);
51+ call.respond(" Added" )
52+
53+ }
54+ delete(" /{id}" ) {
55+ call.respond(toDoList.removeAt(call.parameters[" id" ]!! .toInt()));
56+ }
57+ get(" /{id}" ) {
5258
59+ call.respond(toDoList[call.parameters[" id" ]!! .toInt()]);
60+ }
61+ get {
62+ call.respond(toDoList);
63+ }
5364 }
65+ get(" /author" ){
66+ call.respond(Author (" Baeldung" ," baeldung.com" ));
67+
68+ }
69+
5470
5571 }
5672 }.start(wait = true )
0 commit comments