An introduction to Akka HTTP routing

If it doesn't match any directive the request is rejected.Now that we now that our request is not matching our directives, let’s start looking into why.If we look the documentation for the path directive (Cmd + Click on Mac) we'll find:/** * Applies the given [[PathMatcher]] to the remaining unmatched path after consuming a leading slash..* The matcher has to match the remaining path completely..* If matched the value extracted by the [[PathMatcher]] is extracted on the directive level..* * @group path */So, the path directive has to match exactly the path, meaning our first path directive will only match /tutorials and never /tutorials/:id.In the same PathDirectives trait that contains the path directive we can see another directive named pathPrefix:/** * Applies the given [[PathMatcher]] to a prefix of the remaining unmatched path after consuming a leading slash..* The matcher has to match a prefix of the remaining path..* If matched the value extracted by the PathMatcher is extracted on the directive level..* * @group path */pathPrefix matches only a prefix and removes it..Sounds like this is what we're looking for, let's update our routes:def route: Route = pathPrefix("tutorials") { get { complete("all tutorials") } ~ path(Segment) { id => get { complete(s"tutorial $id") } }}Run the tests, and… we get another error..????"[all tutorials]" was not equal to "[tutorial hello-world]"ScalaTestFailureLocation: RouterSpec at (RouterSpec.scala:18)Expected :"[tutorial hello-world]"Actual :"[all tutorials]"Looks like our request matched the first get directive..It now matches the pathPrefix, and because it also is a GET request it will match the first get directive..Order matters.There are a couple of things we can do..The simplest solution would be to move the first get request to the end of the hierarchy, however, we would have to remember this or document it.. More details

Leave a Reply