RestFul Questions


What are RESTful web services?
Just like SOAP (Simple Object Access Protocol), which is used to develop web services by XML method, RESTful web services use web protocol i.e. HTTP protocol method. They have the feature like scalability, maintainability, help multiple application communication built on various programming languages etc.
RESTful web service implementation defines the method of accessing various resources which are required by the client and he has sent the request to the server through the web browser. The important aspects of this implementation include:
  • Resources
  • Request Headers
  • Request Body
  • Response Body
  • Status codes

Compare SOAP and REST web services?
SOAP
REST
SOAP is a standard protocol for creating web services.
REST is an architectural style to create web services.
SOAP is acronym for Simple Object Access Protocol.
REST is acronym for REpresentational State Transfer.
SOAP uses WSDL to expose supported methods and technical details.
REST exposes methods through URIs, there are no technical details.
SOAP web services and client programs are bind with WSDL contract
REST doesn’t have any contract defined between server and client
SOAP web services and client are tightly coupled with contract.
REST web services are loosely coupled.
SOAP learning curve is hard, requires us to learn about WSDL generation, client stubs creation etc.
REST learning curve is simple, POJO classes can be generated easily and works on simple HTTP methods.
SOAP supports XML data format only
REST supports any data type such as XML, JSON, image etc.
SOAP web services are hard to maintain, any change in WSDL contract requires us to create client stubs again and then make changes to client code.
REST web services are easy to maintain when compared to SOAP, a new method can be added without any change at client side for existing resources.
SOAP web services can be tested through programs or software such as Soap UI.
REST can be easily tested through CURL command, Browsers and extensions such as Chrome Postman.

Name the protocol which is used by RESTful web services?
RESTful web services use a famous web protocol i.e. HTTP protocol. This serves as a medium of data communication between client and server. HTTP standard methods are used to access resources in RESTful web service architecture.

What are the core components of HTTP request and HTTP response?
The core components that come under HTTP Request are:
  • Verb: Includes methods like GET, PUT, POST, DELETE, etc.
  • Uniform Resource Identifier for identifying the resources available on the server.
  • HTTP Version for specifying the HTTP version.
  • HTTP Request header for containing the information about the data.
  • HTTP Request body that contains the representation of the resources in use.
The core components that come under HTTP Response are:
  • Response Code: This contains various codes which determine the status of the server response.
  • HTTP Version for specifying the HTTP version.
  • HTTP Response header for containing the information about the data.
  • HTTP Response body that contains the representation of the resources in use.

Explain the term ‘Statelessness’ with respect to RESTful web service and list the advantages and disadvantages?
The state of the client’s application is never stored on the server and is passed on. In this process, the clients send all the information that is required for the server to fulfill the HTTP request that has been sent. Thus every client request and the response is independent of the other with complete assurance of providing required information.
Every client passes a ‘session identifier’ which also acts as an identifier for each session.
Advantages:
  • Every method required for communication is identified as an independent method i.e. there are no dependencies to other methods.
  • Any previous communication with the client and server is not maintained and thus the whole process is very much simplified.
  • If any information or metadata used earlier in required in another method, then the client sends again that information with HTTP request.
  • HTTP protocol and REST web service, both shares the feature of statelessness.
Disadvantages:
  • In every HTTP request from the client, the availability of some information regarding the client state is required by the web service.

What is a ‘Resource’?
Just like the ‘Object’ instance, we have learned in object orient programming Language, in the same way, ‘Resource’ is defined as an object of a type which can be an image, HTML file, text data, and any type of dynamic data. There are varieties of representation formats available in order to represent a resource.
Some most common are enlisted below:
  • JSON
  • XML
  • YAML
  • HTML

What is URI? What is the main purpose of REST-based web services and what is its format?
URI stands for Uniform Resource Identifier. It is a string of characters designed for unambiguous identification of resources and extensibility via the URI scheme. The purpose of a URI is to locate a resource(s) on the server hosting of the web service.
A URI’s format is <protocol>://<service-name>/<ResourceType>/<ResourceID>.

List some of the HTTP methods with description.
  • GET: This is a read only operation which fetches the data from the server.
  • PUT: This operation is used for the creation of any new resource on the server.
  • POST: This operation is used for updating an old resource.
  • DELETE: This operation is used for deleting any resource on the server.
  • OPTIONS: This operation fetches the list of any supported options of resources that are available on the server.

What is the difference between PUT method and POST method?
The major difference between the PUT and POST method is that the result generated with PUT method is always same no matter how many times the operation is performed. On the other hand, the result generated by POST operation is always different every time. PUT is idempotent.

