Google News
logo
Rest API Interview Questions
The implementation consisted of running the code from the JUnit tests into the APIs and then refreshing the tests to summon those APIs. The modifyCertificate method, which gives the implementation for the certificates resource PUT method, is the most difficult REST API to implement.
Representational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing.
 
REST technology is generally preferred to the more robust Simple Object Access Protocol (SOAP) technology because REST uses less bandwidth, simple and flexible making it more suitable for internet usage. It’s used to fetch or give some information from a web service. All communication done via REST API uses only HTTP request.
Key characteristics of REST include :
 
* REST is stateless, therefore the SERVER has no state (or session data).
* With a well-applied REST API, the server could be restarted between two calls as every data is passed to the server.
* Web service mostly uses POST method to make operations, whereas REST uses GET to access resources.
GET : This requests a resource at the request URL. It should not contain a request body as it will be discarded. It can be cached locally or on the server.

POST : This submits information to the service for processing; it should typically return the modified or new resource.

PUT : At the request URL, this updates the resource.

DELETE : At the request URL, this removes the resource.

OPTIONS : This indicates which techniques are supported.

HEAD : This returns meta-information about the request URL.
Caching is used for network optimization by reducing the load on servers. It is the ability to store copies of frequently accessed data. Get Requests are by default cacheable, however, Post can be made cacheable.
SOAP is more reliable than REST as it practices WS-Security for transmission with Secure Socket Layer. Also, SOAP is state-full as it takes the request as a whole, unlike REST which gives independent processing of various methods. No independent processing is present in SOAP.
The “payload” is the data you are interested in transporting. This is differentiated from the things that wrap the data for transport like the HTTP/S Request/Response headers, authentication, etc.
There are two kinds of web services :
 
* SOAP Web Services
* RESTFUL Web Services

1. SOAP (Simple Object Access Protocol) : SOAP is a XML based method which is used in Web Services.
 
2. RESTFUL Web Services : To implement the concept of REST architecture HTTP method is used. RESTFUL Web Services defines URI (Uniform Resource Identifier), and also provides resource representation like JSON and a set of HTTP method.
RESTFUL Web Services use the HTTP protocol as a communication tool between the client and the server. This is the technique when the client sends a message in the form of HTTP request the server send back the HTTP reply which is called Messaging. This message consists message data and Meta data i.e. information on the message itself.
PUT POST
The PUT method is a call when you have to modify a single resource, which is part of resource collection. POST method is a call when you have to add a child resource under resource collection.
The PUT method is idempotent POST method is not idempotent
PUT for UPDATE operations. POST for CREATE operations.
If the PUT request is used more than one time, the results will remain the same. If a POST request is used multiple times, the results will be different.
PUT works as specific. POST work as abstract.
Every RESTful web service has the following features :
 
* The service is based on the Client-Server model.

* The service uses HTTP Protocol for fetching data/resources, query execution, or any other functions.

* The medium of communication between the client and server is called “Messaging”.

* Resources are accessible to the service by means of URIs.

* It follows the statelessness concept where the client request and response are not dependent on others and thereby provides total assurance of getting the required data.

* These services also use the concept of caching to minimize the server calls for the same type of repeated requests.

* These services can also use SOAP services as implementation protocol to REST architectural pattern.
REST represents REpresentational State Transfer; it is a relatively new aspect of writing web API.
 
RESTFUL is referred for web services written by applying REST architectural concept are called RESTful services, it focuses on system resources and how state of resource should be transported over HTTP protocol to different clients written in different language. In RESTFUL web service HTTP methods like GET, POST, PUT and DELETE can be used to perform CRUD operations.
13 .
Mention whether you can use GET request instead of PUT to create a resource?
No, you are not supposed to use PUT for GET. GET operations should only have view rights, while PUT resource is used for updating a data.
AJAX REST
In Ajax, the request are sent to the server by using XMLHttpRequest objects. The response is used by the JavaScript code to dynamically alter the current page. REST have a URL structure and a request/response pattern the revolve around the use of resources.
Ajax is a set of technology; it is a technique of dynamically updating parts of UI without having to reload the page. REST is a type of software architecture and a method for users to request data or information from servers.
Ajax eliminates the interaction between the customer and server asynchronously. REST requires the interaction between the customer and server.
In document style web services, we can transport an XML message as part of SOAP request which is not possible in RPC style web service. Document style web service is most appropriate in some application where XML message behaves as document and content of that document can alter and intention of web service does not rely on the content of XML message.
JAX-RS stands for Java API for RESTful Web services. They are nothing but a set of Java-based APIs that are provided in the Java EE which is useful in the implementation and development of RESTful web services.
 
Features of JAX-RS are :
 
POJO-based : The APIs in the JAX-RS is based on a certain set of annotations, classes, and interfaces that are used with POJO (Plain Old Java Object) to expose the services as web services.

HTTP-based : The JAX-RS APIs are designed using HTTP as their base protocol. They support the HTTP usage patterns and they provide the corresponding mapping between the HTTP actions and the API classes.

Format Independent : They can be used to work with a wide range of data types that are supported by the HTTP body content.

Container Independent : The APIs can be deployed in the Java EE container or a servlet container such as Tomcat or they can also be plugged into JAX-WS (Java API for XML-based web services) providers.
A resource class is nothing but a Java class that uses JAX-RS provided annotations for implementing web resources.

They are the POJOs that are annotated either with @Path or have at least one method annotated with @Path, @GET, @POST, @DELETE, @PUT, etc.

Example :
import javax.ws.rs.Path;
/**
* InterviewBitService is a root resource class that is exposed at 'resource_service' path
*/
@Path('resource_service')
public class InterviewBitService {
   // Defined methods
}
The Java EE 6 release took the first step towards standardizing RESTful web service APIs by introducing a Java API for RESTful web services (JAX-RS).
 
JAX-RS ensures the portability of REST API code across all Java EE-compliant application servers. The latest version is JAX-RS 2.0, which was released as part of the Java EE 7 platform.
 
JAX-RS focuses on applying Java annotations to plain Java objects. JAX-RS has annotations to bind specific URI patterns and HTTP operations to specific methods of your Java class. It also has annotations that can help you handle input/output parameters.
 
As we already said that JAX-RS is a specification; it means we need to have its implementation to run REST API code. Some of the popular JAX-RS implementations available today are:
 
* Jersey
* RESTEasy
* Apache CXF
* Restlet

Source : Restfulapi
By applying the principle of generality to the components interface, we can simplify the overall system architecture and improve the visibility of interactions.
 
Multiple architectural constraints help in obtaining a uniform interface and guiding the behavior of components.
 
The following four constraints can achieve a uniform REST interface :
 
Identification of resources – The interface must uniquely identify each resource involved in the interaction between the client and the server.

Manipulation of resources through representations – The resources should have uniform representations in the server response. API consumers should use these representations to modify the resources state in the server.

Self-descriptive messages – Each resource representation should carry enough information to describe how to process the message. It should also provide information of the additional actions that the client can perform on the resource.

Hypermedia as the engine of application state – The client should have only the initial URI of the application. The client application should dynamically drive all other resources and interactions with the use of hyperlinks.
SOAP REST
SOAP is a protocol through which two computer communicates by sharing XML document. Rest is a service architecture and design for network-based software architectures.
SOAP permits only XML REST supports many different data formats
SOAP based reads cannot be cached REST reads can be cached
SOAP is like custom desktop application, closely connected to the server A REST client is more like a browser; it knows how to standardized methods and an application has to fit inside it
SOAP is slower than REST REST is faster than SOAP
It runs on HTTP but envelopes the message It uses the HTTP headers to hold meta information
REST APIs must adhere to five requirements :
 
Client-server decoupling : The client and server can only interact in a series of requests and responses. Only clients can make requests, and only servers can send responses. This simple principle allows both parties to operate independently of each other.

Uniform interface : All communications between the client and server must follow the same protocol. For REST, this protocol is HTTP. A uniform interface simplifies integrations because every application is using the same language to request and send data.

Stateless : In stateless communication, the server does not store any information about past requests/responses. Each request and response contains all information needed to complete the interaction. Stateless communication reduces server load, saves memory, and improves performance. It also eliminates the possibility of a failed request caused by missing data.

Layered system : Layers are servers that sit between the client and API server. These additional servers perform various functions, like identifying spam and improving performance (See also: What Is a CDN?). In REST, layers are modular and can be added and removed without affecting the messages between the client and the API server.

Cacheable : Server responses indicate whether or not the resource is cacheable, so that clients can cache any resources to improve performance.

Additionally, REST includes one optional condition :
 
