Springboot – Returning HTTP response code based on ResponseEntity

Each http request can have a different response code sent by http server according to the processing result. The response code has to be used properly, according to the semantic defined for each content.

There are 5 classes of HTTP responses codes, and they are:

·       1xx: Information

·       2xx: Success

·       3xx: Redirect

·       4xx: Client error

·       5xx Server error

 

Then, inside each class there are more specific codes, which can inform the client exactly the state of current response. For instance, the error code 404 inform the request resource was not found and the error code 405 inform the request method was not allowed (ex. client makes a request with PUT, but just GET and POST are available).

The usage of response code in Spring Boot @RestController is quite simple, and we are going to demonstrate some examples here. One way to return the proper response code based in a certain behavior is with the used of the ResponseEntity object.

We can instantiate objects from this class, passing as parameter in the constructor a reference to which response code we could to send back to the HTTP client. A list of response code references can be found in the enum HttpStatus (org.springframework.http.HttpStatus). 

Then, it is just necessary to set the return type of the method as ResponseEntity, and return the proper ResponseEntity object according to the proper semantic.
Here is an example of implementation using such object:

@RequestMapping(value="/update_author/{id}/{first_name}", produces = { "application/json" })

        @Transactional

        public ResponseEntity update(@PathVariable(value="first_name") String firstName, @PathVariable(value="id") Long id ) {

                String queryStr="update actor  set first_name =? where actor_id=?";        

                int result=-1;

                Query query=entityManager.createNativeQuery(queryStr);

            query.setParameter(1, firstName);

            query.setParameter(2, id);

            result=query.executeUpdate();

            if(result==0) {

                HttpStatus.Metho

                return new ResponseEntity(HttpStatus.NOT_FOUND);

            }

                return new ResponseEntity(HttpStatus.OK);

        }

 

You can download the whole source code on github:

https://github.com/rafaelqg/code/blob/main/springboot_responseEntity.java

You can see a video class about this theme here:




 

Comments

Popular posts from this blog

HASHLIB: Using HASH functions MD5 and SHA256

Spread Operator

Dart: implementing Object Oriented Programming (OOP)