Skip to content

Instantly share code, notes, and snippets.

@romilptl
Last active March 8, 2020 05:20
Show Gist options
  • Save romilptl/551a6256081507c29ae38a95a3b983ec to your computer and use it in GitHub Desktop.
Save romilptl/551a6256081507c29ae38a95a3b983ec to your computer and use it in GitHub Desktop.
APIs with the required response, status code and exceptions.
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired UserService userService;
@PostMapping(value = "/save", consumes = "application/json", produces = "application/json")
public ResponseEntity<User> save(@RequestBody User user) {
user = userService.save(user);
return new ResponseEntity<>(user, HttpStatus.OK);
}
@GetMapping(value = "/list")
public ResponseEntity<List<User>> findAll() {
List<User> users = userService.findAll();
return new ResponseEntity<>(users, HttpStatus.OK);
}
@GetMapping(value = "/user/{id}")
public ResponseEntity<Optional<User>> findUserById(@PathVariable Long id) {
Optional<User> user = userService.findById(id);
if(user.isPresent())
return new ResponseEntity<Optional<User>>(user, HttpStatus.OK);
else
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
}
@DeleteMapping("/delete/{id}")
public void delete(@PathVariable Long id) {
userService.delete(id);
}
@GetMapping("/exception/parse")
public void generateParseException() throws ParseException {
throw new ParseException("We can see this generated exception in 'http.server.requests' using '/metrics' endpoint");
}
@GetMapping("/exception/io")
public void generateIOException() throws IOException {
throw new IOException("We can see this generated exception in 'http.server.requests' using '/metrics' endpoint");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment