Spring Rest Interview Questions

Top 15 Spring Rest Interview Questions every developer should know

Spring Rest Interview Questions
Spring Rest Interview Questions

1. What does Rest stand for? and what is RESTful web services?

REST stand for REpresentational State Transfer, term by Roy Fielding. REST is an architectural style that describes best practices to expose web services over HTTP with Emphasizes scalability. Web services written by apply REST Architectural concept are called RESTful web services which focus on System resources and how state of Resource should be transferred over http protocol to a different clients written in different languages. In RESTful web services http methods like GET, PUT, POST and DELETE can can be used to perform CRUD operations. Read more about REST.

2. What is a resource in Rest API?

A resource is how data is represented in the REST architecture. By exposing entities as the resource, it allows a client to read, write, modify, and create resources using HTTP methods.
Example –
https://onlyfullstack.com/students
https://onlyfullstack.com/cars

3. What are the HTTP methods supported by Rest?

HTTP methods supported by REST are:
GET: It requests a resource at the request URL. It should not contain a request body as it will be discarded. Maybe it can be cached locally or on the server.
POST: It submits information to the service for processing; it should typically return the modified or new resource
PUT: At the request URL it update the resource

PATCH: At the request URL it partially updates the resource
DELETE: At the request URL it removes the resource
OPTIONS: It indicates which techniques are supported
HEAD: About the request URL it returns meta information

4. What are safe REST operations?

REST API uses HTTP methods to perform operations. Some of the HTTP operations, which doesn’t modify the resource at the server, are known as safe operations, including GET and HEAD. On the other hand, PUT, POST, and DELETE are unsafe, because they modify the resource on the server.

5. What are idempotent REST operations?

Idempotent operations are those HTTP methods that produce the same response no matter how many times you use them, It would not matter if the method is called only once, or many times over. The result should be the same.
Consider the following examples:
int a = 4; //is idempotent
a++; //is not idempotent
POST is not a idempotent method, calling it multiple times can result in wrong data as it will insert the same record multiple times. Below is the summary of Safe and Idempotent HTTP methods.

HTTP Method
Idempotent
Safe
OPTIONS
YES
YES
GET
YES
YES
HEAD
YES
YES
PUT
YES
NO
POST
NO
NO
DELETE
YES
NO
PATCH
NO
NO

6. Can you use POST request instead of GET to get a resource?

No, you are not supposed to use PUT or any other HTTP method to get the resource. GET method should only use to get the resource.
Please follow below link to know more about HTTP REST standards :

7. What is difference between @RequestParam and @PathVariable?

@RequestParam and @Queryparam is same where @QueryParam is a JAX-RS framework annotation and @RequestParam is from Spring.
These are the Query parameters which are appended after the ? to the url.
http://localhost:8080/students/101?param1=10& param2=20

In the above URL request, the values for param1 and param2 can be accessed as below:

public String getStudentDetails(
 @RequestParam(value="param1", required=true) String param1,
        @RequestParam(value="param2", required=false) String param2){
...
}

The following are the list of parameters supported by the @RequestParam annotation:
• defaultValue – This is the default value as a fallback mechanism if request is not having the value or it is empty.
• name – Name of the parameter to bind
• required – Whether the parameter is mandatory or not. If it is true, failing to send that parameter will fail.
• value – This is an alias for the name attribute

@PathVariable
These variables are the part of the url which are appended by the /.
http://localhost:8080/students/101
Here the 101 is the path url for the students Rest API. The above URL request can be written in your Spring MVC as below:

@RequestMapping("/students/{id}")
public String getStudentDetails(@PathVariable(value="id") String id){
...
}

8. How to validate the input data in Spring Rest?

Most of the time we need to create the validations on input model of the rest. To customize the validation, we will use Hibernate Validator, which is one of the implementations of the bean validation API. Refer below URL is know more about it :
https://www.onlyfullstack.com/spring-rest-input-validations/

9. How to document the Rest API?How you share the Rest API documentation?

Swagger UI allows to visualize and interact with the API’s resources without having any of the implementation logic in place. It’s automatically generated from your OpenAPI (formerly known as Swagger) Specification, with the visual documentation making it easy for back end implementation and client side consumption.
The Swagger 2 specification, which is known as OpenAPI specification, has several implementations. Currently, Springfox that has replaced Swagger-SpringMVC (Swagger 1.2 and older) is popular for Spring Boot applications. Springfox supports both Swagger 1.2 and 2.0.
To know more about Spring swagger – Rest API documentation : 
https://www.onlyfullstack.com/rest-documentation-swagger-2/

10. What is REST versioning?How to implement versioning Spring Rest?

Make the API Version mandatory and do not release an unversioned API. There are 4 techniques to version your API and you can choose as per your convenience.
Different types of Spring Rest Versioning ?

1. URI Path / Path Param – you include the version number in the URL path of the endpoint, for example /v1/students
2. Query Parameters – you pass the version number as a query parameter with specified name, for example / students?version=1
3. Custom HTTP Headers – you define a new header that contains the version number in the request
4. Content Negotiation – the version number is included to the “Accept” header together with accepted content type.

