mapResponse

Signature

def mapResponse(f: HttpResponse 

Description

The mapResponse directive is used as a building block for Custom Directives to transform a response that was generated by the inner route. This directive transforms complete responses.

See also mapResponseHeaders or mapResponseEntity for more specialized variants and Response Transforming Directives for similar directives.

Example: Override status

Scala
sourcedef overwriteResultStatus(response: HttpResponse): HttpResponse =
  response.withStatus(StatusCodes.BadGateway)
val route = mapResponse(overwriteResultStatus)(complete("abc"))

// tests:
Get("/abcdef?ghi=12") ~> route ~> check {
  status shouldEqual StatusCodes.BadGateway
}
Java
sourceimport static org.apache.pekko.http.javadsl.server.Directives.mapResponse;

final Route route =
    mapResponse(
        response -> response.withStatus(StatusCodes.BAD_GATEWAY), () -> complete("abc"));

// tests:
testRoute(route)
    .run(HttpRequest.GET("/abcdef?ghi=12"))
    .assertStatusCode(StatusCodes.BAD_GATEWAY);

Example: Default to empty JSON response on errors

Scala
sourcetrait ApiRoutes {
  protected def system: ActorSystem

  private val log = Logging(system, "ApiRoutes")

  private val NullJsonEntity = HttpEntity(ContentTypes.`application/json`, "{}")

  private def nonSuccessToEmptyJsonEntity(response: HttpResponse): HttpResponse =
    response.status match {
      case code if code.isSuccess => response
      case code =>
        log.warning("Dropping response entity since response status code was: {}", code)
        response.withEntity(NullJsonEntity)
    }

  /** Wrapper for all of our JSON API routes */
  def apiRoute(innerRoutes: => Route): Route =
    mapResponse(nonSuccessToEmptyJsonEntity)(innerRoutes)
}
val route: Route =
  apiRoute {
    get {
      complete(InternalServerError)
    }
  }

// tests:
Get("/") ~> route ~> check {
  responseAs[String] shouldEqual "{}"
}
Java
sourceclass ApiRoute {

  private final ActorSystem system;

  private final LoggingAdapter log;

  private final HttpEntity nullJsonEntity =
      HttpEntities.create(ContentTypes.APPLICATION_JSON, "{}");

  public ApiRoute(ActorSystem system) {
    this.system = system;
    this.log = Logging.getLogger(system, "ApiRoutes");
  }

  private HttpResponse nonSuccessToEmptyJsonEntity(HttpResponse response) {
    if (response.status().isSuccess()) {
      return response;
    } else {
      log.warning(
          "Dropping response entity since response status code was: " + response.status());
      return response.withEntity((ResponseEntity) nullJsonEntity);
    }
  }

  /** Wrapper for all of our JSON API routes */
  private Route apiRoute(Supplier<Route> innerRoutes) {
    return mapResponse(this::nonSuccessToEmptyJsonEntity, innerRoutes);
  }
}

final ApiRoute api = new ApiRoute(system());

final Route route = api.apiRoute(() -> get(() -> complete(StatusCodes.INTERNAL_SERVER_ERROR)));

// tests:
testRoute(route).run(HttpRequest.GET("/")).assertEntity("{}");