attribute

Signature

def attribute[T](key: AttributeKey[T]): Directive1[T]

Description

Extracts the value of the request attribute with the given key.

If no attribute is found for the given key the request is rejected with a MissingAttributeRejectionMissingAttributeRejection.

If the attribute is expected to be missing in some cases or to customize handling when the header is missing use the optionalAttribute directive instead.

Example

Scala
sourceval userId = AttributeKey[String]("user-id")

val route =
  attribute(userId) { userId =>
    complete(s"The user is $userId")
  }

// tests:
Get("/") ~> addAttribute(userId, "Joe42") ~> route ~> check {
  responseAs[String] shouldEqual "The user is Joe42"
}

Get("/") ~> Route.seal(route) ~> check {
  status shouldEqual InternalServerError
}
Java
sourceAttributeKey<String> userId = AttributeKey.create("user-id", String.class);

final Route route = attribute(userId, id ->
  complete("The user is " + id)
);

// tests:
testRoute(route).run(HttpRequest.GET("/").addAttribute(userId, "Joe42"))
  .assertEntity("The user is Joe42");

testRoute(route).run(HttpRequest.GET("/"))
  .assertStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
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.