pathPrefix

Signature

def pathPrefix[L](pm: PathMatcher[L]): Directive[L]

Description

Matches and consumes a prefix of the unmatched path of the RequestContextRequestContext against the given PathMatcher, potentially extracts one or more values (depending on the type of the argument).

This directive filters incoming requests based on the part of their URI that hasn’t been matched yet by other potentially existing pathPrefix or rawPathPrefix directives on higher levels of the routing structure. Its one parameter is usually an expression evaluating to a PathMatcher instance (see also: The PathMatcher DSL).

As opposed to its rawPathPrefix counterpart pathPrefix automatically adds a leading slash to its PathMatcher argument, you therefore don’t have to start your matching expression with an explicit slash. For a comparison between path directives check Overview of path directives.

Depending on the type of its PathMatcher argument the pathPrefix directive extracts zero or more values from the URI. If the match fails the request is rejected with an empty rejection set.

Note

The empty string (also called empty word or identity) is a neutral element of string concatenation operation, so it will match everything and consume nothing. The path provides more strict behaviour.

Example

Scala
sourceval route =
  pathPrefix("ball") {
    concat(
      pathEnd {
        complete("/ball")
      },
      path(IntNumber) { int =>
        complete(if (int % 2 == 0) "even ball" else "odd ball")
      }
    )
  }

// tests:
Get("/") ~> route ~> check {
  handled shouldEqual false
}

Get("/ball") ~> route ~> check {
  responseAs[String] shouldEqual "/ball"
}

Get("/ball/1337") ~> route ~> check {
  responseAs[String] shouldEqual "odd ball"
}
Java
sourceimport static akka.http.javadsl.server.Directives.path;
import static akka.http.javadsl.server.Directives.pathEnd;
import static akka.http.javadsl.server.Directives.pathPrefix;
final Route route =
    concat(
        pathPrefix("ball", () ->
            concat(
                pathEnd(() -> complete("/ball")),
                path(integerSegment(), (i) ->
                    complete((i % 2 == 0) ? "even ball" : "odd ball"))
            )
        )
    );
// tests:
testRoute(route).run(HttpRequest.GET("/")).assertStatusCode(StatusCodes.NOT_FOUND);
testRoute(route).run(HttpRequest.GET("/ball")).assertEntity("/ball");
testRoute(route).run(HttpRequest.GET("/ball/1337")).assertEntity("odd ball");
Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.