I am using this code to show information in Swagger.
@ApiOperation(value = "show code")
@GetMapping("/showActivationCode")
@ApiResponses(
{
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 403, message = "Not login"),
})
public ResponseEntity showActivationCode() {
if (session.getAttribute("isAdmin") == "1") {
return ResponseEntity.status(200).body(userService.getActiveCode());
} else {
return ResponseEntity.status(403).body("Not login");
}
}
And when if goes true, it will return a ActiveCode
array.
public List<ActiveCode> getActiveCode() {
return activeCodeDao.getActiveCodeListDao();
}
And I am expecting Swagger show like this:
[
{
"code": "string",
"isAdmin": "string",
"name": "string",
}
]
But now it show like this
{
"body": {},
"statusCode": "ACCEPTED",
"statusCodeValue": 0
}
There is no information provided by Swagger.
If I am going to change the code like this:
@ApiOperation(value = "show code")
@GetMapping("/showActivationCode")
@ApiResponses(
{
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 403, message = "Not login"),
})
public List<ActiveCode> showActivationCode() {
if (session.getAttribute("isAdmin") == "1") {
return userService.getActiveCode();
} else {
return null;
}
}
It is actually showing as I expected, but I can't customize the Http code in ResponseEntity
. So it can't work.
CodePudding user response:
To customize the HTTP code in ResponseEntity
, you must return a ResponseEntity
object.
in your first block of code the swagger display like that because you didn't specify any type for ResponseEntity
. I can understand that you want to use a dynamic response between a list or a message string but I didn't think that was good practice.
You could try something like this:
public ResponseEntity<List<ActiveCode>> showActivationCode() {
if (session.getAttribute("isAdmin") == "1") {
return ResponseEntity.status(200).body(userService.getActiveCode());
}
else {
return ResponseEntity.status(403).body(Collections.emptyList());
or
return ResponseEntity.status(403).body(null);
}
}
the response in swagger then will be similar to this I guess
{
"body": {
[
{
"code": "string",
"isAdmin": "string",
"name": "string",
}
]
},
"statusCode": "ACCEPTED",
"statusCodeValue": 0
}