Play Framework 2.7.x APIs routing list

Play framework is not just used for web applications. It’s also used to build Microservices.

The Akka http performance and the actor model are very well suited for building high performance systems utilizing Hexagonal and Reactive architecture techniques.

While, it’s highly recommended to use a dedicated API documentation to document the services’ APIs, still, early during the development phase, you would want to represent the APIs to the UI developers in a simple form.

The code below is a good starting point to learn more about the Play Java flavour and how to offer the UI developers and other team members a simple approach to access the list of routes and APIs.

Get the SBT build tools installed and running on your system and follow the instructions on the link to create a new Java application.

You will need to make changes to the app->HomeController->index() method and the app->views->index.scala.html view template.

Check the code comments for clarifications.

app->HomeController

package controllers;

import com.google.inject.Provider;
import play.Environment;
import play.routing.Router.RouteDocumentation;
import play.routing.Router;
import play.mvc.*;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;

/**
 * This controller contains an action to handle HTTP requests
 * to the application's home page.
 */
public class HomeController extends Controller {

    //Inject the current router instance
    @Inject
    Provider<Router> router;
    //Inject the current environment instance
    @Inject
    play.Environment env;

    /**
     * An action that renders an HTML page with a welcome message.
     * The configuration in the <code>routes</code> file means that
     * this method will be called when the application receives a
     * <code>GET</code> request with a path of <code>/</code>.
     */
    public Result index() {
        //Lis of routes (APIs)
        ArrayList<String> routes = new ArrayList<>();
        //Check to see if we are running in DEV or PROD mode
        if(env.isDev()){
            //Get the list of routes
            List<RouteDocumentation> rd = router.get().documentation();
            rd.forEach(item-> {routes.add(item.getHttpMethod()+" "+item.getPathPattern()+" "+item.getControllerMethodInvocation());
            });}else{
            routes.add("Prod Mode");
        }

        return ok(views.html.index.render(routes));
    }

}

app->views->index.scala.html

@(routes:List[String])

<h1>List of APIs</h1>
@*Iterate through the routes list*@
<ul>
  @for(rout <- routes) {
    <li>@rout</li>
  }
</ul>

Run in Dev mode using sbt run

Run in Prod mode by simulating Prod using sbt runProd
Make sure to add a secret key to your application running in Prod, by adding play.http.secret.key=”secretkey” to the config->application.conf

Now, the UI developers can see the list of APIs by just running the service root.