简体   繁体   中英

Spring Rest Controller: Accept single object and array under one URL

Assuming there is a REST Controller with an endpoint that accepts a single object in the body:

@PostMapping("/ExampleObjects")
void mapping(@RequestBody ExampleObject object){ ....

If one would want to add the ability to accept an array under the same endpoint like this:

@PostMapping("/ExampleObjects")
void mapping(@RequestBody ExampleObject[] objects){ ....

Is there a way to implement the new functionality with the given design and without breaking existing users?

How about having the first endpoint called "/ExampleObject" instead, seeing as it appears to be singular?

It's good practise to keep your API endpoints as simple as possible, as consistent as possible (between different endpoints in the single API), and as error-tolerant as possible.

Instead of an array, you'd want to use a generic List<ExampleObject> in any case.

You could just implement the list version of the method, call that method with a list that only contains a single instance. You'd want to think about the consistency part of the equation a little bit. What kinds of different endpoints will you be implementing in your API. Would this solution fit most of those use cases?

Go with the solution that results with the least surprises to your API users.

Currently something like Jackson is doing the parsing from HTTP request body to ExampleObject automatically for you.

You could do the parsing in your code and decide during parsing, if it is an instance of ExampleObject or ExampleObject[] . Therefore you would have one method with this signature:

@PostMapping("/ExampleObjects")
void mapping(@RequestBody String objectOrArray){ 
    // code to parse String into ExampleObject or ExampleObject[] ...

This should handle your issue, but a better API design would be having 2 different endpoints / URLs.

That should help you.

application.properties:

spring.jackson.deserialization.accept-single-value-as-array=true

controller:

@PostMapping("/ExampleObjects")
void mapping(@RequestBody List<ExampleObject> objects){ ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM