Return HTTP code 200 from Spring REST API

I want to use this code to receive http link with values:

@PostMapping(value = "/v1/notification")
public String handleNotifications(@RequestParam("notification") String itemid) {
    // parse here the values
    return "result successful result";
}

How I can return http code 200 - successful response?

And also for example if there is a code exception into code processing how can I return error 404?


Solution 1:

If you are using spring:

@PostMapping(value = "/v1/notification")
public ResponseEntity handleNotifications(@RequestParam("notification") String itemid) {
    // parse here the values
    return ResponseEntity.ok().build(); 
    //OR ResponseEntity.ok("body goes here");
}

Solution 2:

You can do it by annotating your method with @ResponseStatus using HttpStatus.OK (However it should be 200 by default), like this:

Some controller

@PostMapping(value = "/v1/notification")
@ResponseStatus(HttpStatus.OK)
public String handleNotifications(@RequestParam("notification") String itemid) throws MyException {
    if(someCondition) {
       throw new MyException("some message");
    }
    // parse here the values
    return "result successful result";
}

Now, in order to return a custom code when handling a specific exception you can create a whole separate controller for doing this (you can do it in the same controller, though) which extends from ResponseEntityExceptionHandler and is annotated with @RestControllerAdvice and it must have a method for handling that specific exception as shown below:

Exception handling controller

@RestControllerAdvice
public class ExceptionHandlerController extends ResponseEntityExceptionHandler {

    @ExceptionHandler(MyException.class)
    protected ResponseEntity<Object> handleMyException(MyException ex, WebRequest req) {
        Object resBody = "some message";
        return handleExceptionInternal(ex, resBody, new HttpHeaders(), HttpStatus.NOT_FOUND, req);
    }

}

Solution 3:

If you use @RestController it should return 200 by default.

But anyway, you can set a particular response status by @ResponseStatus annotation (even if the methods returns void) or you can return a custom response by ResponseEntity.

EDIT: added error handling

For error handling, you can return a particular response entity:

 return ResponseEntity.status(HttpStatus.FORBIDDEN)
            .body("some body ");

or you can use @ExceptionHandler:

   @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public void handleError(Exception ex) {
        // TODO: log exception
    }

Solution 4:

You can do something like this:

@PostMapping(value = "/v1/notification")
public ResponseEntity<String> handleNotifications(
 @RequestParam("notification") String itemid) {
   // parse here the values
   return new ResponseEntity<>("result successful result", 
   HttpStatus.OK);
}