Home > Net >  How to pass an array of primitives as Request in Postman
How to pass an array of primitives as Request in Postman

Time:01-03

I was wondering what is the best way to pass a simple int[] array to a Spring Controller?

As of now it only worked when I am passing the values as a @RequestParam in the URL, however I would like to send them for example as a @RequestBody. How could I do that?

`

@PostMapping
public int acceptArray(@RequestParam int[] array) {

    if (array == null || array.length == 0) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "You entered an empty array");
    }

    return arraySolver.arraySolver(array);
}

`

Since I am kinda new a more detailed explanation would be appreciated :)

Thank you in advance for the help.

CodePudding user response:

You can achieve that by passing the multiple arguments as query params like show in below. The controller is taking array as input and sum the elements and returns that. That is why for [1,2,3] it outputs 6.

enter image description here

To send it as request body you can just follow below code.

@PostMapping
    public int acceptArray(@RequestBody InputArrayRequest request) {

        if (request.getArray() == null || request.getArray().length == 0) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "You entered an empty array()");
        }

        return arraySolver.arraySolver(array);
    }

class InputArrayRequest {
    private int[] array;

    public int[] getArray() {
        return array;
    }
}

CodePudding user response:

You can pass an array by specifying the same key multiple times in Body > form-data like in this screenshot: Postman Screenshot

  • Related