Blogs On Job Interview Questions

Spring REST Client

Spring REST Client

by Vibrant Publishers on Jan 04, 2022
Introduction The spring framework in Java is used for building enterprise-class applications. This framework has extensive support for building REST-based web services. There are both client-side and server-side libraries available for this. The web applications that leverage the power of the Spring framework can implement REST services in a much faster way. This article will discuss the client-side REST implementation using the Spring framework. The Spring REST Client The client-side implementation of Spring REST will enable a client application to receive web service responses from the server. It also provides a toolset required for building and sending REST API requests from the client application. The main class that enabled the client to use the REST API with Spring was the RestTemplate class. But from the latest version of Spring, ie. Spring 5.0 onwards this class has been deprecated and a new class called WebClient got introduced. It’s a modern alternative to the RestTemplate class. Let us have a detailed look at the WebClient class. WebClient Class From Spring 5.0 onwards the WebClient class will be the gateway of all the web requests and responses in a web application. The advantages of this implementation over its predecessor RestTemplate class are: (a) It is non-blocking in nature. (b)It has a singleton implementation (c) It is reactive in nature. The WebClient class like its predecessor works over protocol HTTP/1.1. While working with the WebClient class the main steps we need to know are the following: 1. Creating an instance. 2. Building a client request. 3. Handling the request & response. Let us get into the details of these processes. Creating an instance The simplest way to create an instance is as shown below: WebClient testClient = WebClient.create(); We can also create the instance by providing a URI: WebClient testClient = WebClient.create(“http://exampleserver.com/8000”); The most advanced way of creating an instance is by providing all the required details for the class. The below given code snippet is an example for that.                                                                             WebClient testClient = WebClient       .builder()       .baseUrl(“http://exampleserver:8000”)       .defaultCookie(“key”, “value”)       .defaultUriVariables(Collections.singletonMap(“url”, “http://exampleserver:8000“))        .defaultHeader(HttpHeaders.CONTENT_TYPE,   MediaType.APPLICATION_JSON_VALUE)     .build();     Building a client request Once we are ready with an instance, the next step is to create a REST API request from the client. One of the main parts of the request is the type of request that we are sending. We must decide the HTTP methods GET, POST, UPDATE & DELETE that we are going to use while sending a request. The following code snippet will do that: WebClient.UriSpec testRequest = testRequest.method(HttpMethod.POST); The next step is to provide a target URL which can be done as given below:                                                             WebClient.RequestBodySpec testURI = testClient     .method(HttpMethod.POST)     .uri(“/resource”);     After this step, we have to provide the other details such as content-type, header details, etc. That can be set as follows:                                                                     WebClient.RequestBodySpec testURI = testClient     .method(HttpMethod.POST)   .uri(“/resources”).body( BodyInserters.fromPublisher( Mono.just(“information”)),   String.class);     Once we are done with setting the body of the request, the WebClient will send the request to the target URI which will invoke the server-side API function.   Handling the request & response There are two ways we can send and receive the information using WebClient. One is using the exchange() method and the other one is using the retrieve() method. The main differences between these two methods are that the first method will return HTTP information like cookies, headers, etc along with the response body while the second method will only return the response body. A sample request & response code will look as follows:                                                                           Class testClass = testClient.post()           .uri(“/resources”)           .body(Mono.just(), String.class)           .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)           .retrieve()           .bodyToMono(String.class);     Here the request is a HTTP POST and the response will be returned as a response body which will be parsed by the bodyToMono() function. If there is a 4xx or 5xx response, this method will throw a WebClientException. Summary Handling requests and responses at the client side are handled in the Spring framework using the WebClient implementation. This is the new standard for handling client web requests and responses after Spring 5.0. There is a rich set of functionalities that makes this implementation an efficient and easier one.  
Spring REST Request Processing

Spring REST Request Processing

by Vibrant Publishers on Dec 21, 2021
IntroductionDeveloping REST APIs and web services using Spring Boot makes the process very easy and helpful for the developer. It takes out a lot of overheads and helps us to only focus on the core business logic. The rest of the configurations and setup processes are taken care of by the framework itself. In this article, we will focus on the request processing part of a REST API using Spring Boot. The flow of an API Request in Spring When we create a microservice in Spring the main control flow of an incoming request will as shown below:The role of annotations Some of the main annotations for processing a request using spring are as follows: @RestController: This is the heart of any Spring web service. There must be a class declared with this annotation. It will make the class discoverable during classpath scanning. @RequestMapping: The resource methods that are annotated with the above annotation will be exposed as HTTP endpoints. When an API request matches a given @RequestMapping annotation, the resource method will be executed to serve the incoming request. The following code snippet will give you an idea of using these annotations:The request mapping process @RestController @RequestMapping(“/employee”) public class EmployeeController {                 @Autowired                 EmployeeDetails employeeDetails                 @RequestMapping(method = RequestMethod.GET)                 public List findEmployee()                  {                     return employeeDetails.findEmployee();                 } }   When we prepare our classes and resource methods with the given annotations, the Spring Boot takes care of the rest of the processing. Let us consider a sample incoming request as given below:Request: http://localhost:8080/employeeAccept: application/JSONWhen this request reaches the server container, the spring boot will handle this request using a DispatcherServlet. The configuration and initialization of this servlet will be already done by the Spring Boot during the project creation time itself.The Dispatcher ServletThe DispatcherServlet will be the front end controller through which all the requests will be passing through. There are a few steps that the DispatcherServlet will be doing for us to process the request. They are: Intercepting the incoming request to identify the resource. Finding a suitable handler for the given request. This is done by checking the Path parameter, HTTP method, Query parameter & the Request header.   Get the matching controller method for the incoming request. This is possible due to the mapping registry prepared by the spring framework by looking up @RequestMapping annotations. Execute the controller method to process the incoming resource. We can understand the process from the following diagram:SummaryUnderstanding the processes involved in REST request handling by the spring ecosystem is important. This will help us to code efficiently and also in doing better troubleshooting.  
Spring REST Response Processing

Spring REST Response Processing

by Vibrant Publishers on Dec 14, 2021
Introduction Requests and Responses are building blocks of any REST API. They must be built and handled properly to make any API to work without glitches. Though the Spring framework takes care of many configurations behind the scene, there are certain things as a developer one must understand. In this article, we will focus on the response processing part of a REST API using Spring Boot.   Spring REST API Responses Once the request is processed by request handlers and resources methods, the next step in the pipeline is to build an appropriate response to the client. The below given diagram is a high level process summary on how responses are handled in REST.     There are multiple ways to build a response using the Spring framework. They are: Response Body Response Entity Response Body   The @ResponseBody annotation in Spring Boot is used for binding a return value from a resource method to a web response body. This is done by the use of HTTP message converters. This conversion is done by looking at the content-type value in the HTTP request header. Let us consider the following example:                                                                       @RequestMapping(path = “/FindEmployee/1234”, produces = “application/json; charset=UTF-8”)   @ResponseBody     public List<Employee> findEmployee() {    var employeeData = (List<Employee>)  employeeDatabase.findAll();       return employeeData; }       in the above code, the request comes to find the employee details for the given employee id. The media type in the request header is JSON. Now the resource method findEmployee() is called that will return the result. Now there is a class in Spring known as RequestResponseBodyMethodProcessor. It will collect the return values from methods that are annotated with @ResponseBody. This value is then written into the body of the response. A suitable HTTP message converter class will be called during this process. In our case since the media type is JSON, the MappingJaxkson2HttpMessageConverter class will be called. This class will read and write JSON using Jackson Object Mapper. Jackson is a popular Java JSON library. The response body is now ready with the response data in the JSON form which can be transported to the client over the network. Response Entity The main difference between the Response Body and Response Entity is that the @ResponseEntity annotation represents the whole of the response including the message body, response header, and the status code. The advantage of using this method is flexibility. We can fully configure the response to the client the way we want. The following code sample will give an idea about the usage of @ResponseEntity.                                                                                 @GetMapping(“/employeeID”)   ResponseEntity<String> getEmployee(@RequestParam(“employeeID”) int employeeID)    {     HttpHeaders httpHeaders = new HttpHeaders();       httpHeaders.add(“My-Header”, “foo”);       if (idNotNumber(employeeID)) {                return new ResponseEntity<>(“Employee ID must be a number”, HttpStatus.BAD_REQUEST);       }         return new ResponseEntity<>(“Employee Details: ” + findEmployee(employeeID), HttpStatus.OK);    }   Here we have used all the major possibilities of @ResponseEntity. We can build a custom response with custom HTTP headers, Status code & message using this method. Summary Building an API response in the Spring framework can be done using ResponseEntity and Response Body annotations. Though @ResponseBody will cater to the basic requirements, @ResponseEntity annotation provides better control and flexibility in building a response. When we need to build responses with a lot of customization, then the @ResponseEntity would be a better choice.  
Spring REST Exception Handling

Spring REST Exception Handling

by Vibrant Publishers on Oct 29, 2021
Introduction Like in any other field, API development is also prone to errors. We might encounter undesired outputs while working with web services. The success of a developer lies in handing these errors gracefully. This is one of the main topics that a web service developer must understand. In this article, we will be discussing how the Spring framework handles REST API exceptions.   Spring Boot Exception Handling The below-given diagram will provide an overview of the exception handling process in the Spring Boot environment.     Usually, the default response for any error would be an HTTP 500-Internal Server Error message to the client. This wouldn’t be the right message that a client would want to see. We can make the message to the client more verbose and with proper HTTP status codes so that it won’t create any panic.   Types of exception handling There are mainly three ways in which Spring Boot exceptions are handled. Using Http Status Codes with Response Entity Using @ExceptionHandler Annotation Custom exception class with @ResponseStatus Let us have a look into each of these in detail: Using Http Status Codes with Response Entity As we have said, the default error response would be to throw an HTTP 500- Internal Server Error. But we can set the correct HTTP status code and message for exceptions, like HTTP 404 – Resource Not Found. But for doing this we must be using the @ResponseEntity annotation. This will provide us the flexibility to make custom messages and status codes in the response header.   Using @ExceptionHandler Annotation In this method, we declare a custom method to handle exceptions on the controller itself. The custom method will return a void and also will implement the @ExceptionHandler annotation. Here we have to map this method to the HTTP exception status and for that, we will use the @ResponseStatus annotation. The response status annotation will take two arguments. The first argument will define the HTTP status code corresponding to the exception and the second argument defines the reason for the current exception. This message will be sent to the client in JSON /XML format as a response message.   Custom exception class with @ResponseStatus In this method, we will create a custom exception class. This class will extend the Java exception class. When an exception occurs in the web service, the controller will throw this custom exception class. This custom exception class must be mapped to the corresponding HTTP error code. This can be done using the @ResponseStatus annotation.   Summary As we have seen, there are different ways by which one can handle the exceptions that occur in web services. It is the choice of the developer to go with one option. There can be scenarios in which one would use a combination of all the given options. But the important task is to handle the exception properly along with providing clear information to the client.  
Spring REST Basics

Spring REST Basics

by Vibrant Publishers on Oct 20, 2021
Introduction Spring is a popular Java application framework. The spring framework is based on a principle called dependency injection which allows developers to build completely decoupled systems. This framework supports all Java features and also there are extensions for this framework that allows us to build web applications leveraging the JavaEE platform. In this article, we are exploring the basics of REST implementation in the Spring framework.   Spring and REST The REST API specification in the Java world is known as JAX-RS. Spring framework has included this specification and is available under the Spring Web package. The spring framework has support for other Java REST implementations like Jersey as well. Within the Spring framework, there are two ways we can implement the REST web services. Spring MVC: Uses the traditional model-view-control method. Configuration heavy. The below given diagram will provide an idea about the MVC model. This is a typical multi layered approach for handling REST requests and responses.   SpringBoot: Leverages the HTTP message converters. More modern (Spring 3.0) and easy to implement. We will be using SpringBoot for developing our REST applications using Spring. Setting up  a Spring REST application When we develop applications using the Spring framework, it’s a good practice to use the Spring Initializr page. This will help you define the project with all dependencies and generate your project configuration file that will save a lot of your project setup time. All the REST applications using SpringBoot will have a SpringWeb dependency that we will choose while creating the project using the Spring Initializr. There are two build systems available here. Gradle and Maven. Gradle will generate a build configuration file namely build.gradle and Maven will use the pom.xml file for build configurations. All your dependencies and external libraries must be included in this file. We will be using the Gradle build system here. In the configuration, first thing you have to include is the Spring Boot Starter Web dependency. In Gradle it will look like the following: #compile(‘org.springframework.boot:spring-boot-starter-web’ The complete configuration file for the Gradle build will look like something as given below: buildscript {    ext {       springBootVersion = ‘2.2.6.RELEASE’    }    repositories {       mavenCentral()    }       Dependencies{         classpath(   “org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”  )    } } apply plugin:’org.springframework.boot’ apply plugin:’java’ apply plugin:’eclipse’ group = ‘com.example’ version = ‘0.0.1-SNAPSHOT’ sourceCompatibility = 1.8 repositories {    mavenCentral() } Dependencies{    compile( ‘org.springframework.boot:spring-boot-starter-web’ )    testCompile( ‘org.springframework.boot:spring-boot-starter-test’ ) }   Basic Annotations Before we start building the REST application using Spring, let us understand some of the annotations that we will be using in the process. Rest Controller The @RestController annotation is used for including the main artifact of the RESTful API in our code. This is also responsible for providing JSON, XML responses and any other custom responses. Request Mapping @RequestMapping annotation is used for defining the URI to access the endpoints. We will use a request method for consuming and producing resources. The default request method is GET. Path Variable When we need to set a custom request URI. The annotation @PathVariable will be specific to each resource and can have dynamic values. Request Body When we send a request the content type of the request is mentioned using @RequestBody annotation. Request Parameter The @RequestParam annotation is used for extracting parameters from the request URL. This parameter must be included while we send a request. Summary The Spring framework is an enterprise application development framework for Java. The JAX-RS specifications for REST web services are well integrated with Spring and are available with many rich features. The SpringBoot package is the modern implementation in Spring that can be used for creating REST applications with ease and flexibility.