REST API Basic Interview Questions
REST API Basic Interview Questions
RESTful web services are services that follow REST architecture. REST stands for
Representational State Transfer and uses HTTP protocol (web protocol) for
implementation. These services are lightweight, provide maintainability, scalability,
support communication among multiple applications that are developed using
different programming languages. They provide means of accessing resources
present at server required for the client via the web browser by means of request
headers, request body, response body, status codes, etc.
• The REST Server provides access to these resources whereas the REST client
consumes (accesses and modifies) these resources. Every resource is
identified globally by means of a URI.
3. What is URI?
Uniform Resource Identifier is the full form of URI which is used for identifying
each resource of the REST architecture. URI is of the format:
<protocol>://<service-name>/<ResourceType>/<ResourceID>
Download PDF
The REST architecture is designed in such a way that the client state is not
maintained on the server. This is known as statelessness. The context is provided by
the client to the server using which the server processes the client’s request. The
session on the server is identified by the session identifier sent by the client.
6. What do you understand by JAX-RS?
As the name itself stands (JAX-RS= Java API for RESTful Web Services) is a Java-
based specification defined by JEE for the implementation of RESTful services. The
JAX-RS library makes usage of annotations from Java 5 onwards to simplify the
process of web services development. The latest version is 3.0 which was released
in June 2020. This specification also provides necessary support to create REST
clients.
These are the standard codes that refer to the predefined status of the task at the
server. Following are the status codes formats available:
• 200 - success/OK
• 201 - CREATED - used in POST or PUT methods.
• 304 - NOT MODIFIED - used in conditional GET requests to reduce the
bandwidth use of the network. Here, the body of the response sent should
be empty.
• 400 - BAD REQUEST - This can be due to validation errors or missing input
data.
• 401- UNAUTHORIZED - This is returned when there is no valid
authentication credentials sent along with the request.
• 403 - FORBIDDEN - sent when the user does not have access (or is
forbidden) to the resource.
• 404 - NOT FOUND - Resource method is not available.
• 500 - INTERNAL SERVER ERROR - server threw some exceptions while
running the method.
• 502 - BAD GATEWAY - Server was not able to get the response from
another upstream server.
HTTP Methods are also known as HTTP Verbs. They form a major portion of
uniform interface restriction followed by the REST that specifies what action has to
be followed to get the requested resource. Below are some examples of HTTP
Methods:
• GET: This is used for fetching details from the server and is basically a read-
only operation.
• POST: This method is used for the creation of new resources on the server.
• PUT: This method is used to update the old/existing resource on the server
or to replace the resource.
• DELETE: This method is used to delete the resource on the server.
• PATCH: This is used for modifying the resource on the server.
• OPTIONS: This fetches the list of supported options of resources present on
the server.
The POST, GET, PUT, DELETE corresponds to the create, read, update, delete
operations which are most commonly called CRUD Operations.
GET, HEAD, OPTIONS are safe and idempotent methods whereas PUT and DELETE
methods are only idempotent. POST and PATCH methods are neither safe nor
idempotent.
The technique of sending a message from the REST client to the REST server in the
form of an HTTP request and the server responding back with the response as
HTTP Response is called Messaging. The messages contained constitute the data
and the metadata about the message.
REST API Experienced Interview Questions
11. Differentiate between SOAP and REST?
SOAP REST
SOAP - Simple Object Access
REST - Representational State Transfer
Protocol
SOAP is a protocol used to REST is an architectural design pattern for
implement web services. developing web services
SOAP cannot use REST as it is a REST architecture can have SOAP protocol as
protocol. part of the implementation.
SOAP specifies standards that are REST defines standards but they need not be
meant to be followed strictly. strictly followed.
SOAP client is more tightly The REST client is more flexible like a browser
coupled to the server which is and does not depend on how the server is
similar to desktop applications developed unless it follows the protocols
having strict contracts. required for establishing communication.
SOAP REST
SOAP supports only XML
REST supports data of multiple formats like XML,
transmission between the client
JSON, MIME, Text, etc.
and the server.
SOAP reads are not cacheable. REST read requests can be cached.
SOAP uses service interfaces for
REST uses URI to expose the resource logic.
exposing the resource logic.
SOAP is slower. REST is faster.
Since SOAP is a protocol, it REST only inherits the security measures based
defines its own security measures. on what protocol it uses for the implementation.
SOAP is not commonly preferred,
REST is commonly preferred by developers these
but they are used in cases which
days as it provides more scalability and
require stateful data transfer and
maintainability.
more reliability.
12. While creating URI for web services, what are the best practices that
needs to be followed?
Below is the list of best practices that need to be considered with designing URI for
web services:
13. What are the best practices to develop RESTful web services?
RESTful web services use REST API as means of implementation using the HTTP
protocol. REST API is nothing but an application programming interface that follows
REST architectural constraints such as statelessness, cacheability, maintainability,
and scalability. It has become very popular among the developer community due to
its simplicity. Hence, it is very important to develop safe and secure REST APIs that
follow good conventions. Below are some best practices for developing REST APIs:
• Since REST supports multiple data formats, it is however good practice to
develop REST APIs that accept and responds with JSON data format
whenever possible. This is because a majority of the client and server
technologies have inbuilt support to read and parse JSON objects with ease,
thereby making JSON the standard object notation.
o To ensure that the application responds using JSON data format, the
response header should have Content-Type set to as application/JSON,
this is because certain HTTP clients look at the value of this response
header to parse the objects appropriately.
o To ensure that the request sends the data in JSON format, again the
Content-Type must be set to application/JSON on the request header.
• While naming the resource endpoints, ensure to use plural nouns and not
verbs. The API endpoints should be clear, brief, easy to understand, and
informative. Using verbs in the resource name doesn’t contribute much
information because an HTTP request already has what the request is doing
in its HTTP method/verb. An appropriate HTTP verb should be used to
represent the task of the API endpoint.
o Below are the most commonly used HTTP methods to define the verb:
§ GET - indicates get/retrieve the resource data
§ POST - indicates create new resource data
§ PUT - indicates update the existing resource data
§ DELETE - indicates remove the resource data
• To represent the hierarchy of resources, use the nesting in the naming
convention of the endpoints. In case, you want to retrieve data of one object
residing in another object, the endpoint should reflect this to communicate
what is happening. For example, to get the address of an author, we can use
the GET method for the URI /authors/:id/address'
o Please ensure there are no more than 2 or 3 levels of nesting as the
name of the URI can become too long and unwieldy.
• Error Handling should be done gracefully by returning appropriate error
codes the application has encountered. REST has defined standard HTTP
Status codes that can be sent along with the response based on the scenario.
o Error codes should also be accompanied by appropriate error
messages that can help the developers to take corrective actions.
However, the message should not be too elaborate as well which can
help the hacker to hack your application.
o Common status codes are:
§ 400 - Bad Request – client-side error - failed input validation.
§ 401 - Unauthorized – The user is not authenticated and hence
does not have authority to access the resource.
§ 403 - Forbidden – User is authenticated but is not authorized to
access the resource.
§ 404 - Not Found – The resource is not found.
§ 500 - Internal server error – This is a very generic server-side
error that is thrown when the server goes down. This shouldn’t
be returned by the programmer explicitly.
§ 502 - Bad Gateway – Server did not receive a valid response
from the upstream server.
§ 503 - Service Unavailable – Some unexpected things happened
on the server such as system failure, overload, etc.
• While retrieving huge resource data, it is advisable to include filtering and
pagination of the resources. This is because returning huge data all at once
can slow down the system and reduce the application performance. Hence,
filter some items reduces the data to some extent. Pagination of data is done
to ensure only some results are sent at a time. Doing this can increase the
server performance and reduce the burden of the server resources.
• Good security practices are a must while developing REST APIs. The client-
server communication must be private due to the nature of data sensitivity.
Hence, incorporating SSL/TLS becomes the most important step while
developing APIs as they facilitate establishing secure communication. SSL
certificates are easier to get and load on the server.
o Apart from the secure channels, we need to ensure that not everyone
should be able to access the resource. For example, normal users
should not access the data of admins or another user. Hence, role-
based access controls should be in place to make sure only the right
set of users can access the right set of data.
• Since REST supports the feature of caching, we can use this feature to cache
the data in order to improve the application performance. Caching is done to
avoid querying the database for a request repeated times. Caching makes
data retrieval fast. However, care must be taken to ensure that the cache has
updated data and not outdated ones. Frequent cache update measures need
to be incorporated. There are many cache providers like Redis that can assist
in caching.
• API Versioning: Versioning needs to be done in case we are planning to make
any changes with the existing endpoints. We do not want to break
communication between our application and the apps that consume our
application while we are working on the API release. The transition has to be
seamless. Semantic versioning can be followed. For example, 3.0.1 represents
3rd major version with the first patch. Usually, in the API endpoints, we
define /v1,/v2, etc at the beginning of the API path.
The meaning of idempotent is that even after calling a single request multiple times,
the outcome of the request should be the same. While designing REST APIs, we
need to keep in mind to develop idempotent APIs. This is because the consumers
can write client-side code which can result in duplicate requests intentionally or not.
Hence, fault-tolerant APIs need to be designed so that they do not result in
erroneous responses.
REST AJAX
REST- Representational State
AJAX - Asynchronous javascript and XML
Transfer
REST has a URI for accessing AJAX uses XMLHttpRequest object to send
resources by means of a request- requests to the server and the response is
response pattern. interpreted by the Javascript code dynamically.
REST is an architectural pattern for
AJAX is used for dynamic updation of UI without
developing client-server
the need to reload the page.
communication systems.
AJAX supports asynchronous requests thereby
REST requires the interaction
eliminating the necessity of constant client-
between client and server.
server interaction.
16. Can you tell what constitutes the core components of HTTP Request?
• Response Status Code − This represents the server response status code for
the requested resource. Example- 400 represents a client-side error, 200
represents a successful response.
• HTTP Version − Indicates the HTTP protocol version.
• Response Header − This part has the metadata of the response message.
Data can describe what is the content length, content type, response date,
what is server type, etc.
• Response Body − This part contains what is the actual resource/message
returned from the server.
18. Define Addressing in terms of RESTful Web Services.
<protocol>://<application-name>/<type-of-resource>/<id-of-resource>
19. What are the differences between PUT and POST in REST?
PUT POST
PUT methods are used to request the server to
POST method is used to
store the enclosed entity in request. In case, the
request the server to store the
request does not exist, then new resource has to be
enclosed entity in the request
created. If the resource exists, then the resource
as a new resource.
should get updated.
The POST URI should indicate
The URI should have a resource identifier.
the collection of the resource.
Example: PUT /users/{user-id}
Example: POST /users
POST methods are not
PUT methods are idempotent.
idempotent.
PUT is used when the client wants to modify a
POST methods are used to add
single resource that is part of the collection. If a part
a new resource to the
of the resource has to be updated, then PATCH
collection.
needs to be used.
Responses are not cacheable
The responses are not cached here despite the unless the response explicitly
idempotency. specifies Cache-Control fields
in the header.
POST is used for CREATE
In general, PUT is used for UPDATE operations.
operations.
20. What makes REST services to be easily scalable?
21. Based on what factors, you can decide which type of web services
you need to use - SOAP or REST?
REST services have gained popularity due to the nature of simplicity, scalability,
faster speed, improved performance, and multiple data format support. But, SOAP
has its own advantages too. Developers use SOAP where the services require
advanced security and reliability.
Following are the questions you need to ask to help you decide which service can
be used:
The request flow difference between the REST and Web Socket is shown below:
23. Can we implement transport layer security (TLS) in REST?
Yes, we can. 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.
24. Should we make the resources thread safe explicitly if they are made
to share across multiple clients?
There is no need to explicitly making the resources thread-safe because, upon every
request, new resource instances are created which makes them thread-safe by
default.
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.
No, the payload is not the same as the request parameters. Hence, it is not possible
to send payload data in these methods.
28. What is the maximum payload size that can be sent in POST methods?
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.
While implementing Basic Authentication as part of APIs, the user must provide the
username and password which is then concatenated by the browser in the form of
“username: password” and then perform base64 encoding on it. The encoded value
is then sent as the value for the “Authorization” header on every HTTP request from
the browser. Since the credentials are only encoded, it is advised to use this form
when requests are sent over HTTPS as they are not secure and can be intercepted
by anyone if secure protocols are not used.
30. What is the difference between idempotent and safe HTTP methods?
• Safe methods are those that do not change any resources internally. These
methods can be cached and can be retrieved without any effects on the
resource.
• Idempotent methods are those methods that do not change the responses to
the resources externally. They can be called multiple times without any
change in the responses.
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.
• 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
}
They are the runtime annotations in the JAX-RS library that are applied to Java
methods. They correspond to the HTTP request methods that the clients want to
make. They are @GET, @POST, @PUT, @DELETE, @HEAD.
Usage 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 {
@GET
public String getRESTQuestions() {
// some operations
}
}
JAX-RS applications have the root resource classes packaged in a war file. There are
2 means of configuring JAX-RS applications.
Yes. the JAX-RS Client API provides a method called Invocation.Builder.async() that is
used for constructing client requests that need to be executed asynchronously.
Invoking a request asynchronously does the task of returning the control to the
caller by returning with datatype java.util.concurrent.Future whose type is set to return
the service call type. Future objects are used because they have the required
methods to check whether the asynchronous calls have been completed and if yes,
then retrieve the responses. They also provide the flexibility to cancel the request
invocations and also check if the cancellation has been successful.
Let us understand this with the help of a random example. We know that
the Future interface from the java.util.concurrent has the below functions available:
package java.util.concurrent;
public interface Future<V> {
// informs the executor to stop the thread execution
boolean cancel(boolean mayInterruptIfRunning);
Let us consider we have this function below which is used for processing 2 Ids
parallelly.
In the above example, we see that there are 2 separate requests getting executed
parallelly. For the first future object, we await the javax.ws.rs.core.Response indefinitely
using the get() method until we get the response. For the second future object, we
wait for the response only for 2 seconds and if we do not get within 2 seconds, then
the get() method throws TimeoutException. We can also use the isDone() method or
isCancelled() method to find out whether the executors have completed or
cancelled.
36. List the key annotations that are present in the JAX-RS API?
• @Path - This specifies the relative URI path to the REST resource.
• @GET - This is a request method designator which is corresponding to the
HTTP GET requests. They process GET requests.
• @POST - This is a request method designator which is corresponding to the
HTTP POST requests. They process POST requests.
• @PUT - This is a request method designator which is corresponding to the
HTTP PUT requests. They process PUT requests.
• @DELETE - This is a request method designator which is corresponding to
the HTTP DELETE requests. They process DELETE requests.
• @HEAD - This is a request method designator which is corresponding to the
HTTP HEAD requests. They process HEAD requests.
• @PathParam - This is the URI path parameter that helps developers to
extract the parameters from the URI and use them in the resource
class/methods.
• @QueryParam - This is the URI query parameter that helps developers
extract the query parameters from the URI and use them in the resource
class/methods.
• @Produces - This specifies what MIME media types of the resource
representations are produced and sent to the client as a response.
• @Consumes - This specifies which MIME media types of the resource
representations are accepted or consumed by the server from the client.
The RestTemplate is the main class meant for the client-side access for Spring-
based RESTful services. The communication to the server is accomplished using the
REST constraints. This is similar to other template classes such as JdbcTemplate,
HibernateTemplate, etc provided by Spring. The RestTemplate provides high-level
implementation details for the HTTP Methods like GET, POST, PUT, etc, and gives
the methods to communicate using the URI template, URI path params,
request/response types, request object, etc as part of arguments.
39. What are the differences between the annotations @Controller and
@RestController?
@Controller @RestController
Represents RESTful web service in
Mostly used traditional Spring MVC service.
Spring.
@Controller @RestController
It is used in case of RESTful web
It is mostly used in Spring MVC service where
service that returns object values
model data needs to rendered using view.
bound to response body.
If response values need to be converted The default behavior of the
through HttpMessageConverters and sent via @RestController needs to be
response object, extra annotation written on the response body
@ResponseBody needs to be used on the class because it is the combination of
or the method handlers. @Controller and @ResponseBody.
@RestController annotation has no
@Controller provides control and flexibility
such flexibility and writes all the
over how the response needs to be sent.
results to the response body.
@PathVariable annotation is used for passing the parameter with the URL that is
required to get the data. Spring MVC provides support for URL customization for
data retrieval using @PathVariable annotation.
Yes. Spring MVC needs to be on the classpath of the application while developing
RESTful web services using Spring. This is because, the Spring MVC provides the
necessary annotations like @RestController, @RequestBody, @PathVariable, etc.
Hence the spring-mvc.jar needs to be on the classpath or the corresponding Maven
entry in the pom.xml.