DELETE REST Calls

less than 1 minute read

DELETE Rest Call

in DAOService

//Delete a user
public User deleteById(int id){
    Iterator<User> itr = users.iterator();
    User deletedUser=null;
    //boolean idExists = false;
    while(itr.hasNext()){
        User currentUser = itr.next();
        if(id == currentUser.getId()){
            //idExists=true;
            deletedUser = currentUser;
            itr.remove();
        }
    }
    return deletedUser;
}

In Controller

//Delete a User
@DeleteMapping(path = "/user/{id}")
public User deleteUserById(@PathVariable int id) throws UserNotFoundException {
    User user = userDAOService.deleteById(id);

    //If user is not found
    if(user == null){
        throw new UserNotFoundException("User with id " + id +" is not found");
    }
    return user;
}

Delete a user by passing its ID to a delete postman request-

/api/hardCodedData/user/1