Home

Monday, August 7, 2023

Spring Boot Rest API -Exception handling

Client is sending the request. Getting response. If everything is okay. Then we are good. But if something fails to work like It supposed to, Then this is part of exception that it throws. What you want to send as a responds when there is an exception?

By default, Spring Boot is imparting a fallback error-handling page, and error-handling response in case of REST requests. Particularly, Spring Boot appears for a mapping for the /error endpoint during the start-up. This mapping depends on what is set on a ViewResolver class. When no legitimate mappings can be found, Spring Boot mechanically configures a default fallback error page. This so-called Whitelabel Error Page is nothing more than a white HTML page containing the HTTP reputation code and a uncertain error message.

This is what the Whitelabel HTML page looks like in your browser:

We need some error code or error message that is sent as JSON and not some random html page that tomcat server throws up right…

There are couple of ways ,we can approach error handling in REST API.

1. We can create an exception and we can throw it if there is no id.
2. Customize Error Response
1. Custom Exception: When you use Spring boot with Rest API then, We have to create a custom exception class like EmployeeNotFoundException.


Let’s first create EmployeeNotFoundException class. and this I want to be as an RuntimeException so iam going to extends RuntimeException, then we have to add Serial id. Because RuntimeException have serial id. Then we create constructor. This constructor takes the String and calls the parent. So actually this exception is thrown when the data we are looking for is not found return employeeRepository.findEmployeeById(id)


Go to POSTMAN. I have addaed 2 employees. Now i wanted to check employee ID which is not existing. When we hit the URL, This is the below response we get when we get for non existing employee.

I don’t want to send status code 500. I want to send 404. For this You can specify the Response Status for a specific exception along with the definition of the Exception '@ResponseStatus' annotation.



Now go to POSTMAN. Hit the send button.You will get below responds.

You got desired result right. This is the way we have to CUstom our Exception in Spring Boot Rest API.

Now let's see Second approarch.

2. Customize error Response:

I don’t want to simply send 404. I want to send specific error message. For that we have to create error response bean class that has date timestamp, string message, string detail and Allargconstructor.

Then create CustomizedResponseEntityExceptionHandler. This class extends ResponseEntityExceptionHandler. In order to get ErrorDetails to return the error response, we have to define a @ControllerAdvice annotation to this class.

• @ExceptionHandler() indicates that this method would handle exceptions of the specific type.
• ResponseEntity(errorDetails, HttpStatus.NOT_FOUND) - Create an error response object and return it with a specific Http Status

Now Hit the send button in POSTMAN. We will get below response.

Related video for this Post:

Tuesday, August 1, 2023

REST API Methods -PUT,POST,PATCH,GET , DELETE

Request from the browser send to the server. And we will get the response from the server. For each and every customer data, we are storing an identifier to find that patron facts and we will send back that identifier to the customer for reference. When we plan the REST APIs, there is lot possibilities that there can be replica requests coming to the API. These duplicate requests can also be accidental as nicely as intentional every now and then (e.g. due to timeout or network issues). We have to make our APIs fault-tolerant in such a way that the duplicate requests do not leave the system unstable.When we talk about duplicate request we have to talk idempotent.

Idempotent ability we will get same end result with a couple of identical request.No count how many times the method has been called. It should not be counted if the approach has been referred to as only once, or ten instances over.. The result should always be the same.In REST API the following HTTP methods are idempotent:
GET, PUT, DELETE, HEAD, OPTIONS, and TRACE methods

and Only POST method is not idempotent.

1. Why POST method is not Idempotent?
POST is used to create a new resource on the server. So when we invoke the identical request N times, we will have N new resources on the server. Duplication is allowed here. So POST is not idempotent.

2. Why PUT method is Idempotent?
PUT is used to update the resource state. If you invoke a PUT method N times, the very first request will replace the resource; the other N-1 requests will simply overwrite the identical useful resource state again and again.

PUT must exchange the existing aid with the new one. This ability we cannot do partial updates. So, if we choose to replace a single area of the resource, we have to send a PUT request containing the whole resource. Hence, PUT is idempotent.

3. Why PATCH method is Idempotent?
PATCH is used for partial modifications to a resource.If the client sends data with an identifier, then it will check whether or not that identifier exists. If the identifier exists, we will replace the replace with the data, else it will throw an exception. Patch request says that we would only send the records that we want to modify without enhancing or effecting different parts of the data. PATCH does partial update.
Ex: if we need to update only the last name, you can pass only the last name.

4. Difference between PUT and PATCH method
PUT is an Idempotent:
1. PUT should replace the present useful resource with the new one.
2. In PUT method, we are now not throwing an exception if an identifier is not located

PATCH is Idempotent:
1. While PUT is used to replace an existing resource, PATCH is used to apply partial modifications to a resource.
2. In PATCH method, we are throwing an exception if the identifier is not found.

5. Why GET method is Idempotent?
GET is the simplest kind of HTTP request method; the one that browsers use each time you click a link or kind a URL into the address bar. It instructs the server to transmit the information identified by means of the URL to the client. Data need to never be modified on the server side as a result of a GET request. Means, a GET request is read-only

6. DELETE method is Idempotent
DELETE method is pretty easy to understand. It is used to delete a resource identified by a URI.On successful deletion, return HTTP status 200 (OK).

Saturday, July 29, 2023

Design principles of Rest API and its Benifits

HTTP protocol will be used in order to connect different machine. In the http there are different types of method or operations such as GET, POST, PUT, DELETE. These are all well defined in HTTP protocol. That's why REST API comes in to the picture.

REST stands for Representational State Transfer. REST full is way to build your API, that follows REST specifications.

REST Architecture:
• REST-REpresentational State Transfer
• Resource-based
• Representation

• Six Constraints:
1. Client-Server
2. Stateless
3. Cacheable
4. Uniform Interface
5. Layered System
6. Code-On-Demand

Representation: The REST specification involves treating an individual useful resource and having the endpoint map to the resource. And then having sure verbs in terms of what you operate on that resource. And additionally we are sending request, receiving response.

Response you want solely data. So in which layout both XML or JSON. JSON is a human readable format. REST API lets in JSON for request payload and send response in JSON format. Using HTTP headers, the HTTP protocol has a concept of request and response headers. Every HTTP request /response has the body which carries the message itself. And additionally include header values which have some information about the metadata of the messages.

The header data could to be length of the content material or date. One such possible header is Content Type. The response ought to contain a content material type header value with the value being JSON or XML. Its basically it important points what the format of the messages. The type of content material being send back is an information that’s available in the header.So customers receives the response it examines the header for this value, the content type value and then relying on what the content type value is it can parse the response body for this reason whether or not its JSON or XML or whatever like that.

HTTP: Request from the browser ship to the server. And client will get the response from the server. The necessary thing is what the format of the request and response are. This layout is described with the aid of HTTP Hyper Text Transfer Protocol.
When you enter the url in the browser it sends get request to that server. The server sends http response containing the html. Browser looks at the html and shows it.
Lets say, there is a structure on listing of small print and when we click on the submit button, in these variety of situations commonly we are growing POST request. HTTP defines the header which is current in the request and the body of the request.
Also http defines the http methods which are: GET, PUT, POST and DELETE. You can indicate what action you are doing by using HTTP methods.

* Retrieve all user GET /users
* Create a user POST /users
* Retrieve one User GET /users/{id }-> /users/1
* Delete a user DELETE /users/{id}-> /users/1
* Retrieve all posts for a user GET /users/{id}/posts
* Create a post for a User POST /users/{id}/posts
* Retrieve details of a post GET /users/{id}/posts/{post_id}
* PUT= Update

Http also includes http status code(200, 404 ...).

Detail about Different types of Rest API Status Code: Different types of Rest API Status Code

Resources: The most important in REST is something called Resources. Resource anything that would want to expose to the outside world through our application.
Example User, list of user, employee, list of employees, todo, list of todos are resources. We would assign URI to the resource.
REST does not worry about how you are representing your resource.
It can be * xml or * html or * json.

The REST architectural fashion describes six constraints. These constraints, applied to the architecture, have been firstly communicated with the aid of Roy Fielding in his doctoral dissertation and defines the foundation of RESTful-style.

Six Constraints:
• Client-Server : This concept explains that the client and the server should be separate from every other and allowed to evolve personally.

• Stateless : REST APIs are stateless, meaning that it does not save history of any request or response. Once the request is sent by the client it closes the connection and establishes the new connection to give the response.

• Cacheable : Because a stateless API can increase request overhead by handling high volume means large loads of incoming and outbound data calls, because for each request and response it creates a new connection, a REST API have to be designed to inspire the storage of cacheable data.

• Uniform Interface : The key to separate the customer from server is having a uniform interface that lets in independent evolution of the application without having the application’s services, or models and actions, tightly coupled to the API layer itself..

• Layered System : REST APIs have different layers of their architecture working together to build a hierarchy that helps create a more scalable and modular application.

• Code on Demand : Code on Demand allows for code or applets to be transmitted via the API for use within the application.

Advantages of REST:
REST has many advantages. It's easy to scale, flexible and portable and works independently from the client and server, which makes development less complex.

Summary
We have looked into REST Architecture design and its six constraints about REST API. And also we saw the advantages of REST.

Tuesday, July 25, 2023

Different types of Rest API HTTP Status Code

2. What is HTTP?

Request from the browser ship to the server. And we will get the response from the server. The necessary element is what the format of the request and response are. This format is described via HTTP Hyper Text Transfer Protocol. When we enter the url in the browser it sends get request to that server. The server sends http response containing the html. Browser looks at the html and displays it.

Lets say, there is list of details and when we click the submit button, in these variety of eventualities commonly we are creating POST request. HTTP defines the header which is current in the request and the body of the request.

Also http defines the http techniques which are: GET, PUT, POST and DELETE. You can indicate what motion you are doing by way of using HTTP methods.

REST API Status code: Whenever the customer make request server need to response. Success on not. HTTP categorizing five extraordinary code.

This Status code begins from 100 and go up to 599. Not all of them are valid code. The first digit shows what type of the code belongs to.

The code starting with 1 XX are informational code like acknowledgment responses. We are now not the use of this code.

The code beginning with 2XX are success code. They point out that the server acquire a request from a client and process it successfully.

200: If your request get success, that response fame OK that indicates the status code 200.

201: is Created. this suggests successful resource creation. Lets say you have POST request on a collection uri like /messages and you were efficaciously able to create that message, you may want to return 200: OK pronouncing for success response. But better response code would be 201 created which especially stands for creational acknowledgment.

204: No content which you use when you don’t really need to send any content back. For example there is delete request. When you get a delete request you delete the resource. At this point you don’t have to send anything back. Because just resource got deleted. You could return 200 status. But still for more specific you could also send 204 no content which makes it really obvious to the client really intended to send nothing back.

300: the code starting with digit 3 are Redirection. Codes. These codes are used by the server to ask the client to do further actions to complete the request. For example it could be redirect asking the client to send the request somewhere else.

The codes 302: Found

304 : is Not modified is an error code which the server sends, when it needs to tell the client that there is nothing that has been modified. Lets say the client raise to get a resource, that already got before. Now the server can send the status code say, hey I already given you the resources little while back. There is nothing has changed since then. That’s why you are sending 304 rather than sending the whole response again.

307: is Temporary redirect. Or one of the 2 error code send by the server to ask the client say, hey don’t ask me , ask this other URL. This is redirect.

400 code indicates Client Error. These error codes are return client makes the error in the request. The request syntax could have been incorrect. Or the client requesting something that its not supposed to see.

400: Bad request which is blanket client error. The server is not able to understand the request.

401: Unauthorized. Which means the clients needs to sign and authorize themselves to see the resource.

403: Forbidden. Which means the clients may have authenticated but not have the permission to access the requested resource. They don’t have write access something like that.

