Hello,
I’m new to Akka, I’d like some help in setting up a route that returns application/json
whether request contains Accept
header with a different type or not, I want to return json in any and all cases for that route.
I have the following setup:
val routes: Route = get {
path("foo") {
// works with all Accept header values, but I would like to try it without explicitly setting application/json content type in all my routes.
complete(
HttpResponse(
StatusCodes.OK,
entity = HttpEntity(ContentTypes.`application/json`, """{ "foo": "bar" }""")
)
)
} ~
path("bar") {
// only works with text/plain only, i want /bar to return json even when accept: text/csv is in request.
complete("""{ "foo": "bar" }""")
}
}
When I try to curl -X GET localhost:8080/bar -H "Accept: text/csv"
It returns:
Resource representation is only available with these types:
text/plain
What I want is to get json result even when I send text/csv in accept header or any other content type:
curl -X GET localhost:8080/bar -H "Accept: text/csv"
Result should be JSON of: { "foo": "bar" }
After searching akka docs I found withAcceptAll
but I wasn’t able to use it like extract directives, and there’s no example in docs to follow, I tried to set it up like this:
(path("bar") & get) {
extractRequestContext { ctx =>
ctx.withAcceptAll.complete("""{ "foo": "bar" }""".parseJson)
}
}
expected: RequestContext => server.Route
Found it in routing docs, this works:
(path("barx") & get) { ctx: RequestContext =>
ctx.withAcceptAll.complete("""{ "foo": "bar" }""".parseJson)
}
Thanks.