ct
04/10/2022, 3:57 PM@Serializable
data class Agent(val id: Int, val hostname: String, val port: Int)
I’m struggling with handling POST:
@Serializable
@Resource("/api/agents")
data class AgentsRoute(val sort: String? = "id") {
@Serializable
@Resource("{id}")
data class Id(val parent: AgentsRoute = AgentsRoute(), val id: Int)
}
fun Application.agentRoutes() {
val agentService = AgentService() // Talks to the database
routing {
get<AgentsRoute> {
call.respond(agentService.getAll())
}
get<AgentsRoute.Id> { request ->
val agent = agentService.get(request.id) ?: call.respond(
HttpStatusCode.NotFound, "Agent not found"
)
call.respond(agent)
}
post<AgentsRoute> {
val agent = call.receive<Agent>() // This blows up!
// TODO
}
delete<AgentsRoute.Id> { request ->
agentService.get(request.id) ?: call.respond(
HttpStatusCode.NotFound, "Agent not found"
)
call.respond(agentService.delete(request.id))
}
}
}
I’m having a problem with the POST
when I post some data to create a new agent:
{
"hostname": "192.168.1.1",
"port": 1012
}
Here’s the exception:
2022-04-10 16:51:06.740 [eventLoopGroupProxy-4-1] ERROR Application - Unhandled: POST - /api/agents/
kotlinx.serialization.MissingFieldException: Field 'id' is required for type with serial name 'com.sonalake.snmpsim.model.Agent', but it was missing
at kotlinx.serialization.internal.PluginExceptionsKt.throwMissingFieldException(PluginExceptions.kt:20)
I understand why it’s happening - the JSON doesn’t contain an id property - but, as I want to create a new agent I don’t want to have to provide one.
I had a look at the Ktor 2.0.0 resource-routing code snippet, but it didn’t go further than receiving the request. Any suggests on the idiomatic Ktor 2 way of doing this?
Thank you 🙇Sebastian Owodzin
04/10/2022, 8:25 PMid
property is the problem you can always declare the default value to be -1
or somethingct
04/10/2022, 8:30 PMSebastian Owodzin
04/10/2022, 8:30 PMid
to be used when you receive POST.ct
04/10/2022, 8:38 PMid
would be an option.James Black
04/11/2022, 4:39 AMct
04/11/2022, 2:00 PMid
, one without).