headerValueByType

Signature

def headerValueByType[T <: HttpHeader: ClassTag](): Directive1[T]

The signature shown is simplified, the real signature uses magnets. [1]

[1] See The Magnet Pattern for an explanation of magnet-based overloading.

Description

Traverses the list of request headers and extracts the first header of the given type.

The headerValueByType directive finds a header of the given type in the list of request header. If no header of the given type is found the request is rejected with a MissingHeaderRejectionMissingHeaderRejection.

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

Note

Custom headers will only be matched by this directive if they extend ModeledCustomHeaderModeledCustomHeader and provide a companion extending ModeledCustomHeaderCompanion, otherwise the routing infrastructure does now know where to search for the needed companion and header name. from the Scala DSL and there is currently no API for the Java DSL (Issue 219)

To learn more about defining custom headers, read: Custom Headers.

Example

Scala
sourceval route =
  headerValueByType(Origin) { origin =>
    complete(s"The first origin was ${origin.origins.head}")
  }

val originHeader = Origin(HttpOrigin("http://localhost:8080"))

// tests:
// extract a header if the type is matching
Get("abc") ~> originHeader ~> route ~> check {
  responseAs[String] shouldEqual "The first origin was http://localhost:8080"
}

// reject a request if no header of the given type is present
Get("abc") ~> route ~> check {
  inside(rejection) { case MissingHeaderRejection("Origin") => }
}
Java
sourceimport static org.apache.pekko.http.javadsl.server.Directives.complete;
import static org.apache.pekko.http.javadsl.server.Directives.headerValueByType;

final Route route =
    headerValueByType(
        Origin.class,
        origin -> complete("The first origin was " + origin.getOrigins().iterator().next()));

// tests:
final Host host = Host.create("localhost", 8080);
final Origin originHeader = Origin.create(HttpOrigin.create("http", host));

testRoute(route)
    .run(HttpRequest.GET("abc").addHeader(originHeader))
    .assertEntity("The first origin was http://localhost:8080");

testRoute(route)
    .run(HttpRequest.GET("abc"))
    .assertStatusCode(StatusCodes.BAD_REQUEST)
    .assertEntity("Request is missing required HTTP header 'Origin'");