I want to shorten the route in Akka Http

Viewed 82

I am new to Akka HTTP and I wanted to make route for this -> server/company/:company/authority/:authority/user/:user/region/:region/:regionId/:planTypes

I have made a route like this ->

val route: Route = get {
          pathPrefix("/server") {
            pathPrefix("/company") {
              parameter('company) { company =>
                pathPrefix("/authority") {
                  parameter('authority) { authority =>
                    pathPrefix("user") {
                      parameter('user) { user =>
                        pathPrefix("region") {
                          parameters('region, 'regionId, 'planType) {
                            (region, regionId, planType) =>
                              comleteRequest(tenant, authority, user, region, regionId, planType)
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }

but this looks ugly. Is there a better and shorter way to write it.

1 Answers

You can use:

path("a" / IntNumber / "b" / IntNumber / "c") { 
   (a, b) => _.complete((a + b).toString)
} ~

Then, calling it like so:

http://localhost:8080/a/1/b/2/c

would return 3.

More path matcher details here: https://doc.akka.io/docs/akka-http/current/routing-dsl/path-matchers.html

Slash operator will concatenate two matchers and insert slash between them. You can match path segments with literal strings like server or extractors like RegEx, LongNumber, etc. Each extractor will provide a value, so in my example I use 2 int extractors and use a lambda (a, b) which will be passed 2 ints.

Related