Hey guys in this post we will discuss the most commonly used HTTP status codes with completed examples.
HTTP response status codes indicate whether a specific HTTP request has been successfully completed. HTTP status codes are 3 digit number divided in categories.
To eliminate confusion for API users when an error occurs, we should handle errors gracefully and return HTTP response codes that indicate what kind of error occurred. This gives maintainers of the API enough information to understand the problem that’s occurred. We don’t want errors to bring down our system, so we can leave them unhandled, which means that the API consumer has to handle them.
Category
HTTP status codes are divided into 5 different groups. Let’s discuss one by one
1xx – Informational
Informational status codes indicating that the request initiated by the browser is continuing
100 – Continue
The 100 (Continue) status code indicates that the initial part of a request has been received and has not yet been rejected by the server. The server intends to send a final response after the request has been fully received and acted upon.
101 – Switching Protocols
The server understands and is willing to comply with the client’s request, via the Upgrade header field1, for a change in the application protocol being used on this connection.
102 – Processing
An interim response used to inform the client that the server has accepted the complete request, but has not yet completed it.
2xx – Success
Success codes returned when browser request was received, understood and processed by the server
200 – Ok
The request has succeeded. This clearly indicates that if the request fulfill its job then we will return 200 status code.
201 – Created
The request has been fulfilled and has resulted in one or more new resources are created
202 – Accepted
The request has been accepted for processing, but the processing has not been completed. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place.
204 – No content
The server has successfully fulfilled the request and that there is no additional content to send in the response payload body.
3xx – Redirection
Redirection codes returned when a new resource has been substituted for the requested resource.
301 – Moved permanently
The target resource has been assigned a new permanent URI and any future references to this resource ought to use one of the enclosed URIs.
302 – Found
The target resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client ought to continue to use the effective request URI for future requests.
304 – not modified
A conditional GET or HEAD request has been received and would have resulted in a 200 OK response if it were not for the fact that the condition evaluated to false.
305 – Use proxy
Defined in a previous version of this specification and is now deprecated, due to security concerns regarding in-band configuration of a proxy.
4xx – Client error
Client error codes indicating that there was a problem with the request
400 – Bad request
The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
401 – Unauthorized
The request has not been applied because it lacks valid authentication credentials for the target resource.
402 – Payment required
Reserved for future use.
403 – Forbidden
The server understood the request but refuses to authorize it.
404 – Not Found
The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
405 – Method not allowed
The method received in the request-line is known by the origin server but not supported by the target resource.
409 – Method not allowed
The request could not be completed due to a conflict with the current state of the target resource. This code is used in situations where the user might be able to resolve the conflict and resubmit the request.
422 – Unprocessable entity
The server understands the content type of the request entity (hence a 415 Unsupported Media Type status code is inappropriate), and the syntax of the request entity is correct (thus a 400 Bad Request status code is inappropriate) but was unable to process the contained instructions.
5xx – Redirection
Server error codes indicating that the request was accepted, but that an error on the server prevented the fulfillment of the request.
500 – Internal server error
The server encountered an unexpected condition that prevented it from fulfilling the request.
502 – Bad gateway
The server, while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request.
503 – Service unavailable
The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay.
504 – Gateway timeout
The server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request.
Checkout the complete HTTP status codes at https://httpstatuses.com/
Examples
So far we have discussed some of the most commonly used HTTP status codes. Now let’s see some of the examples, assume that we are creating Todo application and following are the end points
[irp]Create Todo
Let’s look at the example for create resource
@PostMapping("/todos")
public ResponseEntity<?> createTodo(@RequestBody TodoDTO todo) {
try {
todoService.createTodo(todo);
return new ResponseEntity<TodoDTO>(todo, HttpStatus.CREATED);
} catch (ConstraintViolationException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.UNPROCESSABLE_ENTITY);
} catch (TodoCollectionException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.CONFLICT);
}
}
Read todos
Let’s look at the example for reading all the todos
@GetMapping("/todos")
public ResponseEntity<?> getAllTodos() {
List<TodoDTO> todos = todoService.getAllTodos();
return new ResponseEntity<>(todos, todos.size() > 0 ? HttpStatus.OK : HttpStatus.NOT_FOUND);
}
Read single todo
Let’s look at the example for reading a single todo
@GetMapping("/todos/{id}")
public ResponseEntity<?> getSingleTodo(@PathVariable("id") String id){
try {
return new ResponseEntity<>(todoService.getSingleTodo(id), HttpStatus.OK);
} catch (TodoCollectionException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND);
}
}
Update todo
Let’s look at the example for updating the resource
@PutMapping("/todos/{id}")
public ResponseEntity<?> updateById(@PathVariable("id") String id, @RequestBody TodoDTO todo)
{
try {
todoService.updateTodo(id,todo);
return new ResponseEntity<>("Updated movie with id "+id+"", HttpStatus.OK);
}
catch(ConstraintViolationException e)
{
return new ResponseEntity<>(e.getMessage(), HttpStatus.UNPROCESSABLE_ENTITY);
}
catch (TodoCollectionException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND);
}
}
Delete todo
Let’s look at the example for deleting a resource
@DeleteMapping("/todos/{id}")
public ResponseEntity<?> deleteById(@PathVariable("id") String id) throws TodoCollectionException{
try{
todoService.deleteTodoById(id);
return new ResponseEntity<>("Successfully deleted todo with id "+id, HttpStatus.OK);
}
catch (TodoCollectionException e)
{
return new ResponseEntity<>(e.getMessage(), HttpStatus.NO_CONTENT);
}
}
Learn how to create REST API in Spring boot at https://bushansirgur.in/spring-boot-and-mongodb-rest-api-crud-tutorial-updated-2021/
Good walk through of status code