I understand that spray does that for me, but I still want to override it with my header, how can I override the header in the response?
My response looks like this:
case HttpRequest(GET, Uri.Path("/something"), _, _, _) =>
sender ! HttpResponse(entity = """{ "key": "value" }""" // here i want to specify also response header i would like to explicitly set it and not get it implicitly
In recent version of Spray (1.2.4 / 1.3.4), you may want to use
respondWithMediaType
. Here is the sample from the documentation :Note that while this overrides the HTTP header value, it will not override the marshaller used for serializing your content to the wire.
Therefore using a recent spray with spray routing, the original code would look like :
The
entity
parameter ofHttpResponse
is actually of typeHttpEntity
and your string is only implicitly converted into an instance ofHttpEntity
. You can use one of the other constructors to specify a content-type. See the source for the possible constructors in the nightly version of spray.Also if you use spray-routing, you can leave marshalling/unmarshalling to the infrastructure.
If you still want to use spray can, then you have two options, based on that HttpResponse is a case class. The first is to pass a List with an explicit content type:
Or, the second way, is to use a method
withHeaders
method:But still, like jrudolph said, it's much better to use spray routing, in this case it would look better:
But spray makes it even easier and handles all (un)marshalling for you:
In this case reponse type will be set to
application/json
by the spray itself.Complete example for my comment:
To add to 4lex1v's answer, there is a very nice, short, simple, working (as of 4/15, scala 2.11.5) tutorial on the GeoTrellis site, including a
build.sbt
. The GeoTrellis pieces are also straightforward to eliminate for the purposes of this stack overflow question.http://geotrellis.io/tutorials/webservice/spray/