scalasprayspray-test

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


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.


Solution

  • 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")
    }