Danish Khan
Danish Khan

Reputation: 1544

play 2.3.x framework: How to decline all non application/json requests

In play 2.3, how can I automatically reject (return BadRequest) all incoming requests that are not of type application/json? Is there an annotation type like for BodyParsers?

I don't want to add an extra check:

@BodyParser.Of(BodyParser.Json.class)
public static Result sendMessage() {
    JsonNode requestBody = request().body().asJson();
    if (requestBody == null) {
        return badRequest("Bad Request: Not JSON request");
    }
return ok();
}

Upvotes: 0

Views: 287

Answers (1)

biesior
biesior

Reputation: 55798

Probably the most flexible way is creating own interceptor - a.k.a. Action composition

Sample RequiredJson.java (let's place it in new annotations package)

package annotations;

import com.fasterxml.jackson.databind.JsonNode;
import play.libs.F;
import play.mvc.Http;
import play.mvc.Result;

public class RequiredJson extends play.mvc.Action.Simple {
    @Override
    public F.Promise<Result> call(Http.Context ctx) throws Throwable {

        boolean hasCorrectType = ctx.request().getHeader("Content-Type") != null && ctx.request().getHeader("Content-Type").equals("application/json");
        JsonNode json = ctx.request().body().asJson();

        if (!hasCorrectType || json == null) {
            return F.Promise.<Result>pure(badRequest("I want JSON!"));
        }
        return delegate.call(ctx);
    }
}

So you can use this annotation for whole controller(s) or for selected action(s) only like:

@With(annotations.RequiredJson.class)

Result: if Content-Type isn't valid or if incoming data isn't valid JSON it returns badRequest, otherwise it calls the requested action as usually.

Upvotes: 2

Related Questions