Add default value in Accept header

No matter what the user writes in the Accept header I always want the possibility to return an application/json.

For example if the user requests application/pdf in the Accept header I want primarily to return application/pdf and if the application can not return pdf, return an application/json instead.

Is this possible?

Hello Linda,

You are correct that the Akka HTTP marshalling infrastructure will select a response object serializer taking into account the Accept headers on the request.

You can circumvent this negotiation by constructing the HttpResponse yourself. For example in Scala you can :

complete(
  HttpResponse(
    StatusCodes.OK,
    entity = HttpEntity(ContentTypes.`application/json`, """{ "foo": "bar" }""")
  )
)

This will respond with an application/json entity regardless of the Accept headers on the request. Is that what you were looking for?

You can find some more examples of how to construct a HttpResponse at https://doc.akka.io/docs/akka-http/current/common/http-model.html#httpresponse and in the API docs.

Hi,
No, it does not help.

My problem is that when the user does a post. They will then get a json back with the information about the item they have created.
If the user has written an “incorrect” media type in Accept they will never get the information about that the item that successfully has been created. Instead they just get a 406 back with the message “Resource representation is only available with these types:
application/json”

Hmm, that is interesting, I would not expect that when completing the request with an HttpResponse as I suggested above. Can you share the code you use to produce this response, or (even better) boil it down to a small example project showing the problem?

I can not use what you suggested. Because that would cause a lot special treatment and strange code.

Instead I use headerValueByName(“Accept”) to get the requested media types. For post and delete I then check that it includes / or application/json. If it does not I return 406 before I save or delete anything. When I do it this way nothing will be executed that the user will not know about.

OK, I can’t speak to that of course.

That indeed seems like a reasonable solution, especially when we’re talking about successful responses.

Yes, I did what you suggested for error messages.

1 Like