Home > Enterprise >  [HTTP response code]Does one REST API only respond one successful code?
[HTTP response code]Does one REST API only respond one successful code?

Time:10-28

Background: I'm using Java with Spring boot framework. I have one REST API which input parameter is a int flag, when the flag is 0 then the API will give the response '200' and when the flag is 1 then the response is '204'

[edit] Now, I can give the response of '200'. But I don't know how to return '200' and '204' by using condition for the REST API.

Question: Can a REST API return different successful code? If it can, how should I do that?

Thanks.

CodePudding user response:

Spring Boot allows you to customize the HTTP response by editing/creating @RestControllers:

@RestController
public class DoStuffController {
    @RequestMapping(value = "/do-stuff", method = RequestMethod.POST)
    public void doStuff(@RequestParam int flag, HttpServletResponse response) {
       if(flag == 0){
          response.setStatus(HttpStatus.OK);
       } else {
          response.setStatus(HttpStatus.SC_NO_CONTENT);
       }
    }
}

The above is untested - but should react to a POST /do-stuff?flag=[0|1] by returning eithet HTTP 200 or 204.

  •  Tags:  
  • rest
  • Related