404: Not found. You are sending the request. Let’s say the request URI may le say /messages/101. There is no message available with the id 101 you will get 404 not found status code. Because server will be able to find the resource.

415: Unsupported Media Type. Which means the client is speaking in a language that the server cannot understand. Which means some format the server cannot understand. In this case server response with 415 unsupported media type.

The 500 codes indicates the server error. The 400 codes are when the clients make error when the make request. 500 are server side error when response back. Basically the server is saying I got your request. It looks like a valid one. But something went wrong when I try to process it. So it returns the 500 codes.

500: internal Server error. This is the generic error code. The server get a request. The resources exist. Or otherwise you got 404. But something went wrong. When processing the request.in this case the standard practice is to send the error code 500 along with the error details in the body of the response.

Summary

We have looked into Different types of Rest API HTTP Status Code and What is HTTP .

Related Blogs:
Different types of Rest API Status Code

Lombok Installation in Spring Suite Tool And Advantages and DisAdvantages of Using Lombok

What is Lombok?

Lombok is an open source library. You don’t need to pay for it to use.


1.
2.

When using Lombok, all that you need is, technically we need to configure the dependency to the required libraries.You need to configure Lomobk in pom.xml if it is maven based project. Maven will automatically downdoad jar for your project. Add @data annotation to our User pojo class to generate getter and setter for our properties.

Our IDE is still not understand what these @Data annotations and will keep complaining about those missing getters and setters.

We can fix this issue in different ways:
1. You can install from eclipse marketplace if it is available. Or
2. you can get plugin from lombok website for your IDE and install it.
3. Or another way is go to browser. Enter lombok jar download. Here you can latest version


Copy and move downloaded jar file to your STS installation folder here or your favorite folder. Copy the path of your lombok jar and open this ini file in your favorite ide either in notepad or notepad ++.
You have to include this lombok path all the way down here using javaagent like below .
-javaagent:E:\software\STS_setup\sts-4.18.1.RELEASE\lombok.jar

Now go to our IDE. File click exit. We will now start our ide again. Double click this spring tool suite application icon.
Now remove @data annotation and enter again. Now you can see our IDE is not complaining.
We saw how to install lombok on our STS IDE.


Reference Video for Lombok Installation In Spring Suite Tool - Advantages and Disadvantages of using Lombok::
Now we will see advantages and disadvantages of using lombok in our project.

Advantages

* Lombok saves time and money. Think about all the paid time your team spends writing getters and setters, renaming them when renaming a variable, etc. This will take lot of time and money.

* Lombok make your code cleaner and easier to read.



Disadvantages

* Debugging Lombok code is difficult:
You don't need to debug getter, setter as it does not change much between classes and usually does very simple tasks, such as setting variable values. But if you do need to debug Lombok code, then you will have difficulties doing so. You have to delomboke means you have to remove your lombok configuration.

* Generated getter and setter won't display. Suppose if you are using SonarQube in your Enterprise Application, then it leads to Sonar Violation, Since your code will be without getters and setters. This is the big disadvantege of using Lombok.


Summary:

We saw how to install Lombok open source plugin in Spring Suite Tool and also we saw what are the advantages and disadvantages of using lombok in our Enterprise Application.

Tuesday, July 18, 2023

How to install Docker on Windows 10

Install Docker on Windows 10


Welcome everyone.This guide will help you to understand the
1. What is docker?
2. What is Container?
3. What are benefits of Docker?
4. How to install of docker on the windows 10

1. What is Docker?
DDocker is a open source software platform that approves you to build, run, test, and build and replace applications quickly. Docker programs software program into standardized units called containers that have everything the software needs to run such as libraries, device tools, code, and runtime.

Docker is an operating system for containers. Similar to how a virtual machine virtualizes server hardware, containers virtualize the operating system of a server. Docker is installed on every server and gives simple commands you can use to build, start, or stop containers..

