Everythink what i won
Everythink what i won

Reputation: 23

How to conditionally return custom response body and status in Spring Boot?

I have a Spring Boot application and this handler method:

@PostMapping("/{id}")
public User create(@PathVariable("id") Long id, @RequestBody User user) {
    if (id > 0 && id < 10) {
        String fullName = user.getFirstName() + " " + user.getLastName();
        user.setId(id);
        user.setFullName(fullName);
    } else {
        //Return 401 ?
    }
    
    return userService.save(user);
}

How can I return return 401?

The response JSON should look like:

{
    "msg": "empty",
    "status" : "401"
}

Upvotes: 2

Views: 2109

Answers (1)

vszholobov
vszholobov

Reputation: 2363

You can do it, using ResponseEntity.

You would need to change your method return type to ResponseEntity<?>, and change your method body to:

if (id > 0 && id < 10) {
    String fullName = user.getFirstName() + " " + user.getLastName();
    user.setId(id);
    user.setFullName(fullName);
    return new ResponseEntity<>(userService.save(user), HttpStatus.OK);
}

return new ResponseEntity<>(yourJsonObject, HttpStatus.UNAUTHORIZED);

Java Spring rest return unauthorized json

Upvotes: 3

Related Questions