1

Is there any way to validate the patch request body in spring boot?

Ex:
[
  {"op": "replace", "path": "/id", "value": "foo"},
   {"op": "replace", "path": "/id2", "value": "foo2"}
]

if any user sends the request with "op"(field) as "xx" and "path"(field) as "se". Is there any way to validate it and throw 400 (Bad Request), without changing the contract?

Udara Gunathilake
  • 202
  • 1
  • 2
  • 14
  • This isn't really clear to me. Did you write your own REST controller? Do you want to verify that `"op"` is a specific value (eg `"replace"` but not `"xx"`)? What do you mean by "without changing the contract"? Is your request body structure the contract? – g00glen00b Aug 10 '17 at 13:05
  • 1
    You can go through this article: http://www.baeldung.com/spring-data-rest-validators – SkyWalker Aug 10 '17 at 13:06
  • @g00glen00b yes. I meant the request body. In my question, I'm referring "op" field not the "op" value("replace") – Udara Gunathilake Aug 10 '17 at 15:44
  • Maybe you can provide (at least) the method signature ? you probably need to add a @ Valid before your @ RequestBody – Gremi64 Aug 10 '17 at 15:56
  • @Gremi64 @ Valid is not working as expected when the body is a List. Patch request body is a list. – Udara Gunathilake Aug 11 '17 at 00:03
  • 1
    Possibly a duplicate of https://stackoverflow.com/questions/17207766/spring-mvc-valid-on-list-of-beans-in-rest-service or https://stackoverflow.com/questions/28150405/validation-of-a-list-of-objects-in-spring or https://stackoverflow.com/questions/39348234/spring-boot-how-to-use-valid-with-listt – g00glen00b Aug 11 '17 at 05:35
  • Maybe you can do a foreach on your list and apply javax validator on each element ? – Gremi64 Aug 11 '17 at 08:48
  • Yeap Gremi64 :( . I think that is the solution. I thought there is a better way to do this. But I can't find any other solution. – Udara Gunathilake Aug 14 '17 at 07:57

1 Answers1

3

I tried many ways to solve this. But finally had to go with this solution.

My patch request signature:

public void patch(@RequestBody List<PatchOperation> operations)

I created a simple function to verify valid patch keys are present in the request.

void validatePatchOperation(PatchOperation patchOperation) {
    if (patchOperation.getOp() == null) {
        throw new BadRequestException();
    }
    if (patchOperation.getPath() == null) {
        throw new BadRequestException();
    }
    if (patchOperation.getValue() == null) {
        throw new BadRequestException();
    }
}

And used this inside a for-each

buræquete
  • 14,226
  • 4
  • 44
  • 89
Udara Gunathilake
  • 202
  • 1
  • 2
  • 14