Refer below link to know more about each strategy and its pros and cons:
https://www.onlyfullstack.com/spring-rest-versioning/

11. How to implement the asynchronous Rest endpoint?

We can send the immediate response to the client and defer the execution later on the server. In this approach we speed up the server and client interaction and executes the remaining processing in an asynchronous way where a new thread is created to handle the execution.
With Asynchronous code we defer the execution part in another thread and close the incoming HTTP rest connection by responding back.
We can implement the asynchronous implementation with @Async annotation.
Refer below link to know more :
https://www.onlyfullstack.com/asynchronous-processing-in-spring/

12. What is the need of @ResponseBody?

@ResponseBody means that the controller’s return value should be used as the body of the response. That is, the HTTP response should be whatever is stated in the return value in the format specified by the Produces variable(JSON ? XML). Without the annotation, Spring would try to use the find the template with view resolver to render the view.

@GetMapping(value = "/connections", produces = {MediaType.APPLICATION_JSON_VALUE.                                       , MediaType.APPLICATION_ATOM_XML_VALUE})
public @ResponseBody FinalResponse getDataBaseConnectionDetails() {
return new FinalResponse(configServer.setup(), mailSettings);
}

13. How does @ResponseBody Works ?

On the other end, you have a RESTful architecture. In this case, there is no View. The Controller only sends back the model (or resource representation, in more RESTful terms). The client can be a JavaScript application, a Java server application, any application in which we expose our REST API to. With this architecture, the client decides what to do with this model. Take for instance Twitter. Twitter as the Web (REST) API, that allows our applications to use its API to get such things as status updates, so that we can use it to put that data in our application. That data will come in some format like JSON.

Depending on your configuration, spring has a list of HttpMessageConverters registered in the background. A HttpMessageConverters responsibility is to convert the request body to a specific class and back to the response body again, depending on a predefined mime type. Every time an issued request is hitting a @RequestBody or @ResponseBody annotation spring loops through all registered HttpMessageConverters seeking for the first that fits the given mime type and class and then uses it for the actual conversion.

14. How to change the response type dynamically in Spring Rest?How to write a web service which returns json and xml as response?

@GetMapping(value= "/connections", produces = { MediaType.APPLICATION_JSON_VALUE                                        , MediaType.APPLICATION_ATOM_XML_VALUE})
public @ResponseBody FinalResponse getDataBaseConnectionDetails() {
return new FinalResponse(configServer.setup(), mailSettings);
}
 

Spring supports a couple of conventions for selecting the format required: URL suffixes and/or a URL parameter. These work alongside the use of Accept headers. As a result, the content-type can be requested in any of three ways. By default they are checked in this order:
Ways to change the response type dynamically
1. Path Extension
Add a path extension (suffix) in the URL. So, if the incoming URL is something like http://localhost:8080/connections.json then the spring will return the response in JSON format. http://localhost:8080/connections.json then the spring will return the response in XML format.

2. URL parameter 
like this: http://myserver/myapp/accounts/list?format=xls. The name of the parameter is format by default, but this may be changed. Using a parameter is disabled by default, but when enabled, it is checked second.
http://localhost:8080/connections?format=json then the spring will return the response in JSON format.
http://localhost:8080/connections.json?format=xml then the spring will return the response in XML format.

3. Accept HTTP Header
Finally the Accept HTTP header property is checked. If Spring finds any Accept in header then it will convert the response accordingly.
Accept: application/json – the spring will return the response in JSON format.

Accept: application/xml –  the spring will return the response in XML format.

15. In how many ways you can return the HTTP status codes in Rest service?

1. HttpServletResponse
We can pass HttpServletResponse in our controller method and we can set the HTTP status explicitly depending ion the condition.

@RequestMapping(value = "/matches/{matchId}", produces = "application/json")
public String match(@PathVariable String matchId, @RequestBody String body,
            HttpServletRequest request, HttpServletResponse response) {
    String json = matchService.getMatchJson(matchId);
    if (json == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
    return json;
}

2. @ResponseStatus
We can send static response to every request coming to our REST endpoint.

@RequestMapping(value = "/sth")
@ResponseStatus(HttpStatus.OK)
public void name(HttpServletResponse response) throws Exception{
    boolean lever = service.doSomethingAndReturnTrueIfSucceedOrFalseIfNot();
    if(!lever){
throw new SomethingWentWrongCustomException("Not okay..");
     }
}

and we can handle the exception as

@ControllerAdvice
public class SomethingControllerAdvice{
    @ExceptionHandler(value = SomethingWentWrongCustomException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public void someName(){
    }
}

3. @ResponseEntity
Its most preferred way to return an entity with HTTP response status code.

@RequestMapping(value="/customer/{id}" ,headers = "Accept=application/json","application/xml")
public ResponseEntity<Customer> getCustomerById(@PathVariable String id)
{
    Customer customer;
    try
    {
        customer = customerService.getCustomerDetail(id);
    }
    catch (CustomerNotFoundException e)
    {
        return new ResponseEntity<Customer>(HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity<Customer>(customer,HttpStatus.OK);
}

2 Comments

Comments are closed.