How to change the response status code for successful operation in Swagger?
Asked Answered
K

2

11

As shown in the image, it says "Response Class (Status 200)" for the add operation. However, the add operation has been implemented in such a way that it will never return 200. It returns 201 on success.

My question is how can I change the (Status 200) to (Status 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

Kana answered 24/5, 2016 at 5:41 Comment(3)
Have you tried adding @ResponseStatus annotation to the operation?Schnabel
@DilipKrishnan: you are a lifesaver!!!Hazzard
@DilipKrishnan if you make that an answer rather than a comment, I will upvote it!Pell
S
0

You can add the @ResponseStatus annotation to any a controller method to define the http status it should return. Ex

Adding the following annotation on acontroller method:

@ResponseStatus(code = HttpStatus.CREATED)

Will return a HTTP status 201 (Created)

Soble answered 2/10, 2018 at 23:43 Comment(0)
K
-1

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

Ker answered 11/12, 2018 at 13:34 Comment(1)
Welcome to StackOverflow! Although it's good to post additional answers where you can add value, I don't think this answer adds anything that's not already included in the accepted answer, and arguably introduces an error because HttpStatus.ACCEPTED (i.e. 202) isn't the status that the question is talking about.Mither

© 2022 - 2024 — McMap. All rights reserved.