How to change the response status code to work successfully in Swagger?

As shown in the figure, it says β€œResponse class (state 200)” for the add operation. However, the add operation was implemented in such a way that it never returns 200. It returns 201 for success.

My question is how to change (status 200) to (state 201)? The code for this part is as follows:

@RequestMapping(method = RequestMethod.PUT, value = "/add") @ApiOperation(value = "Creates a new person", code = 201) @ApiResponses(value = { @ApiResponse(code = 201, message = "Record created successfully"), @ApiResponse(code = 409, message = "ID already taken") }) public ResponseEntity<String> add(@RequestParam(value = "name", required = true) String name, @RequestParam(value = "id", required = true) String id) { if (PD.searchByID(id).size() == 0) { Person p = new Person(name, id); PD.addPerson(p); System.out.println("Person added."); return new ResponseEntity<String>(HttpStatus.CREATED); } else { System.out.println("ID already taken."); return new ResponseEntity<String>(HttpStatus.CONFLICT); } } 

Thanks!

enter image description here

+8
source share
2 answers

You can add the @ResponseStatus annotation to any controller method to determine the http status it should return. former

Add the following annotation to the acontroller method:

 @ResponseStatus(code = HttpStatus.CREATED) 

Will return HTTP status 201 (Created)

+1
source

Add the following annotation in the controller method (method = requestMethod.PUT) or (method = requestMethod.POST) @ResponseStatus (code = HttpStatus.ACCEPTED)

-one
source

All Articles