HTTP Status Codes in REST APIs
Table of Contents
- Introduction
- What are HTTP Status Codes?
- Categories of HTTP Status Codes
3.1 Informational (1xx)
3.2 Successful (2xx)
3.3 Redirection (3xx)
3.4 Client Error (4xx)
3.5 Server Error (5xx) - HTTP Status Codes in CRUD Operations
- Example: Implementing Status Codes in Java
- Conclusion
1. Introduction
In the world of web development, HTTP status codes play a critical role in communication between the client and server. These status codes are issued by the server in response to a client’s request and indicate the outcome of the request, whether it was successful, redirected, encountered an error, or something else. Understanding and using the correct HTTP status codes is essential for creating robust, user-friendly APIs.
In this article, we will explore different categories of HTTP status codes, how they relate to CRUD (Create, Read, Update, Delete) operations, and how they can be implemented in a RESTful API using Java.
2. What are HTTP Status Codes?
HTTP Status Codes are three-digit numbers issued by a web server in response to a client’s request. They provide feedback about the success or failure of a request and are an essential part of REST APIs.
For example, when a client sends a request to retrieve a resource, the server may respond with:
- 200 OK: The request was successful.
- 404 Not Found: The resource was not found.
Each status code is grouped into one of five categories, depending on the type of response they represent.
3. Categories of HTTP Status Codes
3.1 Informational (1xx)
These codes indicate that the server has received the request and is continuing the process. They are rarely used in RESTful APIs.
Status Code | Meaning |
---|---|
100 | Continue: The client should continue with the request. |
102 | Processing: The server has received and is processing the request. |
3.2 Successful (2xx)
These codes indicate that the request was successfully received, understood, and accepted by the server.
Status Code | Meaning |
---|---|
200 | OK: The request was successful. |
201 | Created: A new resource was created as a result of the request. |
3.3 Redirection (3xx)
Redirection codes indicate that further action is needed to complete the request.
Status Code | Meaning |
---|---|
301 | Moved Permanently: The resource has been permanently moved to a new location. |
304 | Not Modified: The resource has not been modified since the version specified. |
3.4 Client Error (4xx)
Client error codes indicate that the request contains bad syntax or cannot be fulfilled by the server.
Status Code | Meaning |
---|---|
403 | Forbidden: The request was valid, but the server is refusing action. |
404 | Not Found: The requested resource could not be found. |
3.5 Server Error (5xx)
Server error codes indicate that the server failed to fulfill a valid request due to an issue on the server side.
Status Code | Meaning |
---|---|
500 | Internal Server Error: A generic error indicating a server malfunction. |
503 | Service Unavailable: The server is currently unavailable. |
4. HTTP Status Codes in CRUD Operations
When building a RESTful API, status codes are integral to indicating the outcome of CRUD operations.
Operation | Status | Method | Code |
---|---|---|---|
READ | Successful | GET | 200 OK |
Not Found | GET | 404 Not Found | |
Failure | GET | 500 Internal Server Error | |
DELETE | Successful | DELETE | 200 OK/204 No Content |
Not Found | DELETE | 404 Not Found | |
Failure | DELETE | 500 Internal Server Error | |
CREATE | Successful | POST | 201 Created |
Data Error | POST | 400 Bad Request | |
Failure | POST | 500 Internal Server Error | |
UPDATE | Successful | PUT | 200 OK |
Data Error | PUT | 400 Bad Request | |
Not Found | PUT | 404 Not Found | |
Failure | PUT | 500 Internal Server Error |
5. Example: Implementing Status Codes in Java
Here’s an example of how you can handle HTTP status codes in a Java Spring Boot application.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
@RestController @RequestMapping("/api") public class ApiController { // GET Request to retrieve a resource @GetMapping("/resource/{id}") public ResponseEntity<Object> getResource(@PathVariable("id") int id) { Resource resource = findResourceById(id); if (resource != null) { return new ResponseEntity<>(resource, HttpStatus.OK); } else { return new ResponseEntity<>("Resource not found", HttpStatus.NOT_FOUND); } } // POST Request to create a new resource @PostMapping("/resource") public ResponseEntity<String> createResource(@RequestBody Resource resource) { try { saveResource(resource); return new ResponseEntity<>("Resource created successfully", HttpStatus.CREATED); } catch (Exception e) { return new ResponseEntity<>("Failed to create resource", HttpStatus.INTERNAL_SERVER_ERROR); } } // PUT Request to update a resource @PutMapping("/resource/{id}") public ResponseEntity<String> updateResource(@PathVariable("id") int id, @RequestBody Resource resource) { if (findResourceById(id) != null) { updateResource(id, resource); return new ResponseEntity<>("Resource updated successfully", HttpStatus.OK); } else { return new ResponseEntity<>("Resource not found", HttpStatus.NOT_FOUND); } } // DELETE Request to delete a resource @DeleteMapping("/resource/{id}") public ResponseEntity<String> deleteResource(@PathVariable("id") int id) { if (findResourceById(id) != null) { deleteResource(id); return new ResponseEntity<>("Resource deleted successfully", HttpStatus.NO_CONTENT); } else { return new ResponseEntity<>("Resource not found", HttpStatus.NOT_FOUND); } } } |
Explanation:
- GET /resource/{id}: Returns a 200 OK if the resource is found, or a 404 Not Found if the resource is missing.
- POST /resource: Returns a 201 Created if the resource is successfully created, or a 500 Internal Server Error if the operation fails.
- PUT /resource/{id}: Returns a 200 OK if the resource is updated, or a 404 Not Found if the resource is missing.
- DELETE /resource/{id}: Returns a 204 No Content if the resource is deleted, or a 404 Not Found if the resource is missing.
6. Conclusion
HTTP status codes provide crucial feedback on the success or failure of client-server communication in RESTful APIs. They are especially important in CRUD operations, where each operation can result in different outcomes. By correctly implementing status codes, developers can create more reliable and user-friendly APIs.