10
votes

I am trying to use Akka-Http for invoking REST url. I am following this example from the akka documentation. Using this I am able to make the rest call. But I am not able to find out how to add custom request headers. I tried using ModeledCustomHeader, but still request is not having header. Here is my example.

final class ApiTokenHeader(token: String) extends ModeledCustomHeader[ApiTokenHeader] {
  override def renderInRequests = false
  override def renderInResponses = false
  override val companion = ApiTokenHeader
  override def value: String = token
}
object ApiTokenHeader extends ModeledCustomHeaderCompanion[ApiTokenHeader] {
  override val name = "apiKey"
  override def parse(value: String) = Try(new ApiTokenHeader(value))
}

This is how I am invoking,

def invokeHttpRequest(cmd: WSRequestCommand) = {
    val s: HttpRequest = HttpRequest(uri = cmd.url).addHeader(ApiTokenHeader(cmd.apiKey))

    sender ! http.singleRequest(s)
  }

Instead of addHeader, i tried with addHeaders(), but Seq(ApiTokenHeader) is not working as it is giving compilation error.

val s: HttpRequest = HttpRequest(uri = cmd.url, headers = Seq(ApiTokenHeader(cmd.apiKey)))

Error:(55, 66) type mismatch; found : Seq[com.myapp.http.core.ApiTokenHeader] required: scala.collection.immutable.Seq[akka.http.scaladsl.model.HttpHeader] val s: HttpRequest = HttpRequest(uri = cmd.url, headers = Seq(ApiTokenHeader(cmd.apiKey))) //.addHeader(ApiTokenHeader(cmd.apiKey))

Can someone help me to add multiple custom headers for my request ? What am I doing wrong here ?

2
To be able to use the Seq your header needs to extend HttpHeader. - Ende Neu
@EndeNeu Even in single addHeader method, the custom header I have added is not coming in the request. - Yadu Krishnan
Why do you have renderInRequest as false? - leachbj
First thing: you don't have to model custom headers, just use RawHeader(name, value) for one-off usages. - jrudolph
The type error is due to the unfortunate fact, that scala.Seq != scala.collection.immutable.Seq. So, instead of Seq(ApiTokenHeader(...)), you can use either ApiTokenHeader(...) :: Nil to create a List (which is a subtype of immutable.Seq) or use scala.collection.immutable.Seq(ApiTokenHeader(...)). - jrudolph

2 Answers

30
votes

try do it simply you can use the methods on HttpMessage with RawHeaders instead:

HttpRequest(GET, "/example.com/some")
   .withHeaders(
     RawHeader("X-CSRF-TOKEN", ...))
2
votes

You should use scala.collection.immutable.Seq instead of the not immutable one

Also don't forget to set the renderInRequests and/or renderInResponses to true, otherwise your headers will disappear