I was working on a Play! Framework project and I was wondering why our whole API was available in one piece. It got me thinking whether there is a way to hide at least some parts of the API from the clients. Precisely because some of the clients didn’t have the privilege/permission to execute given operations, e.g. visiting restricted pages. I thought there should be a way to hide at least the operations that are on these restricted pages. I’ve found a way to do so and below it is.
We had a controller for each business object, so most of the views were served from a few huge classes with all the logic implemented in those.
The provided routing had to be made accessible to the frontend. Creating an API call is as follows:
Making it accessible from the frontend.
GET /assets/js/routes controllers.Application.jsRoutes()
And in our main.scala.html:
Usage from your code
In this case you just made every url accessible from your client-side/frontend. There are a few problems with this approach:
First of all we changed how we separate functionalities. Each view had its own controller with a service specified for the specific functionality and common service for the common stuff. We moved the routing to each controller, but collected it into one huge jsRoutes.js as before. In this case the Application.java has been modified.
Your full API is still available in one piece, but the code maintenance has been decreased drastically because you can find all your code where it belongs locally.
The next step is to reduce the surface of your observable interface at a time. If you prefer this case, you need a little ceremony to create your implementation. First of all you need to create a new line in your routes file for each view.
GET /assets/js/pets/view/routes controllers.PetCtrl.jsRoutes()
Each of your Controller file should be modified a little:
Your view should download this routing for every view but it contains only the required functionality.
You can call them like this:
As you can see (petRoutes) you can specify the “namespace” with this approach.
It costs you only a short ceremony to:
I hope this will prove to be a useful resource to many of my fellow backend developers! If you have any questions or related solutions, let me know! :)
[Editor’s note: to learn more about the author, visit our Facebook page.]