I have a controller class with a few methods one of which is a method that is supposed to take POST requests and create a new Account with the JSON from the body of that POS
You cannot use multiple @RequestBody
. You need to wrap everything into a class that will be used to match your request body.
The same is answered also here.
There is also a JIRA issue for a feature request which was rejected.
NOTE: if you want to write less, you can use @PostMapping
instead of @RequestMapping(method = RequestMethod.POST)
.
NOTE: @RequestParam
and @PathVariable
are used to extract data from URI, not from body.
NOTE: the same is valid also for the equivalent [FromBody]
attribute from ASP.NET WebAPI
.
Complete example:
Bellow I created a working example similar to your case:
Request DTO
public class AccountCreateRequest {
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Response DTO
public class AccountCreateResponse {
private String userName;
private String password;
public AccountCreateResponse() {
}
public AccountCreateResponse(String userName, String password) {
this.userName = userName;
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Controller
@RestController
@RequestMapping("/v1/account")
public class AccountController {
@PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseStatus(HttpStatus.CREATED) AccountCreateResponse add(@RequestBody() AccountCreateRequest account) {
AccountCreateResponse response = new AccountCreateResponse(account.getUserName(), account.getPassword());
return response;
}
}
curl request
curl -X POST --data '{"userName":"bepis", "password":"xyz"}' -H "Content-Type:application/json" http://localhost:8080/v1/account