REST

What are REST and RESTful web services ?

REST is architectural style for building web service using HTTP protocol and REST stands for REpresentational State Transfer (REST). REST is a relatively new concept of writing web API which enforces a stateless client server design where data and functionality are considered resources and are accessed using Uniform Resource Identifiers (URIs), typically links on the Web.

Restful web API (also called a RESTful web service) is a web API implemented using HTTP and the REST principles.

Explain the architectural style REST API ?

  • It is a client/server architecture.
  • It uses a stateless communication protocol, typically HTTP.
  • It uses simple URI as an address for the service.
  • It uses different MIME media types(JSON, XML, Text, HTML etc.) as data formats.

What principles encourage RESTful applications to be simple, lightweight, and fast ?

Resource identification through URI: A RESTful web service exposes a set of resources that identify the targets of the interaction with its clients. Resources are identified by URIs, which provide a global addressing space for resource and service discovery.

Uniform interface: Resources are manipulated using a fixed set of four create, read, update, delete operations: PUT, GET, POST, and DELETE. PUT creates a new resource, which can then be deleted by using DELETE. GET retrieves the current state of a resource in some representation. POST transfers a new state onto a resource.

Self-descriptive messages: Resources are decoupled from their representation so that their content can be accessed in a variety of formats, such as HTML, XML, plain text, PDF, JPEG, JSON, and others. Metadata about the resource is available and used, for example, to control caching, detect transmission errors, negotiate the appropriate representation format, and perform authentication or access control.

Stateful interactions through hyperlinks: Every interaction with a resource is stateless; that is, request messages are self-contained. Stateful interactions are based on the concept of explicit state transfer. Several techniques exist to exchange state, such as URL rewriting, cookies, and hidden form fields. State can be embedded in response messages to point to valid future states of the interaction.

What is Payload in terms of RESTful web services?

Payload refers to the data which are passed in the body of the request. It is not the same as the request parameters. The payload can be sent only in POST methods as part of the request body.

What tool is required to test your REST API ?

Postman, Firexfox poster plugin or firefox REST client, Talend API Tester, etc.

Describe HTTP methods used in REST API ?

HTTP GET: It requests a resource at the request URL. It is used to Get/List/Retrieve an individual resource or a collection of resources. It does not need to contain a request body as it will be discarded.

HTTP POST: Creates a new resource or resources. It requires a request body in the processing.

HTTP PUT: Updates an existing resource or collection of resources.

HTTP DELETE: Deletes a resource or collection of resources.

HTTP OPTIONS: It indicates which techniques are supported.

HTTP HEAD: About the request URL it returns meta information.

Differences between REST and SOAP web services

Here are some of Key differences between SOAP and REST web Service :

  • REST uses HTTP/HTTPS, SOAP can use almost any transport to send the request(for example we can have SOAP Messages over SMTP), SOAP is an XML based messaging protocol.
  • REST is totally stateless operations where as SOAP supports statefull calls too.
  • SOAP has more strict contract in the form of WSDL between applications, no such contract exists in case of REST.
  • As REST APIs can be consumed using simple GET requests, REST response can be cached, this is not possible with SOAP.
  • REST is lighter but SOAP is heavier because requires an XML wrapper around every request and response(SOAP Headers, XML tags etc).
  • SOAP message format is restricted to XML only where as REST supports other formats too, for example JSON, Text, HTML etc.
  • REST is simpler in terms of development as compared to SOAP.
  • Browsers can handle REST easily as compared to SOAP as REST is based on HTTP where SOAP is another wrapper over HTTP.
  • In case of failure SOAP has built-in retry logic but REST has no such mechanism.
  • SOAP maintains ACID properties and supports two phase commit on transactions but REST has no such support.
  • SOAP has built-in WS* Security support but in case of REST we have to implement it.

Does a RESTful web service have an ability to generate output in different formats, based on a parameter given by the end user ?

Yes it has, certainly if we use Jersey framework. We can specify multiple comma separated MediaType formats(text, xml, json etc.) in @Produces annotation. And the service method should return the Java object itself. Now depending on client supplied format parameter, Jersey framework will convert the Java object to appropriate media type and send that to client.

Could an internet browser be a client to RESTful web service, or not ?

