Akka HTTP api routes structure

Viewed 1534

I'm writing Akka-HTTP based REST API. As I'm new to Akka and Scala, I'm not sure what could be the best way of organize code in my project. I will have approx. 7 different entities with basic CRUD. Which means I will have over 25 routes in the API. I would like to keep routes grouped based on the entity they are logically associated with. What could be a good way to achieve this ? Currently I took inspiration from some of the projects available on the GitHub, and grouped those routes into traits. I have a main trait which include some general stuff, extends Directive and adds marshaling:

trait Resource extends Directives with JsonSupport{
   ...
}

Then I have other routes organized like the one below.

trait UserResource extends Resource{

  def userRoutes:Route =
    pathPrefix("authenticate") {
      pathEndOrSingleSlash {
        post {
          entity(as[LoginRequest]) { request =>
            ...
            }
          }
        }
      }
    } ~
    pathPrefix("subscribe") {
      pathEndOrSingleSlash {
        post {
          entity(as[UserSubscribeRequest]) { request =>
            ...
            }
          }
        }
      }
    }
}

There is a class which defines exception handlers, instantiates some helpers and puts routes together:

class Routes extends UserResource with OtherResource with SomeOtherResource{

  ... handlers definitions ...
  ... helpers ...

  def allRoutesUnified: Route =
    handleErrors {
     cors() {
        pathPrefix("api") {
          authenticateOAuth2("api", PasswordAuthenticator) { _ =>
            //Routes defined in other traits
            otherRoutes ~ someOtherRoutes
          } 
        } ~ userRoutes  
      }
   }
}

Finally in the app entry point:

object Main extends App{

  ... usual Akka stuff ..

  val routes = new Routes ()
  val router = routes.allRoutesUnified
  Http().bindAndHandle(router, "localhost", 8080)
}

What could be some better or more elegant ways of organizing routes ?

1 Answers
Related