Pass custom json object in swagger with spring boot
I want to pass a custom json object as swagger request body. In Java we use @ApiModelProperty(hidden = true)
annotation to hide some fields in swagger. But in my case I want to pass custom json object as swagger request body.
here's my code,
@PostMapping(value = "/verifyMobile", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation(value = "Verify User otp", notes = "Verifies user email")
public ResponseEntity<Map<String, Boolean>> verifyMobile(@RequestBody Map<String, Object> verificationObj) {
Boolean isUpdated = userService.mobileVerification(verificationObj.get("phoneNumber").toString(),
verificationObj.get("mobileVerificationOtp").toString());
Map<String, Boolean> objMap = new HashMap<String, Boolean>();
objMap.put("success", isUpdated);
return isUpdated ? ResponseEntity.status(HttpStatus.ACCEPTED).body(objMap) :
ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(objMap);
}
and I will be accepting bellow as request body,
{
"phoneNumber":"+919038897580",
"mobileVerificationOtp":"9399"
}
How can I implement this on swagger. Swagger body looks something like this. Please help me to fix this. 🙏🏻
Solution 1:
If you want to display a json
object as request body in Swagger
you can create a model object.
Your model object can be as follows.
public class VerificationRequest {
private String phoneNumber;
private String mobileVerificationOtp;
public VerificationRequest(String phoneNumber, String mobileVerificationOtp) {
this.phoneNumber = phoneNumber;
this.mobileVerificationOtp = mobileVerificationOtp;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getMobileVerificationOtp() {
return mobileVerificationOtp;
}
public void setMobileVerificationOtp(String mobileVerificationOtp) {
this.mobileVerificationOtp = mobileVerificationOtp;
}
}
Then you can edit this model where your endpoint is located as follows.
@PostMapping(value = "/verifyMobile", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation(value = "Verify User otp", notes = "Verifies user email")
public ResponseEntity<Map<String, Boolean>> verifyMobile(@RequestBody VerificationRequest verificationObj) {
Boolean isUpdated = userService.mobileVerification(verificationObj.getPhoneNumber(),
verificationObj.getMobileVerificationOtp());
Map<String, Boolean> objMap = new HashMap<String, Boolean>();
objMap.put("success", isUpdated);
return isUpdated ? ResponseEntity.status(HttpStatus.ACCEPTED).body(objMap) :
ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(objMap);
}