Yes, definitely. Because REST works on HTTP protocol and so is internet browsers. For out project, we use a plugin for Firefox named RESTClient where we can specify Method Type, Header details like content type etc. We have Postman for Google chrome.

Can you name the main distinctions between a RESTful web service and HTTP Servlet, if both of them are designed to perform the exactly same function ?

  • One difference is for deploying a Servlet application you need a Java based Web Server. But you can develop and deploy a REST web service in .Net using IIS server or in PHP using Apache HTTP server.
  • Similarly REST can be accessed by both Java and .NET platform clients. But not sure if we can write HTTPClient in .NET framework to access a Servlet application.
  • One difference comes straight out of the very name RESTful. In REST, all the information that is required for the service method to work means the Representational State is to be supplied at one go, at least if you want to be fully compliant with REST architecture. There is no server to hold any kind of state. Wherein in sever based web application, state can be held in Web Server context.
  • Another difference: if you go by architectural constraint laid down by W3C, REST server should not hold any client state at all. But in servlet application we have a dedicated API of HTTP Session to hold user state.

Can you name the main difference of HTTP POST and PUT requests, from the point of view of final user ?

The use of an HTTP PUT method versus an HTTP POST method should be based on the idempotent aspect of that operation. That is, if the operation is idempotent, then use the HTTP PUT method. If the operation is non-idempotent, then use the HTTP POST method.

According to the HTTP 1.1 specifications the GET, HEAD, DELETE, and PUT methods must be idempotent, and the POST method is not idempotent.

An operation is idempotent if it can be performed on a resource once or many times and always return the same state of that resource. Whereas a non idempotent operation can return a modified state of the resource from one request to another.

Hence, in a non idempotent operation, there is no guarantee that one will receive the same state of a resource.

Examples:

Idempotent: If you add an Employee with same ID. First Time it will be added to the repository. Then onwards no change in repository as the Employee is already there. A=4 is an idempotent operation
Non-Idempotent: Submitting request for take-out money in ATM. Successive request will keep on decreasing the account balance and thus changing the repository. A++ is a Non-idempotent

Idempotency is important in building a fault-tolerant API. Suppose a client wants to update a resource through POST. Since POST is not an idempotent method, calling it multiple times can result in wrong updates.

What would happen if you sent out the POST request to the server, but you get a timeout. Is the resource actually updated ? Does the timeout happen during sending the request to the server, or the response to the client ? Can we safely retry again, or do we need to figure out first what has happened with the resource ? By using idempotent methods, we do not have to answer this question, but we can safely resend the request until we actually get a response back from the server.

Name output formats that can be generated using RESTful web service.

XML, JSON, PJSON(Prettified JSON ), HTML, Plain Text

Do you know how JAXB is associated with RESTful web services ?

JAXB stands from Java API for XML Binding. It is used for Java Object to XML conversion (Marshaling) and vice versa (Un-marshaling).

This is required when we develop REST to produce and/or consume Java object. Actually data is sent to REST as XML and in after consuming REST service convert it into Java object using JAXB.

Note that if you are using Jersey framework, JAXB is embedded and you only need to have JAXB compliant class for that Java object.

How will you cope up with synchronization problem when multiple clients attempt to use web service simultaneously ?

REST approach is straightforward. For each request a new web resource instance is created to serve the request.

Could we use GET request as an alternative to PUT request to generate resources ?

You should not. If a seemingly safe method like GET will change a resource, it might be possible that any middleware client proxy systems between you and the server, will cache this response.