Code on demand : An API can send executable computer code to clients in its response. This lets the client application run the code in its own back end.
Statelessness is one of the key principles of REST architecture. In stateless communication, the server does not store any information about previous communications. In other words, the client and server do not know each other’s state. Every request and response is a new interaction, and each request includes everything the server needs to give a successful response.
 
Statelessness simplifies client-server interactions because the server does not rely on past requests to process future requests, and thus does not need to consume space and resources storing data from these requests.
REST APIs use the HTTP protocol to communicate with clients. This allows REST APIs to be easily deployed over the internet, since HTTP is the same protocol that is used to deliver web pages to client browsers.
CRUD stands for “Create, Read, Update, Delete.” These are the four basic actions that can be performed on databases through a REST API. Each action corresponds to an HTTP request method :
 
* Create = POST
* Read = GET
* Update = PUT
* Delete = DELETE

It’s not the most elegant of acronyms, but it works.
The core components under HTTP Request are :
 
* Verb : Includes methods like GET, PUT, POST, 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 under HTTP Response are:
 
* Request Code : This contains various codes that 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.
In REST, ST itself defines State Transfer and Statelessness means complete isolation. This means, 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 requests and the response is independent of the other with complete assurance of providing the required information.
 
Every client passes a ‘session identifier’ which also acts as an identifier for each session.
We have understood the meaning of statelessness with respect to client-server communication. Now, let us see some of its advantages and disadvantages.
 
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 the HTTP request.
* The 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.
28 .
What are "Options" in REST APIs? 
It is an HTTP method used to fetch the supported HTTP options or operations that help clients to choose the options in REST APIs. Cross-Origin Resource Sharing (CORS) uses the REST option method.
In REST, messaging refers to the back-and-forth communication between the client and API. An interaction always starts with the client messaging the API with an HTTP request. The API processes this request, then sends back an HTTP response that gives the status of the request and any resources the client asked for.
HTTP requests are sent by the client to the API. They request data or perform some action on the server. There are five main components of an HTTP request in REST :
 
* Start line : Indicates the intended action of the request and includes:

* a request method that indicates the HTTP request method to be performed on the resource (i.e., GET, POST, PUT, DELETE).

* a URI that identifies the requested resource on the server.

* the HTTP version being used, which signals which version the API should respond with.

* HTTP Request Header : Lists metadata about the request, such as the user agent, file formats the client will accept, format of the request body, language, caching preferences, etc.

* HTTP Request body : Contains any data associated with the request. This is only necessary if the request is to modify data on the server with the POST or PUT methods.
HTTP response status codes tell the client the result of the requested action (GET, POST, etc.). Some common codes you’ll see in HTTP responses are:
 
200 OK : The request succeeded.

201 Created : The request succeeded and a resource was created.

400 Bad Request : The request was not fulfilled due to an error in the request, such as a typo or missing data.

401 Unauthorized : The request was not fulfilled because the client is not authenticated or authorized to access the requested resource.

403 Forbidden : The request was not fulfilled because the client is authenticated, but not authorized to access the requested resource.

404 Not Found : The request was not fulfilled because the server could not locate the requested resource.

500 Internal Server Error : The request was not fulfilled due to an unexpected problem with the server. (See also: 500 Internal Server Errors: What They Are & How to Fix Them)

502 Bad Gateway : The request was not fulfilled due to an invalid response from an upstream server.

503 Service Unavailable : The server was unable to process the request due to maintenance, overloading, or another temporary interference.
REST APIs do not employ as strict security measures as SOAP APIs, and therefore should not be used to send or retrieve sensitive information. However, good REST APIs still implement safety measures for secure and reliable data transfers.
 
Authentication and authorization : All requests to the API should be authenticated and authorized. Authentication is the process of verifying the identity of the client, and authorization is confirming that the client has permission to access the requested resources.

Validation : After authentication and authorization, requests still need to be scanned for potentially malicious code before the API gives access to its resources. Otherwise, a server will be vulnerable to an injection attack.

Encryption : TLS/SSL encryption secures the connection between client and server and prevents attackers from intercepting requests and responses.

Rate-limiting : Rate-limiting methods like quotas and throttling prevent brute-force attacks like DDoS that attempt to slow or crash the server.
No sensitive information in URIs: Protected information (e.g., username, password, or authentication token) should not be visible in the URI of a resource.
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 for 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.
A standard Cache-control header can help in attaining cache ability. Enlisted below is the brief description of the various cache-control header :
 
