Ali
Ali

Reputation: 267077

How to nest routes in Akka HTTP?

I'm trying to write a simple series of routes, here's what I want to happen:

GET / should print "hello get"

POST / should print "hello post"

GET /foo should print "hello foo get"

POST /foo should print "hello foo get"

Here's what I have:

val route = pathSingleSlash {
    get(complete("hello get")) ~
    post(complete("hello post"))~
    path("foo") {
      get(complete("hello foo get"))~
      post(complete("hello foo post"))
    }
  }

This works for GET / and POST / but both GET and POST on /foo 404.

I've tried almost everything and can't figure out what to do. The documentation is pretty hard to understand when it comes to this.

Can anyone give me any pointers?

Upvotes: 0

Views: 578

Answers (2)

Mon Calamari
Mon Calamari

Reputation: 4463

I would recommend structuring the paths this way for maximum readability:

get & pathEndOrSingleSlash {
  complete("hello get")
} ~
post & pathEndOrSingleSlash {
  complete("hello post")
} ~
get & path("foo") & pathEndOrSingleSlash {
  complete("hello foo get")
}
post & path("foo") & pathEndOrSingleSlash {
  complete("hello foo post")
}

Upvotes: 1

Raman Mishra
Raman Mishra

Reputation: 2686

can you please try this. it is working for me.

val route1 = path("foo") {
        get(complete("hello foo get")) ~
          post(complete("hello foo post"))
      }

  val route = pathSingleSlash {
    get(complete("hello get")) ~
      post(complete("hello post"))
  }

  val finalRoute = route ~ route1

and use finalRoute in your route binding statement.

val bindingFuture = Http().bindAndHandle(finalRoute, "localhost", 8085)

Upvotes: 2

Related Questions