Table of Contents
Introduction
In this REST Interview Questions blog post we will go over some of the frequently asked Spring and REST interview questions to Java and Spring framework developers. REST has become one of the most important topic when it comes to being an experienced Java developer. As Spring came up with newer versions it kept on adding new features when it comes to RESTful communication. Please visit my article on Spring Boot 3 and Spring framework 6 features.
What are web services?
To explain web services in layman terms we can take an example of English language. As we know most of the countries have their own language which other countries can’t understand. So In this case they make use of English as the common language and this is a widely used language to bridge the gap between countries.
In the similar way we have web services in the IT world where different languages and platforms can communicate with one another. E.g. Java applications can communicate with .NET or Angular applications can communicate with Java applications.
In web services we have two parties, one is the service provider who provides the data/services and another is the service consumer who gets the required data/services.
There are two types of web services, SOAP & RESTful web services. The communication between both parties is via http protocol. In SOAP the data exchange format is XML and in RESTful it uses multiple data formats E.g. JSON, Text etc.
What is REST?
REST stands for representational state transfer. HTTP is there for quite some time now and almost all the websites use it. Roy Fielding did research on how HTTP can be used for other types of applications and that’s where RESTful services was born.
HTTP has various methods such as GET, POST, PUT, DELETE which we can use to perform an operation against a URL/URI. You can relate it to the CRUD (Create, Read, Update and Delete) operations you perform against the database which are very common in all the applications and across the industry.
The data exchange between service provider and service consumer can be in JSON, XML or any other format which makes RESTful services Interoperable.
What do you mean by REST is stateless
Statelessness is one of the biggest advantages of REST. Statelessness does not mean that it does not have state at all, but it exchanges the representational state between applications. The state is maintained at the client side instead of maintaining it at the server side.
It should not rely on previous or next requests or some data maintained at the server end, like sessions.
What are the different HTTP methods present in REST
Some of the commonly used HTTP methods are as below.
GET : This is used to fetch/get data from the server.
POST : This is used to create a new resource.
PUT : This is used to modify a resource
DELETE: This is used to delete a resource
What are safe REST operations?
HTTP methods which don’t modify any resource can be considered as the safe REST operations. GET and HEAD HTTP methods are safe REST operations. PUT, POST and DELETE are not safe because modify the resource on the server.
What is a resource in REST
Everything that we access is called a resource. Each resource has something called as identifier which is called as URI (uniform resource identifier)
E.g. Below a
/employees/1 – URI for accessing an employee resource with id 1.
/employees – URI for accessing all the employees
And the action that we perform on resource is using the HTTP methods i.e. GET, POST, PUT, DELETE. We will see the meaning of each HTTP method in the questions below.
What is Idempotency in REST APIs
Idempotency is when the HTTP methods or the HTTP call, produce the same response no matter how many times you perform make the operation. GET is idempotent because it produces the same response whenever you send multiple GET request. PUT operation is also idempotent because when you update a resource on the server it will give the same end result. If you talk about POST http method, it is not idempotent because if you send multiple POST requests, it will result in multiple resource creation on the server.
Is REST scalable and/or interoperable
Yes REST is scalable as well as interoperable. You can use any technologies like Java, Python, Javascript etc. to create RESTful web services and consume them from the client end which is implemented using different technology.
What is the difference between POST and PUT
POST is used to create a new resource and PUT is used to update an existing resource.
Can we send payload in GET and DELETE methods?
No. It is not possible to send payload data in these methods.
What do you mean by a resource in REST
In Object oriented programming we have objects, Similarly we have resources in REST. Operations are performed against a resource. Resources can be in XML or JSON representation.
Mention some of the implementations of REST
Some of the common implementations used to implement REST web services are Apache CXF, Jersey, REST Easy & Spring REST. Spring REST is used most widely today.
What are the tools used to test the REST web services
There are 2 parts to REST web services, one is service consumer and another is service provider. Let’s say you are a service provider and your service is invoked by multiple consumers. Before releasing/deploying your final code you have to test it properly using some standalone tools. Two of the very common tools are Postman & SOAP UI.
What does a REST request consist of
REST request consists of request headers and request body. Mandatoriness of both depends on your business logic.
Name some of the HTTP response codes
200 – OK
Operation successful
400 – BAD REQUEST
For missing Mandatory headers or any other parameter
404 – NOT FOUND
If a particular URI is not present or wrong.
405 – METHOD NOT ALLOWED
If URI has a different http method and if the invoking http method is different. E.g. if /getEmployee has a GET http method and if you are invoking the endpoint with POST http method.
401 – UNAUTHORIZED
If the user is not authenticated properly then we return 401
403 – FORBIDDEN
If the user is authenticated but he does not have rights to access the resource.
500 – INTERNAL SERVER ERROR
If for some reason the server is down.
502 – BAD GATEWAY
Server was unable to get response from the upstream server
What is the HTTP status return code for a successful DELETE statement?
If the DELETE operation is successful and the response body is empty then we get 204 response code. But if the DELETE request is successful and the response body is NOT empty, return 200.
What are the spring annotations used for HTTP methods.
@GetMapping – To fetch a resource
@PostMapping – To create a new resource
@PutMapping – To update an existing resource
@DeleteMapping – To delete a resource
What is @RestController?
@RestController = @Controller + @ResponseBody
This annotation is the combination of 2 annotations. By adding this we don’t need to explicitly add @ResponseBody annotation. The class annotated with @RestController has REST endpoint methods exposed so that other services can consume.
What is the difference between @Controller and @RestController
The main difference between @Controller and @RestController is that, you get @ResponseBody along with @RestController, whereas you have separately annotate your handler methods with @ResponseBody annotation with it comes to @Controller annotation.
What is RestTemplate and why do we use it?
If you want to consume a RESTful service, then you can make use of RestTemplate. We use the exchange() method to invoke the service.
restTemplate.exchange("http://localhost:8081/employees", HttpMethod.GET, entity, Employee.class).getBody();
First parameter to the exchange method is the URI, second parameter is the HTTP method i.e. GET, POST, PUT or DELETE, third parameter is the entity which consists of headers & body or just header/body and fourth parameter containing the return type of the response that the service will return.
What is ResponseEntity?
Being a RESTful service provider if we want to return a response body that contains Data as well as the response code then we make use of ResponseEntity
E.g. Let’s say we have a URI or a method getEmployee which returns an Employee object. Along with the Employee object we want to return a response code say 200, then we would return as
Employee employee = new Employee(1451,”John”,”Software Engineer”)
return new ResponseEntity<>(employee, HttpStatus.OK);
@RequestHeader OR @RequestHeaders annotation
Both the annotations are used to receive values from the request headers.
-> @RequestHeader annotation is used to get each header one by one whatever is required.
@PostMapping(path = "/employee", consumes = "application/json", produces = "application/json")
public void addEmployee(@RequestHeader(“channel”) String channelName,
@RequestHeader(“uuid”) String uuid,
@RequestHeader(“sessionId”) String sessionId,
@RequestBody Employee employee) {
//Business logic here
}
@RequestHeaders are used to get all the headers into one object. This can be used when there are too many headers and you want all instead of fetching it one by one.
@PostMapping(path = "/employee", consumes = "application/json", produces = "application/json")
public void addEmployee(@RequestHeader HttpHeaders headers,
@RequestBody Employee employee) {
//Business logic here
}
What is the usage of @PathVariable
@PathVariable annotation is used to read the value from the URI.
Example – Lets say you want to fetch the student with ID as 213. The URI looks like http://studentmgmt.com/v1/students/213. If you want to fetch the student id i.e. 213 from the URI, in your code, then you need to make use of @PathVariable.
@GetMapping(value = "/v1/students/{studentId}", produces = "application/json)
public StudentResponse get(
@PathVariable("studentId")
String studentId) {
//your code here
}
What do you mean by Accept and Content-Type header
Both are keys that are present in the headers sent from the client (E.g. browsers) to the service
Accept : It contains the value which specifies what response format the client is expecting. E.g. application/json
Content-Type : It contains the value which specifies which format of the data sent to the service
Produces and consumes in REST
Produces specifies the MIME media type that is sent to the client and Consumes specifies the MIME media type that is accepted or consumed from the client.
E.g. The consumer of the below service has to send the request in the JSON format.
@PostMapping(path = "/employee", consumes = "application/json", produces = "application/json")
public void addEmployee(@RequestBody Employee employee) {
//Business logic here
}
What are the best practices in developing RESTful services?
As we know, there are two parties involved in REST communication. Service consumer and Service provider. Service provider is the one who has exposed the web service and consumers are the one who are accessing the web service.
- Correct HTTP Method Usage : We need to make the best use of HTTP methods, make semantic use of methods properly. E.g. If you are providing data to the consumer then use HTTP GET, if you are creating a new resource then make use of HTTP POST.
- JSON data response : Accepting and responding in JSON format is advisable when working with REST 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.
- Correct HTTP Response code : Also make the best use of HTTP Response codes. E.g. If the operation is successful send a 200 response. If the request format is not proper or some of the header is missing we need to send a 400 response. I did see some developers sending 500 Internal Server which is wrong. We need to send the correct response codes
- URI naming convention : While designing the URIs, make use of plural forms. For example
/emloyees/123 – CORRECT
/employee/123 – WRONG - Handling huge data: Make use of Pagination when the response is huge. This is avoid system slow down and increase application performance.
- Security: Make use of SSL/TLS to facilitate secure communication when it comes to data transfer. Also role-based access should be implemented so that data on the server is accessed by authorized user.
- Caching: In order to increase the application performance, caching should technologies such as Redis should be used. Caching avoids frequent database querying. In case you implement caching, care must be taken to ensure that the cache has updated data and not outdated ones. Frequent cache update measures need to be incorporated.
- API Versioning: API endpoint should start with versions i.e. /v1. Because in future if there is a major change to the functionality, then we can create a new endpoint with version /v2 in order to support new requirements as well as service the old endpoint and functionality.
What are the best practices that needs to be followed while creating URI for web services
- Using plural nouns. Example: to find the employees, use the name “employees” for that resource.
- uri should be in lower case.
- No need to use verbs like getEmployee in the uri, because http method GET itself says that we are fetching the resource. Example: use /employees instead of /getEmployees
- Use hyphen or underscore in case url contains long names. Avoid using spaces.
What are HttpMessageConverters in Spring REST and why does it return JSON format by default?
HttpMessageConverters are used to convert the object to JSON/XML and vice versa. While developing REST web services in Spring Boot, the default data format that is being returned in JSON. This is because it registers the default MessageConvertor i.e. Jackson.
Each HttpMessageConverter implementation has one or several MIME Types associated with it. Spring uses the “Accept” header to determine the content type the client is expecting.
How to add XML support for our endpoint?
As we know that JSON is the default data format that REST service returns, the question is how do we send the response in XML format if the client requests it. If we are using Spring boot then we need to add below dependency.
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
What is Swagger in the REST web services world?
As per the Open API/Swagger specification “The OpenAPI Specification (OAS) defines a standard, language-agnostic interface to RESTful APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection”
Swagger is a document or contract which is either .yml or .json format which has below details
-The list of endpoints present in our service and their respective HTTP method.
-Header that we need to pass to the consumer.
-The data definition i.e. request body that a service consumer needs to send, and in return what the endpoint/service provider will return.
-Http Response code being returned for different scenarios.
Usually the service provider will prepare the document and share it with one or more service consumers, so that both parties work independently based on the agreed contract. Sometimes service providers & service consumers will discuss together to design the final contract/swagger file.
How to secure REST APIs
REST APIs can be secured using Spring security or using any OAuth provider such as keycloak server.
Can we use TLS (Transport layer security) with REST
TLS is the successor of SSL which is used for secure communication between the client and the server. REST can work with both SSL and TLS.
What is the difference between REST and Web socket
REST | Web socket |
---|---|
Rest is based on Request Response model. | Web socket is based on full duplex model. |
A request in REST consists of Header, Body, URL etc. | Web socket does not have any additional components like REST. |
A new TCP connection is setup for every new HTTP request. | There will be only one TCP connection and the client server will start communicating. |
REST supporting both vertical and horizontal scaling. | Web socket support vertical scaling. |
REST is stateless in nature. | Web socket APIs are stateful as it requires session based data storage. |
Communication in REST is slower as compared to web sockets. | Communication in Web socket is faster than REST. |
Memory is not needed to store the data. | Memory is needed to store the data. |
Is it possible to implement Transport layer security (TLS) in REST?
Yes we can implement TLS in REST. TLS is used for encrypting the communication between the REST client and the server. It is used for secure communication.
Conclusion
We tried to gather as many questions as possible which are asked in Spring REST interview sessions. Let us know through comments or email if you think we need to add any question which is more frequently asked and that is not included in this post. Happy Learning 🙂
Heya terrific blog! Ⅾoes running a blog ѕimilar tο this require a
massive amount ԝork? I havе no knowledge of programming ƅut
I hаd been hoping to start my own blog ѕoon. Anywаy,
if you haѵe any suggestions or tips f᧐r neѡ blog
owners please share. I understand thіs іs off topic ƅut Ι just wanted
tо аsk. Thankѕ!