What are idempotent operations? Why is idempotency important? 
There are some HTTP methods e.g. GET which produce same response no matter how many times you use them e.g. sending multiple GET request to the same URI will result in same response without any side-effect hence it is known as idempotent.

On the other hand, the POST is not idempotent because if you send multiple POST request, it will result in multiple resource creation on the server, but again, PUT is idempotent if you are using it to update the resource.

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 is known as safe operations e.g. GET and HEAD. On the other hand, PUT, POST, and DELETE are unsafe because they modify the resource on the server.

What are the best practices that are to be followed while designing RESTful web services?
To design a secure RESTful web service, there are some best practices or say points that should be considered. These are explained as follows:
  • In Rest, we think Nouns (resources) and NOT Verbs (NOT actions). So, URI’s should represent resources. URI’s should be hierarchical and as self-descriptive as possible. Prefer plurals.
  • Every input on the server should be validated.
  • Input should be well formed.
  • Never pass any sensitive data through URL.
  • For any session, the user should be authenticated.
  • Only HTTP error messages should be used for indicating any fault.
  • Use message format that is easily understood and is required by the client.
  • Unified Resource Identifier should be descriptive and easily understood.

What is Payload?
The request data which is present in the body part of every HTTP message is referred as ‘Payload’. In Restful web service, the payload can only be passed to the recipient through POST method.
There is no limit of sending data as payload through POST method but the only concern is that more data with consuming more time and bandwidth. This may consume much of user’s time also.

What is HATEOAS in REST?
HATEOAS stand for Hypermedia as the Engine of Application State. It provides links to resources so that client does not have to manually bookmark the links. Below is an example.
{
"id":1,
"message":"Hello World",
"author":"Dhiraj",
"href":"/messages/1"
}

List some of the HTTP states codes?
1xx Informational
100 Continue

2xx Success
200 OK, shows success.
201 Created, when a resource is successful created using POST or PUT request.
204 No Content, when response body is empty for example, a DELETE request.

3xx Redirection
302 Found
304 Not modified, used to reduce network bandwidth usage in case of conditional GET requests. Response body should be empty
307 Temporary Redirect
308 Permanent Redirect

4xx Client Error
400 Bad Request, states that invalid input is provided e.g. validation error, missing data.
401 Unauthorized, the request has not been applied because it lacks valid authentication credentials for the target resource.
403 Forbidden, states that user is not having access to method being used for example, delete access without admin rights.
404 Not Found, states that method is not available.
405 Method Not Allowed

5xx Server Error
500 Internal Server Error, states that server has thrown some exception while executing the method.
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout

Is REST scalable and/or interoperable?
Yes, REST is Scalable and interoperable. It doesn't mandate a specific choice of technology either at client or server end. You can use Java, C++, Python or JavaScript to create RESTful Web Services and consume them at the client end.

What does @RequestMapping annotation do?
The @RequestMapping annotation is used to map web requests to Spring Controller methods. You can map request based upon HTTP methods e.g. GET and POST and various other parameters. For examples, if you are developing RESTful Web Service using Spring then you can use produces and consumes property along with media type annotation to indicate that this method is only used to produce or consumers JSON as shown below:
@RequestMapping (method= RequestMethod.POST, consumes="application/json")

Is @Controller a stereotype? Is @RestController a stereotype?
Yes, both @Controller and @RestController are stereotypes. The @Controller is actually a specialization of Spring's @Component stereotype annotation. This means that class annotated with @Controller will also be automatically be detected by Spring container as part of container's component scanning process.

And, @RestController is a specialization of @Controller for RESTful web service. It not only combines @ResponseBody and @Controller annotation but also gives more meaning to your controller class to clearly indicate that it deals with RESTful requests
 
What is the difference between @Controller and @RestController?
There are many differences between @Controller and @RestController, but the most important one is that with @RestController you get the @ResponseBody annotation automatically, which means you don't need to separately annotate your handler methods with @ResponseBody annotation. This makes the development of RESTful web service easier using Spring. 

Do you need Spring MVC in your classpath for developing RESTful Web Service?
Yes, you need Spring MVC in your Java application's classpath to develop RESTful web services using Spring framework. It's actually Spring MVC which provides all useful annotations e.g. @RestController@ResponseCode@ResponseBody@RequestBody, and @PathVariable, hence you must spring-mvc.jar or appropriate Maven entry in your pom.xml

What is the HTTP status return code for a successful DELETE statement?
There is no strict rule with respect to what status code your REST API should return after a successful DELETE i.e it can return 200 OK or 204 No Content. In general, if the DELETE operation is successful and the response body is empty return 204. If the DELETE request is successful and the response body is NOT empty, return 200

Where do you need @EnableWebMVC?
The @EnableWebMvc annotation is required to enable Spring MVC when Java configuration is used to configure Spring MVC instead of XML. It is equivalent to <mvc: annotation-driven> in XML configuration.

