-2

I am creating a dynamic parameter rest api using spring boot and I would like to throw an exception if any field passed as parameter does not exist

This is a get call using request parameters like this one: http://localhost:8080/action?prop1=a

I have a class:

public class MyObject {
    private String prop1;
}

and a getMapping:

@GetMapping(value = "/action")
public @ResponseBody List<MyObject> myAction(MyObject myObject) { ... }

If I call http://localhost:8080/action?prop1=x&prop_that_does_not_exist=z I would like to get an exception because prop_that_does_not_exist does not exist in MyObject.

Is there any annotation for it? Is there any way to achieve this behavior?

I would like to get an error in the example added but I would not like (if possible) to change the object binding to something like myAction(Map<String, String> map).

Thanks!

fmezini
  • 17
  • 4

1 Answers1

0

Please don't confuse that:

@RequestBody: it gets data from body of request, not from url
@PathVariable: it gets data as path variable e.g: /api/<myData>
@RequestParam: it gets params from url e.g: /api?param1=val1&param2=val2

You can use @Valid annotation (from javax.validation) for your @RequestBody and you can set constraints for fields:

@RestController
@RequestMapping("/api")
public class MyController {

@GetMapping(value = "/action")
public List<MyObject> myAction(@Valid MyObject myObject) { ... }

}

public class MyObject {
    @NotBlank 
    private String prop1;

    @Email @NotBlank
    private String prop2;

    @Min(0) 
    @Max(5)   
    private Int prop3;

}

Or if you want to get valid parameters without the RequestBody object, you can use @RequestParam. If you set required=true and don't provide the param you will get an error.

  @GetMapping(value = "/action")
    public List<MyObject> myAction(  @RequestParam(required = false) String param1) 
        { ... }
// usage: api/action?param1=MyParam
gurkan
  • 509
  • 1
  • 4
  • 18
  • Thanks for your answer But I am not trying to set constraints. All fields in my object are optional. I want to throw an exception If my request contains a parameter that IS not mapped in MyObject. Currently If I send a parameter that IS not mapped in MyObject I got ann empty object But I don't get any error message. – fmezini Apr 20 '23 at 06:10
  • Sorry i misunderstood you. I hope this will solve: https://stackoverflow.com/a/75521858 – gurkan Apr 20 '23 at 06:26