This is just something I was playing around with when discussing how to build proper tooling for our teams at work. Play has the idea of an Action which is basically a function that takes a Request object and returns a Result object. Each of those can be parameterized for the content type being transmitted.

However, when you’re working in an API, you typically work with some exchange format (e.g. JSON) and then serialize and de-serialize to/from your internal data model. If you are using Scala, then possibly some case classes. Rather than having to worry about the exchange format, developers should really just worry about these data-models when writing their code.

So, just the result of me playing with the idea for a few minutes:

 1 object TypedAction {
 2   def TypedAction[A,B](f: A => B)(implicit reader: Reads[A], writer: Writes[B]) : Action[String] =
 3     Action.async(BodyParsers.parse.tolerantText) { request =>
 4       val json = Json.parse(request.body)
 5       Future.successful {
 6         val badRequest: Result = Results.BadRequest("Could not parse input")
 7         json.asOpt[A](reader).map(f).map(Json.toJson(_)(writer)).map(_.toString()).map(Results.Ok(_)).getOrElse(badRequest)
 8       } : Future[Result]
 9     }
10 
11   def TypedAction[B](f: () => B)(implicit writer: Writes[B]): Action[String] =
12     Action.async(BodyParsers.parse.tolerantText) { request =>
13       Future.successful {
14         Results.Ok(Json.toJson(f())(writer).toString)
15       }
16     }
17 }

And then using the model

1 case class UserModel(id: Int, name: String)
2 
3 object UserModel {
4   implicit val reads = Json.reads[UserModel]
5   implicit val writes = Json.writes[UserModel]
6 }

We can create a controller that looks like

 1 object UserController extends Controller {
 2 
 3   var userStore = Map(
 4     1 -> UserModel(1, "Joe Schmoe"),
 5     2 -> UserModel(2, "Susy Jane"),
 6     3 -> UserModel(3, "Jenny Jackson")
 7   )
 8 
 9   def getUser(id: Int) = TypedAction[UserModel] { () =>
10     userStore(id)
11   }
12 
13   def storeUser = TypedAction[UserModel, UserModel] { userIn =>
14     val nextKey = userStore.keys.max + 1
15     userStore += nextKey -> userIn
16     userIn.copy(id = nextKey)
17   }
18 
19 }

We could also create different input and output models within the same controller method. In addition, if you really wanted to do something like this you would need to handle errors much better, both from the user code and from the parsing code. I’m also not really doing anything with the Action.async portion above, so that could be improved as well.

But yeah, just some (light) food for thought.