Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Akka-http: How to get custom header from a request?

I send following headers in a request to my akka-http api: "Content-type": "application/json", "Accept": "application/json", "AppId": "some_id".

How do I get "AppId" custom header in my akka-http route?

(get & parameters("id")) { (id) =>
      complete {
        val appId = ?? // I want to get custom header here.
      }
    } 

Thanks.

like image 987
user3024710 Avatar asked Dec 05 '22 02:12

user3024710


2 Answers

You need to use one of the HeaderDirectives (HeaderDirectives docs) to extract the header. For example, if it's a custom one you can use headerValueByName which yields the value of the header, and rejects the route if the header was not present (if the header is optional you can use optionalHeaderValueByName):

headerValueByName("AppId") { appId =>
  complete(s"The AppId was: $appId")
}

Happy hakking!

like image 173
Konrad 'ktoso' Malawski Avatar answered Dec 17 '22 08:12

Konrad 'ktoso' Malawski


I actually prefer creating custom directive for things like authentication tokens, app ids and other parameters that are sort of mandatory for serving client's request. In your case it might look like this

val extractAppId = (headerValueByName("AppId") | headerValueByName("AppId2")).tflatMap[Tuple1[String]] {
  case Tuple1(appId) =>
    if (!appId.equalsIgnoreCase("BannedAppId"))
      provide(appId)
    else
      complete(StatusCodes.Forbidden -> "Your application is banned")
}.recover {
  case rejections => reject(ValidationRejection("AppId is not provided"))
}

which is used like

extractAppId { appId =>
 get {
  complete {
   "Your AppId is " + appId
  }
 }
}

To make my example more interesting I added support of conditional response based on provided AppId.

like image 26
expert Avatar answered Dec 17 '22 07:12

expert