user9680767
user9680767

Reputation:

Rest API method get

How should I check, that I receive an entity from DB and return correct response? I use restController. I want to check that I receive a user from DB or not. If I found the user, I want to return the user and HttpStatus.OK, if not - HttpStatus.NOT_FOUND.

public ResponseEntity<User> getUser(@PathVariable("id") int id) {
        User User= this.userService.getUserById(id);
        ResponseEntity<User> responseEntity = new ResponseEntity<>(HttpStatus.NOT_FOUND);
        if (Objects.nonNull(user)) {
            responseEntity = new ResponseEntity<>(user, HttpStatus.OK);
        }
        return responseEntity;
    }

Upvotes: 0

Views: 178

Answers (3)

A_C
A_C

Reputation: 925

In simple terms, if you want to use Optional for checking availability of user in the database:

public ResponseEntity<User> getUser(@PathVariable("id") int id) {
    User User= this.userService.getUserById(id);
    ResponseEntity<User> responseEntity = new ResponseEntity<>(HttpStatus.NOT_FOUND);
    if (Optional.ofNullable(user).isPresent()) {
        responseEntity = new ResponseEntity<>(user, HttpStatus.OK);
    }

    return responseEntity;
}

Upvotes: 1

Jose
Jose

Reputation: 124

For me this an elegant way to do it, normally id is Long type

public ResponseEntity<User> getUser(@PathVariable ("id") Long id) {
            return Optional.of(this.userService.getUserById(id))
                    .map(u -> new ResponseEntity<>(u, HttpStatus.OK))
                    .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
        }

Upvotes: 0

Aditya Narayan Dixit
Aditya Narayan Dixit

Reputation: 2119

Path parameters can't be made optional, you'll have to map 2 URLs to your get controller method. Try below:

@RequestMapping(method=GET, value={"/", "/{id}"})
 public ResponseEntity<User> getUser(@PathVariable Optional<Integer> id) {

    if(!id.isPresent()){
      return ResponseEntity.notFound().build();
    }
    User User= this.userService.getUserById(id);
    ResponseEntity<User> responseEntity = new ResponseEntity<>(HttpStatus.NOT_FOUND);
    if (Objects.nonNull(user)) {
        responseEntity = new ResponseEntity<>(user, HttpStatus.OK);
    }
    return responseEntity;
}

This solution requires Spring 4.1+ and Java 1.8.

Upvotes: 0

Related Questions