Server-side typesafe Spine schema usage¶
Implement a Ktor API described with type-safety in common code.
Spine allows us to declare Ktor endpoints in code shared between the client and server.
Declaring a fullstack endpoint¶
First, create a module that will contain the endpoint definition (see the api module), with the following API:
object Api : RootResource("v1") {
object Users : StaticResource<Api>("users", Api) {
val create by post()
.request<CreateUserRequest>()
.response<User>()
}
}
Create a new module, with a dependency on dev.opensavvy.spine:server. Instantiate a Ktor server by following our tutorial. You can now declare the endpoint in your existing routing block:
routing {
route(Api.Users.create) {
// The variable 'body' is automatically created with the correct type
println("Creating a user: ${body.username}")
// The 'respond' method expects the correct response type
respond(User(username = body.username))
}
}