mapRequest

Signature

def mapRequest(f: HttpRequest ⇒ HttpRequest): Directive0

Description

Transforms the request before it is handled by the inner route.

The mapRequest directive is used as a building block for Custom Directives to transform a request before it is handled by the inner route. Changing the request.uri parameter has no effect on path matching in the inner route because the unmatched path is a separate field of the RequestContextRequestContext value which is passed into routes. To change the unmatched path or other fields of the RequestContextRequestContext use the mapRequestContext directive.

See Request Transforming Directives for an overview of similar directives.

Example

Scala
def transformToPostRequest(req: HttpRequest): HttpRequest = req.copy(method = HttpMethods.POST)
val route =
  mapRequest(transformToPostRequest) {
    extractRequest { req =>
      complete(s"The request method was ${req.method.name}")
    }
  }

Get("/") ~> route ~> check {
  responseAs[String] shouldEqual "The request method was POST"
}
Java
import static akka.http.javadsl.server.Directives.mapRequest;

import static akka.http.javadsl.server.Directives.extractRequest;
import static akka.http.javadsl.server.Directives.mapRequest;

final Route route = mapRequest(req ->
  req.withMethod(HttpMethods.POST), () ->
  extractRequest(req -> complete("The request method was " + req.method().name()))
);

// tests:
testRoute(route).run(HttpRequest.GET("/"))
  .assertEntity("The request method was POST");
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.