Reputation: 71
Can I create multiple HTTP POST methods with same request mapping with different requestbody
@RequestMapping("api/v1/")
@RequestMapping(value = "test" ,method = RequestMethod.POST)
public RObjet create(@RequestBody RBody rbody)
{
// do some process...
}
@RequestMapping("api/v1/")
@RequestMapping(value = "test" ,method = RequestMethod.POST)
public RObjet2 create2(@RequestBody RBody2 rbody)
{
// do something.
}
Is this possible.? How do we handle this in spring boot.
Upvotes: 5
Views: 10977
Reputation: 906
Yes, you can use POST Http Method for the same end point URI with different request body and also you could get different responses. One way to achieve this, is mapping requests using end point URI + Headers
e.g.
@RestController
@RequestMapping("/api/bills")
public class BillingController {
@RequestMapping(method = RequestMethod.POST, headers = "action=add-bill")
public BillId addBill(@Valid @RequestBody BillingData data) {
//Some code
}
@RequestMapping(method = RequestMethod.POST, headers = "action=delete-bill-by-id")
@ResponseStatus(code = HttpStatus.NO_CONTENT)
public void removeBill(@Valid @RequestBody BillId identifier) {
//Some code here to remove bill
}
}
In this case, both class methods in BillingController are mapped to the same HTTP Method (POST) and URI (/api/bills). The header action drives what class method in BillingController is going to be invoked once you point your post request to /api/bills
How to hit BillingController.addBill?
NOTE: I know that good REST API design dictates that if I want to delete records I should use DELETE method, however this sample was created only as reference to show how to use same URI/Method to handle 2 different end points.
Upvotes: 2
Reputation: 1506
You have to option for this.
it is possible with consumes field. You can use different consuming types.
You can user params field if you have in url.
@RequestMapping(value="/path", params="id") public String test1(@RequestBody RBody body) {}
@RequestMapping(value="/path", params="name") public String test2(@RequestBody RBody body) {}
Upvotes: 0