def headerValueByName(headerName: Symbol): Directive1[String]
def headerValueByName(headerName: String): Directive1[String]


Extracts the value of the HTTP request header with the given name.

The name can be given as a String or as a Symbol. If no header with a matching name 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 optionalHeaderValueByName directive instead.


sourceval route =
  headerValueByName("X-User-Id") { userId =>
    complete(s"The user is $userId")

// tests:
Get("/") ~> RawHeader("X-User-Id", "Joe42") ~> route ~> check {
  responseAs[String] shouldEqual "The user is Joe42"

Get("/") ~> Route.seal(route) ~> check {
  status shouldEqual BadRequest
  responseAs[String] shouldEqual "Request is missing required HTTP header 'X-User-Id'"
sourceimport static akka.http.javadsl.server.Directives.complete;
import static akka.http.javadsl.server.Directives.headerValueByName;

final Route route = headerValueByName("X-User-Id", userId ->
  complete("The user is " + userId)

// tests:
final RawHeader header = RawHeader.create("X-User-Id", "Joe42");
  .assertEntity("The user is Joe42");

  .assertEntity("Request is missing required HTTP header 'X-User-Id'");
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.