2

I am creating a RESTful service using Play. I want Play to reject any request where the media type is not specified as JSON in the request header.

There tutorial has a good example of this. http://www.playframework.com/documentation/2.0/JavaJsonRequests

Read where it says ...

@BodyParser.Of(Json.class)
public static index sayHello() {
  String name = json.findPath("name").getTextValue();
  if(name == null) {
    return badRequest("Missing parameter [name]");
  } else {
    return ok("Hello " + name);
  }
}

Note: This way, a 400 HTTP response will be automatically returned for non JSON requests.

Why is it returning HTTP error 400, bad request, instead of HTTP error 415, unsupported media type?

Is there a way to change this behavior?

Marc M.
  • 3,631
  • 4
  • 32
  • 53
  • 1
    I'm not sure if they are talking about the header or the content. A 400 response seems fine if the header is set to json but the content is in another format. If it's about the header than that you are right, 415 seems more appropriate. Did you test it and saw the wrong response? If yes, you could file a bug report if there isn't any yet. – kapex Oct 06 '13 at 15:19
  • 1
    Kapep's request for clarification is a good one. If you set the `Content-header` in your request to `application/json` and you received a 400 for **valid json** then you have found a bug in the BodyParser middleware. If your JSON is malformed or the header is not sent, 400 is okay. A possible fix is to maybe build your own JSON parsing annotation for body (perhaps by extending an existing bodyparser), though that seems like overkill. – Ray Toal Oct 06 '13 at 18:29
  • I think I was always getting 400 let me check. Thanks great point. – Marc M. Oct 06 '13 at 20:01

1 Answers1

3

You can return a custom HTTP response with the status(int, String) method:

return status(415, "The only supported content type is application/json");
Ray Toal
  • 86,166
  • 18
  • 182
  • 232
aaberg
  • 2,253
  • 15
  • 14
  • Unless I am misunderstanding 415, I am not sure a missing parameter or malformed JSON would constitute a 415. request().body().asJson(); May return null for a lot of reasons. The JSON may be malformed, but the Content-type header is still valued as application/json, so it's still not a unsuproted media you are getting, but a malformed one. – Marc M. Oct 06 '13 at 19:55
  • 1
    I think the answerer meant you could return a 415 directly from your code but just didn't take the time to show a new error message. I took the liberty to edit the answer. Hope it's okay, @aaberg. – Ray Toal Oct 07 '13 at 00:25