2. What is Container?
Containers simplify development and sending distributed applications. They have grow to be increasingly famous as agencies shift to cloud-native development and hybrid multicloud environments. It’s viable for developers to create containers barring Docker, via working immediately with capabilities built into Linux and other working systems. But Docker makes containerization faster, simpler and safer.A container shares the kernel with different containers and its host machine. This makes it a lot more lightweight than a virtual machine.

  Docker containers include everything an application needs to run, including:
  * The code,
  * A runtime,
  * Libraries,
  * Environment variables,
  * Configuration files... etc

  A Docker container consists of three main parts:
    1. Dockerfile: used to build the image.
    2. Image itself: a read-only template with instructions for creating a Docker container
    3. Container: a runnable instance created from an image

3. What are benefits of Docker?
 Using Docker lets you ship code faster, standardize software operations, convenient cross code, and keep cash through improving useful resource utilization. With Docker, you get a single object that can reliably run anywhere. Docker's simple and straightforward syntax offers you full control.You can use Docker containers as a core constructing block growing cutting-edge functions and platforms.
Docker makes it handy to build and run allotted microservices architecures, installation your code with standardized continuous integration and delivery pipelines, construct highly-scalable facts processing systems, and create fully-managed structures for your developers.

4. How to install of docker on the windows 10?
 docker is something available for most of the operating systems. like unix and windows.
Through various Linux commands we can do the installation. But in the case of windows, we have to download the exe file on the particular installer from the docker website.

Let's go to browser, enter: https://hub.docker.com/editions/community/docker-ce-desktop-windows

This is free version. Click Get docker. The installer, .exe file will get download. Its around 536 mb. Once the download will complete, we can go ahead to proceed the installation. When we install we have to proceed some of the steps.
Actually There is a huge difference between installer, for example in case of linux, the size of installer is little bit less. But in case of windows, GUI is also involved. And there are lot of binds are available. So that size is bigger than unix. This installation require windows 10

Once completed the downloaded, Double click the installer. It will ask for the approval. Yes or no you have to provide. Now once that is done , desktop, kind of GUI component will open there. It will start proceeding with the installation. Asking whether add it desktop to desktop, so you can say okay. It will unpack the files. Once the installation done you can open your command line and start working on the docker.
Taking sometime to extract the files. Now its asking us to close and restart. Once that is done you will be able to proceed further. Press Windows key+R altogether, enter cmd or Powershell. Hit enter.
In order to check the docker version enter docker version enter:
docker -v

When you do the restart of the machine then at that moment of time the docker server will also be started.

This is the way that how exactly we can go for a docker installation. I hope you got the idea about What is Docker?, What is Docker Container and Benifit and also How to install docker in windows 10

Video reference for How to install Docker on Windows 10. Please click here to watch.


Monday, July 17, 2023

How to launch Java VisualVM in Spring Tool Suite(STS)

This demo is about:
What is VisualVM?
What is the Benifit of VisualVM?
And how to launch visualvm in sts.

What is VisualVm and What is the benefit of using it.

VisualVM is a Java profiler, and is also Java performance tools. Several Java performance tools are available. VisualVM is one of them. And this is a very powerful tool which provides visual interface and also it provides detailed information about local and remote Java applications while they are running on a Java Virtual Machine (JVM).

And also It helps the programmers and architects to track memory leaks, analyze the heap data, monitor the garbage collector and CPU profiling. It also helps to improve the application performance and ensure that memory usage is optimized.

Now we will see how to install visualVM plugin in our STS.

* To Install VisualVM plugin, go to this website: https://visualvm.github.io/idesupport.html
the plugin will get download. Extract download plugin zip. Now

* Go to STS, click Help menu, choose install new software
We have to point it to the local drive were we have unzipped here like below
file:/E:/software/visualvm/visualvm_launcher_u3_eclipse/



Once installation done STS will ask you to restart and click restart.

Next go to Window, preferences -> Run/Debug -> Launching ->VisualVM configuration


Here i have created video how to install and launch VisualVM in Spring Suite Tool (STS).Please wathc it.
How to launch VisualVM in STS Eclipse - Java profiler and Performance tool.


Spring Boot Rest API -Exception handling

Client is sending the request. Getting response. If everything is okay. Then we are good. But if something fails t...