sbnotes

Topic 003: HTTP status codes for REST API in Spring Boot

Topic 003: HTTP status codes for REST API in Spring Boot

In addition to the common HTTP status codes used in the CRUD operations outlined above, there are several other HTTP status codes that you might encounter or use in a REST API. Here are some of them, along with explanations:

1xx Informational Responses

2xx Success

3xx Redirection

4xx Client Errors

5xx Server Errors

Usage in Spring Boot

In Spring Boot, these status codes can be returned using ResponseEntity in your controllers. Here’s how you can use some of these status codes in a controller:

@GetMapping("/{id}")
public ResponseEntity<EmployeeDTO> getEmployeeById(@PathVariable Long id) {
    EmployeeDTO employeeDTO = employeeService.getEmployeeById(id);
    if (employeeDTO != null) {
        return new ResponseEntity<>(employeeDTO, HttpStatus.OK);
    }
    return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}

@PostMapping
public ResponseEntity<EmployeeDTO> createEmployee(@RequestBody EmployeeDTO employeeDTO) {
    try {
        EmployeeDTO createdEmployee = employeeService.createEmployee(employeeDTO);
        return new ResponseEntity<>(createdEmployee, HttpStatus.CREATED);
    } catch (DataIntegrityViolationException e) {
        return new ResponseEntity<>(HttpStatus.CONFLICT);
    }
}

@PutMapping("/{id}")
public ResponseEntity<EmployeeDTO> updateEmployee(@PathVariable Long id, @RequestBody EmployeeDTO employeeDTO) {
    if (!employeeService.existsById(id)) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
    EmployeeDTO updatedEmployee = employeeService.updateEmployee(id, employeeDTO);
    return new ResponseEntity<>(updatedEmployee, HttpStatus.OK);
}

@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteEmployee(@PathVariable Long id) {
    if (!employeeService.existsById(id)) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
    employeeService.deleteEmployee(id);
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}

Explanation of REST API and Status Codes

This setup provides a comprehensive CRUD REST API with basic security and detailed HTTP status codes.