Public : Resources that are marked as the public can be cached by any intermediate components between the client and the server.

Private :
Resources that are marked as private can only be cached by the client.

No cache means that a particular resource cannot be cached and thus the whole process is stopped.
REST Web Socket
REST follows stateless architecture, meaning it won’t store any session-based data. Web Socket APIs follow the stateful protocol as it necessitates session-based data storage.
The mode of communication is uni-directional. At a time, only the server or the client will communicate. The communication is bi-directional, communication can be done by both client or server at a time.
REST is based on the Request-Response Model. Web Socket follows the full-duplex model.
Every request will have sections like header, title, body, URL, etc. Web sockets do not have any overhead and hence suited for real-time communication.
For every HTTP request, a new TCP connection is set up. There will be only one TCP connection and then the client and server can start communicating.
REST web services support both vertical and horizontal scaling. Web socket-based services only support vertical scaling.
REST depends on HTTP methods to get the response. Web Sockets depend on the IP address and port number of the system to get a response.
Communication is slower here. Message transmission happens very faster than REST API.
Memory/Buffers are not needed to store data here. Memory is required to store data.
Yes, we can. Transport Layer Security(TLS) does the task of encrypting the communication between the REST client and the server and provides the means to authenticate the server to the client. It is used for secure communication as it is the successor of the Secure Socket Layer (SSL). HTTPS works well with both TLS and SSL thereby making it effective while implementing RESTful web services. One point to mention here is, the REST inherits the property of the protocol it implements. So security measures are dependent on the protocol REST implements.
37 .
What is Payload in terms of RESTful web services?
Payload refers to the data passes in the request body. It is not the same as the request parameters. The payload can be sent only in POST methods as part of the request body.
38 .
What is the use of @RequestMapping?
Mapping web requests to specific classes or methods is made through @RequestMapping annotation. 
Theoretically, there is no restriction on the size of the payload that can be sent. But one must remember that the greater the size of the payload, the larger would be the bandwidth consumption and time taken to process the request that can impact the server performance.
In REST, every accessible piece of content on the server is labeled as a resource. A resource is an object with a type, associated data, a relationship with other resources on the server, and a list of methods that can be used with it. For example, a resource could be an HTML or text file, a data file, an image or video, or an executable code file.
 
A resource is identified with a uniform resource identifier, or URI. Clients access resources by including their URIs in HTTP requests.
URI stands for uniform resource identifier. In REST, a URI is a string that identifies a resource on a web server. Each resource has its own unique URI which, when included in an HTTP request, allows clients to target that resource and perform actions on it. The process of targeting a resource with its URI is called “addressing.”
 
The format of a URI is as follows :
<protocol>://<service-name>/<ResourceType>/<ResourceID>
 Here are some examples of REST APIs in use:
 
* To display weather information, weather apps harness public APIs that share weather data.

* Airlines expose their flight times and prices through APIs so travel and ticketing sites can use them.

* Public transportation services usually make their data publicly in real-time via APIs so that mapping and navigation apps (like Google Maps) can use them.

* Twitter allows publishing sites to pull information like tweets, users, tweet streams, and so on. Developers can also write programs to post tweets through the API instead of the website interface.
* In turn, Google Maps hosts several APIs that make its mapping data available to developers. Developers leverage these APIs to palace dynamic maps on their websites or in their apps.
Not forbidden, but it’s unusual to send a payload with GET and DELETE methods. There can be some client libraries that do not support the payload with these two methods. It’s also possible that some servers may just ignore the body of GET and DELETE methods. It’s better not to include payload with these two methods.
@Controller  @RestController
Mostly used traditional Spring MVC service.  Represents RESTful web service in Spring.
It is mostly used in Spring MVC service where model data needs to rendered using view. It is used in case of RESTful web service that returns object values bound to response body.
If response values need to be converted through HttpMessageConverters and sent via response object, extra annotation @ResponseBody needs to be used on the class or the method handlers. The default behavior of the @RestController needs to be written on the response body because it is the combination of @Controller and @ResponseBody.
@Controller provides control and flexibility over how the response needs to be sent. @RestController annotation has no such flexibility and writes all the results to the response body.
The URI template variables are bound to the handler method parameters of a controller using the @PathVariable annotation. Multiple @PathVariable can be used in the same method. In resource creation, the path variable plays a critical role. Spring MVC provides URL customization support for retrieval of data through the use of @PathVariable.