https://kotlinlang.org logo
#ktor
Title
# ktor
l

leus

01/26/2018, 2:02 PM
Is it possible to use Locations with POST?
Copy code
@Location("/v1/check") class IntegrationsContainer

...

post<IntegrationsContainerC> { body ->
call.respond(realAppLogic(body))
}
but I get
2018-01-26 10:59:50.226 [nettyCallPool-4-1] ERROR Application - Unhandled: POST - /v1/check
s

spand

01/26/2018, 2:05 PM
The properties in
IntegrationsContainerC
cannot be used for post variables
l

leus

01/26/2018, 2:05 PM
what about JSON?
s

spand

01/26/2018, 2:06 PM
Only get variables
l

leus

01/26/2018, 2:11 PM
Ok - so no locations
s

spand

01/26/2018, 2:16 PM
Well, you can still use locations but you just cannot route based on post body data
k

kristofdho

01/26/2018, 2:31 PM
Copy code
@Location("/")
class Post(val test: Int) //only query params

data class Body(val x: Int) //actual body

post<Post> { post ->// contains query params
    val body = call.receive<Body>() // contains body
    call.respond(body)
}
the unhandled POST probably means you did not specify all the query params in the
IntegrationsContainer
class
l

leus

01/26/2018, 2:59 PM
Ok - so the class uses in Location is just for (mandatory?) query params, and I need to use
call.receive<T>()
to get my actual class
but if my class (the
Body
class above) is a complex one, can it be used? If I get a JSON body with a
Content-Type: application/json
header, can I use something like Content-Negotiation feature, or should I just use a plain string / JSON serializer by hand?
s

spand

01/26/2018, 3:03 PM
You can have optional query params also. I think they just need a default value. ie
class Foo(val bar : String = "")
No experience with the built in json
k

kristofdho

01/26/2018, 3:09 PM
content negotiation works with the exact same code
you just need to install one of the json features (gson, jackson) and it just works
l

leus

01/29/2018, 5:55 PM
As an update, it indeeds magically works
Copy code
fun Application.main() {
    install(DefaultHeaders)
    install(CallLogging)
    install(ContentNegotiation) {
        install(ContentNegotiation) {
            jackson {
                configure(SerializationFeature.INDENT_OUTPUT, true)
                registerModule(JavaTimeModule())
            }
        }
    }

    routing {
       post("/v1/check") {
            try {
                val myObj = call.receive<MyObject>()
                call.respond(HttpStatusCode.OK)
            } catch (e: Exception) {
                call.respond(HttpStatusCode.BadRequest)
            }
        }
    }
}
k

kristofdho

01/29/2018, 6:06 PM
you have duplicate
install(ContentNegotiation)
calls, just a minor oversight