How to get http request header info from the server side with spray RestAPI

3.1k views Asked by At

I am new to Scala and Spray. I have written a simple REST API according to the instructions given in this blog post. http://www.smartjava.org/content/first-steps-rest-spray-and-scala

And all are working as expected.

Now I want to modify the program to print the HTTP headers like Encoding, Language, remote-address, etc.. I would like to print all the header information (purpose is to log these information)

But I could not find a proper documentation or examples. Could anyone please help me to get this done.

2

There are 2 answers

6
Gabriele Petronella On BEST ANSWER

If you need to extract a specific header:

optionalHeaderValueByName("Encoding") { encodingHeader =>
  println(encodingHeader)
  complete("hello")
}

alternatively you can access the raw request object and directly extractive the headers. Here's a custom directive that logs all the headers:

def logHeaders(): Directive0 = extract(_.request.headers).map(println)

Usage

logHeaders() {
  complete("hello")
}
0
jasop On

Here's how I got it working.

Directive:

def logHeaders(innerRoute: Route): (RequestContext => Unit) = extract(_.request.headers) { headers =>
  headers.foreach(h => logger.info("header: {} = {}", h.name, h.value))
  innerRoute
}

Usage:

logHeaders() {
  complete("hello")
}