Statically typed REST APIs


#1

The traditional way of accessing a REST API is to send a request without any check against the API about what types are allowed (of course you read documentation, but you don’t get any type checks of the call in the IDE). You request for example “GET /users/5” and get returned JSON representing user with ID 5. You don’t get any hint on the client side that an int is required to be passed, and you get just a JSON string back, not an object of type User.

What if it was possible to access the REST API statically. Let’s say we write something like this on the client-side, in JS-Kotlin:

val user: User? = UsersResource.get(id)

Then on the server, we have

object UsersResource {   
  fun get(id: Int): User? {
    return UsersDao.findById(id)
  }
}

Plus maybe some annotations for path and HTTP method (or, that could go by convention). The User type will be shared between client and server side. The call to the server will be “GET /users/”, and the User will be returned as JSON, containing all the propeties of the User type, example:

{
id: 10,
firstName:"Joe",
lastName:"Jones",
}

On the client side, the JSON will be parsed and a User object will be created. Might need to add a type property to the JSON.

Is there any library like this today? If not, would that be possible to create with the current version of Kotlin? If not, would this be a cool thing to add to Kotlin in the future? The language already offers great possibilities for sharing code between client and server side. Making REST APIs statically typed would take that to a whole new level. What do you think?


#2

Hello,

What you are describing is possible and in fact very similar idea is already fully implemented in KVision framework (it works with Jooby on the server side). Please take a look at the Address book - fullstack example.

Regards,
Robert Jaros


#3

Take a look at GraphQL also. There are frameworks which can generate GraphQL schema based on your Kotlin code.