optionalHeaderValueByName

Signature

def optionalHeaderValueByName(headerName: Symbol): Directive1[Option[String]] 
def optionalHeaderValueByName(headerName: String): Directive1[Option[String]] 

Description

Optionally extracts the value of the HTTP request header with the given name.

The optionalHeaderValueByName directive is similar to the headerValueByName directive but always extracts an OptionOptional value instead of rejecting the request if no matching header could be found.

Example

Scala
sourceval route =
  optionalHeaderValueByName("X-User-Id") {
    case Some(userId) => complete(s"The user is $userId")
    case None         => complete(s"No user was provided")
  } ~ // can also be written as:
  optionalHeaderValueByName("X-User-Id") { userId =>
    complete {
      userId match {
        case Some(u) => s"The user is $u"
        case _       => "No user was provided"
      }
    }
  }

// tests:
Get("/") ~> RawHeader("X-User-Id", "Joe42") ~> route ~> check {
  responseAs[String] shouldEqual "The user is Joe42"
}
Get("/") ~> Route.seal(route) ~> check {
  responseAs[String] shouldEqual "No user was provided"
}
Java
sourceimport static org.apache.pekko.http.javadsl.server.Directives.complete;
import static org.apache.pekko.http.javadsl.server.Directives.optionalHeaderValueByName;

final Route route =
    optionalHeaderValueByName(
        "X-User-Id",
        userId -> {
          if (userId.isPresent()) {
            return complete("The user is " + userId.get());
          } else {
            return complete("No user was provided");
          }
        });

// tests:
final RawHeader header = RawHeader.create("X-User-Id", "Joe42");
testRoute(route).run(HttpRequest.GET("/").addHeader(header)).assertEntity("The user is Joe42");

testRoute(route).run(HttpRequest.GET("/")).assertEntity("No user was provided");