Another client who wants to change this resource through the same URL (like: http://example.org/api/article/124/delete), will not call the server, but return the information directly from the cache. Non-safe (and non-idempotent) methods will never be cached by any middleware proxies.

What is Safe method ?

Safe methods are HTTP methods that do not modify resources. For instance, using GET or HEAD on a resource URL should never change the resource. Non-safe (and non-idempotent) methods will never be cached by any middleware proxies.

Using a RESTful web service, whose state is actually getting transferred and how this happens from a point of view of programmer ?

It is the resource’s state that is transferred. Remember REST is stateless means it is not concerned with client’s state. For example, the server may send data from its database as HTML, XML or JSON, none of which are the server’s internal representation, and it is the same one resource regardless.

What is Restlet framework ?

Restlet is leading RESTful web framework for Java applications is used to build RESTFul web services it has two part Restlet API and a Restlet implementation much like Servlet specification. There are many implementation of Restet framework available you just need to add there jar in your classpath to use them. By using Restlet web framework you can write client and server.

What is a Resource in REST framework ?

It represents a “resource” in REST architecture. on RESTLET API it has life cycle methods like init(), handle() and release() and contains a Context, Request and Response corresponding to specific target resource. This is now deprecated over ServerResource class and you should use that.

Can you use Restlet without any web-container ?

Yes, Restlet framework provide default server which can be used to handle service request in web container is not available.

What is RESTEasy ?

RESTEasy is another REST framework introduced in JBoss Application Server.

What are the tools used for creating RESTFull web services ?

You can use AJAX(Asynchronous JavaScript with XAML) and Direct Web Removing to consume web serives in web application. Both Eclipse and NetBeans also supported development of RESTFul services.

How to display custom error pages using RESTFull web services ?

In order to customize error you need to extend StatusService and implement getRepresentation(Status, Request, Response) method with your custom code now assign instance of your CustomStatusService to appropriate “statusService property”.

What is HATEOAS?

HATEOAS is an acronym for Hypermedia As The Engine Of Application State. HATEOAS is an extra level on REST (REpresentational State Transfer) API and is used to present information about the REST API to the client, allowing for a better understanding of the API without the need to bring up the specification or documentation. This is done by including the related links in a returned response from a resource in REST API and using only these links to further communicate with the sever. So the representations returned for REST resources contain not only data, but links to related resources.

HATEOAS is an approach that breaks down the principal elements of a REST approach into three steps are resources, http verbs and hypermedia controls:

  • Without using any mechanism of the web, HTTP is used as a transport system for remote interactions.
  • Every individual service end point in REST is treated as resource.
  • Every operation is performed on HTTP protocol using HTTP verbs such as, GET, POST, PUT, DELETE, etc.
  • Finally, comes hypermedia control, where a list of related links is returned in the response of the resource, which is known as HATEOAS.

You can read an example on HATEOAS using Spring.

How would you ensure that the cached responses of the REST API is not stale?

Let’s assume you have implemented caching of REST API in your client or web service (which depends on other webservices).

Depending on the rate at which you expect the information to change, you can have different mechanism. You have to keep additional metadata about the API response to implement caching + avoiding stale data. Meta data that you require would be: (a) when did you last receive the data, (b) was there an “Expires” header in the response, (c) history or rate of change of data etc.

After that, you can implement on or more of following:

  1. Issue “GET + If-modified-since” (GIMS) request instead of simple GET request.
  2. When your server receives down stream REST API, respond from the cache; but immediately after that, asynchronously refresh your cache from upstream server(s).
  3. Issue GIMS request if you are at more than half the time between last refresh check and cache expiry.
  4. If your upstream service has put too conservative Expiry header, then you can add additional logic to issue GIMS even after cache expiry using rate of change of data algorithm. Let’s say, t0 is when you received original data. Expiry header says response will expire in 5 days. So, on 6th day, you issue GIMS. If it’s still not expired, you assume effective expiry date = t0 + 5 days + 2 * (now – expiry as per Expires: header). So, you won’t check for 2 more days. On 8th day, you again check issue GIMS. If server ever returns 200 ok response, t0 resets.

How would you ensure that you meet your SLA most of the times?

Problem Scenario

Let’s assume, you are writing a micro service that has signed up for certain SLA of response time. Let’s say, you must respond within 1 second of receiving the request. However, your micro service depends on 3 external micro services with 500 ms SLA each.

Solution

REST API Caching is the primary solution to meet the response time SLA requirements. You should cache the response from the other micro services; with proper mechanism to deal with staleness of the cache.

Explain the architectural style for creating web API?

The architectural style for creating web API are HTTP for client server communication XML/JSON as formatting language Simple URI as the address for the services Stateless communication.

Is it possible to send payload in the GET and DELETE methods?

No, the payload is not the same as the request parameters. Hence, it is not possible to send payload data in these methods.

How do you provide security to REST API?

Best Practices to Secure REST APIs are to keep it simple. Secure an API/System – just how secure it needs to be. Always use HTTPS. Use password hash instead of plain text. Never expose information on URLs. Consider OAuth for authentication mechanism. Consider adding timestamp in request. Input parameter validation must be applied.