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:
- 100 Continue: This interim response indicates that everything so far is OK and that the client should continue with the request or ignore it if it is already finished.
- 101 Switching Protocols: This code is sent in response to an
Upgrade
request header from the client and indicates the protocol the server is switching to.
2xx Success
- 200 OK: The request has succeeded. Typically used for successful GET, PUT, DELETE, or PATCH operations.
- 201 Created: The request has been fulfilled and resulted in a new resource being created. Used for successful POST requests.
- 202 Accepted: The request has been accepted for processing, but the processing has not been completed. Useful for asynchronous operations.
- 204 No Content: The server successfully processed the request and is not returning any content. Often used for successful DELETE requests.
3xx Redirection
- 301 Moved Permanently: This and all future requests should be directed to the given URI.
- 302 Found: Tells the client to look at (browse to) another URL. Temporary redirection.
- 304 Not Modified: Indicates that the resource has not been modified since the version specified by the request headers
If-Modified-Since
or If-None-Match
. Useful for caching.
4xx Client Errors
- 400 Bad Request: The server could not understand the request due to invalid syntax. Often used for validation errors.
- 401 Unauthorized: The client must authenticate itself to get the requested response. Used when authentication is required and has failed or has not yet been provided.
- 403 Forbidden: The client does not have access rights to the content, i.e., it is unauthorized, so the server is refusing to give the requested resource.
- 404 Not Found: The server can not find the requested resource. Used when a resource is not found.
- 405 Method Not Allowed: The request method is known by the server but has been disabled and cannot be used. For example, an API endpoint may support only GET and POST methods, but a DELETE method request is made.
- 409 Conflict: The request could not be completed due to a conflict with the current state of the target resource. Often used in response to PUT requests.
- 422 Unprocessable Entity: The request was well-formed but was unable to be followed due to semantic errors. Often used for validation errors on complex data types.
5xx Server Errors
- 500 Internal Server Error: The server has encountered a situation it doesn’t know how to handle.
- 501 Not Implemented: The request method is not supported by the server and cannot be handled. For example, the server may only support GET and POST methods but not PUT or DELETE methods.
- 502 Bad Gateway: The server, while acting as a gateway or proxy, received an invalid response from the upstream server.
- 503 Service Unavailable: The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded.
- 504 Gateway Timeout: The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server.
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
- GET /api/employees: Fetches all employees. Returns 200 OK with a list of employees.
- GET /api/employees/{id}: Fetches an employee by ID. Returns 200 OK if found, otherwise 404 NOT FOUND.
- POST /api/employees: Creates a new employee. Returns 201 CREATED with the created employee.
- PUT /api/employees/{id}: Updates an existing employee by ID. Returns 200 OK if updated, otherwise 404 NOT FOUND.
- DELETE /api/employees/{id}: Deletes an employee by ID. Returns 204 NO CONTENT.
This setup provides a comprehensive CRUD REST API with basic security and detailed HTTP status codes.