It enables support for @Controller-annotated classes that use @RequestMapping to map incoming requests to handler methods 

When do you need @ResponseStatus annotation in Spring MVC?
The @ResponseStatus annotation is required during error handling in Spring MVC and REST. Normally when an error or exception is thrown at server side, web server return a blanket HTTP status code 500 - Internal server error.

This may work for a human user but not for REST clients. You need to send them proper status code e.g. 404 if the resource is not found. That's where you can use @ResponseStatus annotation, which allows you to send custom HTTP status code along with proper error message in case of Exception.

In order to use it, you can create custom exceptions and annotated those using @ResponseStatus annotation and proper HTTP status code and reason.

When such exceptions are thrown from controller's handler methods and not handled anywhere else, then appropriate HTTP response with the proper HTTP status code, which you have set is sent to the client.

For example, if you are writing a RESTful Web Service for a library which provides book information then you can use @ResponseStatus to create Exception which returns HTTP response code 404 when a book is not found instead of Internal Server Error (500), as shown below:

@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such Book") // 404
public class BookNotFoundException extends RuntimeException {
// ...
}

How to set different status code in HTTP response?
For setting HTTP status code other than 200, we have to use javax.ws.rs.core.Response class for response. Below are some of the sample return statements showing it’s usage.

return Response.status(405).entity(exception).build();
return Response.ok(response).build(); //200

What is the use of Accept and Content-Type Headers in HTTP Request?
These are important headers in Restful web services. Accept headers tells web service what kind of response client is accepting, so if a web service is capable of sending response in XML and JSON format and client sends Accept header as “application/xml” then XML response will be sent. For Accept header “application/json”, server will send the JSON response.
Content-Type header is used to tell server what is the format of data being sent in the request. If Content-Type header is “application/xml” then server will try to parse it as XML data. This header is useful in HTTP Post and Put requests.

What is Caching?
Caching is the process in which server response is stored so that a cached copy can be used when required and there is no need of generating the same response again. This process not only reduces the server load but in turn increase the scalability and performance of the server. Only the client is able to cache the response and that too for a limited period of time.
Mentioned below are the header of the resources and their brief description so that they can be identified for the caching process:
  • Time and Date of resource creation
  • Time and date of resource modification that usually stores the last detail.
  • Cache control header
  • Time and date at which the cached resource will expire.
  • The age which determines the time from when the resource has been fetched.

Explain Cache-control header.
A standard Cache control header can help in attaining cache ability. Enlisted below is the brief description of various cache control header:
  • Public: Resources that are marked as the public can be cached by any intermediate components between the client and server.
  • Private: Resources that are marked as private can only be cached by the client.
  • No cache means that particular resource cannot be cached and thus the whole process is stopped.

What are the different ways of Restful Web Services Versioning?
URI Versioning
Basic approach to versioning is to create a completely different URI for the new service. Example implementation is shown in the example code.
Example URL’s
http://localhost:8080/rest/v1/person

Request Parameter versioning
In request parameter versioning the version number is passed URI as the request parameter. 
Example URL’s
http://localhost:8080/rest/person/param?version=1
http://localhost:8080/rest/person/param?version=2

(Custom) Headers versioning
The third approach to versioning is to use a Request Header, pass the version number in the header.
Example URL’s
http://localhost:8080/rest/person/header
headers [X-API-VERSION=1]
http://localhost:8080/rest/person/header
headers [X-API-VERSION=2]

Media type versioning (“content negotiation” or “accept header”)
The fourth versioning approach is to use the Accept Header in the request.
Examples
http://localhost:8080/rest/person/produces
headers[Accept=application/vnd.company.app-v1+json]
http://localhost:8080/rest/person/produces
headers[Accept=application/vnd.company.app-v2+json]

RestFul example snippet?
@RestController
public class EmployeeController {
// Map to store employees, ideally it should come from database
Map<Integer, Employee> empData = new HashMap<Integer, Employee>();

@Autowired
private EmployeeService employeeService;

@RequestMapping(value = "/rest/emp/default", method = RequestMethod.GET, produces = "application/json")
public @ResponseBody Employee getDefaultEmployee() {
Employee emp = new Employee();
empData.put(9999, emp);
emp = employeeService.getDefaultEmployeeService();
return emp;
}
               
@RequestMapping(value = "/rest/emp/create", method = RequestMethod.POST, produces = "application/json")
public @ResponseBody Employee createEmployee(@RequestBody Employee emp) {
System.out.println("Start createEmployee.");
emp.setCreatedDate(new Date());
empData.put(emp.getId(), emp);
return emp;
}
}
  




No comments:

Post a Comment