Table of Contents
Introduction
REST APIs (Representational State Transfer Application Programming Interfaces) are a crucial part of modern web development, enabling seamless communication between different software systems. This guide will cover a wide range of REST API interview questions, with a particular focus on Java and Spring Boot, to help you prepare effectively.
General REST API Interview Questions
1. What is a REST API?
A REST API (Representational State Transfer API) is a set of web services that adhere to REST architectural principles, allowing systems to communicate over HTTP. REST APIs are stateless, cacheable, and support a uniform interface, which makes them scalable and easy to maintai
2. Explain the principles of REST.
The principles of REST includes:
- Stateless: Each request from a client contains all the information needed by the server to fulfill that request.
- Client-Server Architecture: Separates the client interface from the server functionality.
- Cacheable: Responses must define themselves as cacheable or not to improve performance.
- Uniform Interface: Simplifies and decouples the architecture, allowing each part to evolve independently.
- Layered System: A client cannot ordinarily tell whether it is connected directly to the end server or to an intermediary along the way.
- Code on Demand (optional): Servers can temporarily extend or customize the functionality of a client by transferring executable code.
3. What is the difference between REST and SOAP?
Feature | REST | SOAP |
---|---|---|
Architecture Style | Architectural style for distributed hypermedia systems | Protocol for exchanging structured information in web services |
Protocol | Uses HTTP protocol for communication | Uses its own protocol |
Data Format | Commonly uses JSON or XML for data exchange | Uses XML for message format |
Statelessness | Stateless; each request contains all necessary information | Can maintain state between requests |
Flexibility | Lightweight and flexible, suitable for mobile devices and web applications | More rigid, suitable for enterprise-level applications |
Protocol Overhead | Less overhead due to simpler message format | More overhead due to XML parsing and additional SOAP headers |
Security | Typically uses HTTPS and OAuth for security | Supports WS-Security for message integrity and confidentiality |
Error Handling | Standard HTTP error codes are used for error handling | Built-in error handling mechanisms |
Interoperability | Less interoperable between different platforms and languages | Highly interoperable between different platforms and languages |
4. What are the main HTTP methods used in REST?
- GET: Retrieve data from the server.
- POST: Submit data to the server.
- PUT: Update existing data on the server.
- DELETE: Remove data from the server.
- PATCH: Apply partial modifications to data.
5. What is an Idempotent HTTP method?
An idempotent HTTP method is one that can be called multiple times without producing different outcomes. For example, GET, PUT, and DELETE are idempotent, whereas POST is no.
6. What is RESTful Web Services?
RESTful web services are web services that adhere to the principles of REST (Representational State Transfer), an architectural style for designing networked applications. These services use HTTP methods (GET, POST, PUT, DELETE, etc.) to perform CRUD operations on resources, which are identified by URIs (Uniform Resource Identifiers). RESTful web services are stateless, meaning each request from a client must contain all the information the server needs to fulfill that request. This allows for greater scalability and simplicity.
7. What is a REST Resource?
A REST resource is an abstraction of information that can be addressed using a URI. Resources represent entities in a system, such as users, orders, or documents. Each resource is identified by a URI and interactions with the resource are performed using standard HTTP methods:
- GET: Retrieve a resource.
- POST: Create a new resource.
- PUT: Update an existing resource.
- DELETE: Remove a resource.
8. What is URI?
A URI (Uniform Resource Identifier) is a string that uniquely identifies a resource on the web. It consists of a scheme (such as HTTP or HTTPS), a host (domain), and a path that points to the resource.
Example:
http://example.com/api/users/1
In this URI:
http
is the scheme.example.com
is the host./api/users/1
is the path that identifies a specific user resource.
9. What is the concept of statelessness in REST?
Statelessness in REST means that each HTTP request from a client to the server must contain all the information needed to understand and process the request. The server does not store any session information about the client. Each request is independent and isolated from previous requests. This simplifies the server design and improves scalability since the server does not need to manage client state.
10. What are the best practices that need to be followed while creating URI for web services ?
Best practices for creating URIs for web services include:
- Use Nouns: URIs should represent resources and use nouns, not verbs. Example:
/users
rather than/getUsers
. - Consistency: Maintain a consistent naming convention, preferably using kebab-case or snake_case.
- Hierarchical Structure: Use a clear hierarchical structure to represent relationships. Example:
/users/1/orders/5
. - Pluralization: Use plural nouns for resource collections. Example:
/users
for a collection of user resources. - Avoid Special Characters: Avoid using special characters in URIs. Stick to alphanumeric characters and hyphens.
- Versioning: Include version numbers in URIs to manage different versions of the API. Example:
/v1/users
.
11. What are the best practices to develop RESTful web services?
Best practices to develop RESTful web services include:
- Use Proper HTTP Methods: Use GET, POST, PUT, DELETE appropriately for CRUD operations.
- Statelessness: Ensure the service is stateless and each request contains all necessary information.
- Use Standard HTTP Status Codes: Return appropriate status codes to indicate the result of the request.
- Resource Naming: Use meaningful, consistent resource names and avoid actions in URIs.
- Versioning: Implement versioning in your API to manage updates and changes.
- Security: Use HTTPS for secure communication and implement authentication and authorization (e.g., OAuth).
- Pagination: Implement pagination for endpoints returning large lists of resources.
- Error Handling: Provide meaningful error messages and use standard error codes.
- Documentation: Provide clear and comprehensive API documentation (e.g., using Swagger).
12. What are the differences between PUT and POST in REST?
Feature | PUT | POST |
---|---|---|
Purpose | Updates a resource or creates it if it does not exist | Creates a new resource |
Idempotent | Yes, making multiple identical requests will result in the same state | No, each request can result in a new resource creation |
Resource Location | Client specifies the URI of the resource | Server determines the URI of the newly created resource |
Request Body | Contains the complete representation of the resource to be created or updated | Contains the data for the new resource |
13. What are the differences between PUT and PATCH in REST?
Feature | PUT | PATCH |
---|---|---|
Purpose | Replaces the entire resource with the given data | Partially updates the resource with the given data |
Idempotent | Yes, making multiple identical requests will result in the same state | Generally, yes, but partial updates might not always be idempotent |
Request Body | Contains the complete representation of the resource | Contains only the fields to be updated |
14. What is the purpose of HTTP status codes in a REST API?
HTTP status codes provide information about the result of an HTTP request. They indicate whether the request was successful, resulted in an error, or required further actions. HTTP status codes are three-digit codes returned by the server to indicate the result of a client’s request. They are grouped into five categories:
- 1xx (Informational): Request received, continuing process.
- 100 Continue: The server has received the request headers and the client should proceed to send the request body.
- 2xx (Successful): The request was successfully received, understood, and accepted.
- 200 OK: The request succeeded.
- 201 Created: The request succeeded, and a new resource was created.
- 204 No Content: The request succeeded, but there is no content to send back.
- 3xx (Redirection): Further action needs to be taken by the user agent to fulfill the request.
- 301 Moved Permanently: The resource has been moved to a new URL permanently.
- 302 Found: The resource has been found at a different URL temporarily.
- 4xx (Client Error): The request contains bad syntax or cannot be fulfilled.
- 400 Bad Request: The server cannot process the request due to a client error.
- 401 Unauthorized: Authentication is required and has failed or not been provided.
- 403 Forbidden: The server understands the request but refuses to authorize it.
- 404 Not Found: The requested resource could not be found.
- 5xx (Server Error): The server failed to fulfill a valid request.
- 500 Internal Server Error: An error occurred on the server side.
- 502 Bad Gateway: The server received an invalid response from an upstream server.
- 503 Service Unavailable: The server is currently unavailable (overloaded or down).
15. What are the disadvantages of RESTful Webservices ?
Some disadvantages of RESTful web services include:
- Statelessness: While statelessness improves scalability, it requires that clients handle more state-related logic, which can increase complexity.
- Overhead of HTTP: Each request involves the overhead of HTTP, which may not be suitable for real-time applications requiring high performance.
- Lack of Standard: REST does not have a strict specification, leading to different interpretations and implementations.
- Limited Security: REST itself does not provide security features; they must be implemented separately (e.g., using HTTPS, OAuth).
- Complexity in Batch Processing: Performing batch operations can be complex and inefficient due to REST’s one-operation-per-request model.
Java REST API Interview Questions
1. How do you create a REST API in Java?
To create a REST API in Java, you typically use JAX-RS (Java API for RESTful Web Services). Here’s a basic example:
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/example")
public class ExampleResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getExample() {
return "Hello, REST API!";
}
}
The @Path
annotation defines the URI path for accessing this resource. The @GET
annotation indicates that this method will handle HTTP GET requests. The @Produces
annotation specifies that the method produces a plain text response.
2. Explain the usage of annotations in JAX-RS.
@Path
: Specifies the path at which the resource is accessible.@GET
,@POST
,@PUT
,@DELETE
: Define the HTTP methods.@Produces
: Specifies the MIME type of the response.@Consumes
: Specifies the MIME type of the request body.
3. How do you handle exceptions in JAX-RS?
You can handle exceptions in JAX-RS using @Provider
and ExceptionMapper
. Here’s an example:
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@Provider
public class GenericExceptionMapper implements ExceptionMapper<Throwable> {
@Override
public Response toResponse(Throwable exception) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(exception.getMessage())
.build();
}
}
The @Provider
annotation registers the ExceptionMapper
class, which converts exceptions into HTTP responses. This mapper catches all exceptions and returns a 500 Internal Server Error response with the exception’s message.
4. What is JAX-RS?
JAX-RS (Java API for RESTful Web Services) is a Java programming language API specification that provides support for creating web services according to the REST architectural pattern.
5. What are some popular JAX-RS implementations?
Some popular JAX-RS implementations include:
- Jersey: Reference implementation provided by Oracle.
- RESTEasy: Provided by JBoss.
- Apache CXF: An open-source services framework.
Spring Boot REST API Interview Questions
1. How do you create a REST API using Spring Boot?
Spring Boot simplifies the creation of RESTful APIs. Here’s a basic example:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/example")
public class ExampleController {
@GetMapping
public String getExample() {
return "Hello, Spring Boot REST API!";
}
}
The @RestController
annotation combines @Controller
and @ResponseBody
, indicating that this class handles REST requests and returns responses directly. The @RequestMapping
annotation maps HTTP requests to /example
, and @GetMapping
maps GET requests to the getExample
method.
2. What are the differences between the annotations @Controller and @RestController?
Feature | @Controller | @RestController |
---|---|---|
Purpose | Used to define web controllers in Spring MVC | Specialization of @Controller for REST APIs |
Return Type | Typically returns a view (HTML, JSP) | Returns data directly (e.g., JSON, XML) |
Additional Annotation | Requires @ResponseBody on each method to return data directly | Combines @Controller and @ResponseBody , so no need for @ResponseBody on each method |
3. What are the key annotations used in Spring Boot REST APIs?
@RestController
: Indicates that the class is a REST controller.@RequestMapping
: Maps HTTP requests to handler methods.@GetMapping
,@PostMapping
,@PutMapping
,@DeleteMapping
: Specialized versions of@RequestMapping
for specific HTTP methods.@RequestBody
: Binds the HTTP request body to a method parameter.@ResponseBody
: Binds the return value to the HTTP response body.@PathVariable
: Binds a method parameter to a URI template variable.@RequestParam
: Binds a method parameter to a query parameter.
4. How do you handle exceptions in Spring Boot REST APIs?
Spring Boot provides several ways to handle exceptions
- Controller-Based Exception Handling:
@RestController
@RequestMapping("/example")
public class ExampleController {
@GetMapping
public String getExample() {
if (true) { // Simulate an error
throw new ExampleException("Example error");
}
return "Hello, Spring Boot REST API!";
}
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ExampleException.class)
public class ExampleExceptionHandler {
@ExceptionHandler
public String handleExampleException(ExampleException e) {
return e.getMessage();
}
}
The @ExceptionHandler
annotation in the ExampleExceptionHandler
class indicates that this method handles ExampleException
. The @ResponseStatus
annotation sets the HTTP status code to 400 (Bad Request).
- Global Exception Handling with
@ControllerAdvice
:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ExampleException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleExampleException(ExampleException e) {
return e.getMessage();
}
}
The @ControllerAdvice
annotation allows defining a global exception handler that applies to all controllers in the application.
5. How do you document a Spring Boot REST API?
You can document a Spring Boot REST API using Swagger with Springfox. Here’s a simple setup:
- Add Dependencies:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
- Configure Swagger:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example"))
.paths(PathSelectors.any())
.build();
}
}
- Access the Documentation: Visit
http://localhost:8080/swagger-ui/
to see the API documentation.
Advanced Spring Boot REST API Interview Questions
1. How do you implement HATEOAS in Spring Boot?
HATEOAS (Hypermedia As The Engine Of Application State) is a constraint of the REST application architecture that keeps the RESTful interface dynamic and discoverable. In Spring Boot, you can implement HATEOAS using the spring-boot-starter-hateoas
dependency.
- Add Dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
- Implement HATEOAS:
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/example")
public class ExampleController {
@GetMapping
public EntityModel<String> getExample() {
String example = "Hello, Spring Boot HATEOAS!";
EntityModel<String> resource = EntityModel.of(example);
resource.add(WebMvcLinkBuilder.linkTo(WebMvcLinkBuilder.methodOn(ExampleController.class).getExample()).withSelfRel());
return resource;
}
}
Explanation: The EntityModel
class wraps the response and allows adding links to it. The WebMvcLinkBuilder
helps create these links dynamically.
2. How do you handle validation in Spring Boot REST APIs?
You can handle validation in Spring Boot REST APIs using the javax.validation
constraints along with @Valid
annotation.
- Add Dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
- Implement Validation:
import javax.validation.constraints.NotBlank;
public class ExampleRequest {
@NotBlank(message = "Name is mandatory")
private String name;
// getters and setters
}
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/example")
@Validated
public class ExampleController {
@PostMapping
public String createExample(@Valid @RequestBody ExampleRequest request) {
return "Received: " + request.getName();
}
}
The @NotBlank
annotation ensures that the name
field is not empty. The @Valid
annotation on the method parameter triggers the validation.
3. How do you implement pagination in a Spring Boot REST API?
Pagination in Spring Boot can be implemented using Pageable
from Spring Data.
- Add Dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
- Implement Pagination:
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Entity
public class ExampleEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// getters and setters
}
public interface ExampleRepository extends JpaRepository<ExampleEntity, Long> {
}
@RestController
@RequestMapping("/examples")
public class ExampleController {
private final ExampleRepository exampleRepository;
public ExampleController(ExampleRepository exampleRepository) {
this.exampleRepository = exampleRepository;
}
@GetMapping
public Page<ExampleEntity> getExamples(Pageable pageable) {
return exampleRepository.findAll(pageable);
}
}
The Pageable
parameter in the getExamples
method allows pagination by specifying the page number and size. The Page
object returned by the findAll
method contains the requested page of results.
4. How do you test a Spring Boot REST API?
You can test a Spring Boot REST API using Spring Boot’s @WebMvcTest
for controller layer testing and @SpringBootTest
for integration testing.
- Controller Layer Testing with
@WebMvcTest
:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(ExampleController.class)
public class ExampleControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testGetExample() throws Exception {
mockMvc.perform(get("/example"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, Spring Boot REST API!"));
}
}
The @WebMvcTest
annotation sets up a minimal context for testing web controllers. The MockMvc
object simulates HTTP requests and checks the results.
- Integration Testing with
@SpringBootTest
:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ExampleControllerIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void testGetExample() {
ResponseEntity<String> response = restTemplate.getForEntity("/example", String.class);
assertThat(response.getStatusCode().is2xxSuccessful()).isTrue();
assertThat(response.getBody()).isEqualTo("Hello, Spring Boot REST API!");
}
}
The @SpringBootTest
annotation loads the full application context, allowing for comprehensive integration testing. The TestRestTemplate
is used to perform HTTP requests and validate responses.
Additional Rest API Interview Questions
1. How do you implement security in a Spring Boot REST API?
You can implement security in a Spring Boot REST API using Spring Security
- Add Dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
- Configure Security:
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
The @EnableWebSecurity
annotation enables Spring Security’s web security support. The configure
method sets up basic authentication and authorizes requests based on their paths. The PasswordEncoder
bean defines the password encoding mechanism.
2. How do you handle cross-origin requests (CORS) in Spring Boot?
You can handle CORS in Spring Boot by using the @CrossOrigin
annotation or by configuring it globally.
- Using
@CrossOrigin
Annotation:
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/example")
public class ExampleController {
@CrossOrigin(origins = "http://example.com")
@GetMapping
public String getExample() {
return "Hello, Spring Boot REST API!";
}
}
The @CrossOrigin
annotation allows cross-origin requests from the specified origins.
- Global CORS Configuration:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.add
Mapping("/**").allowedOrigins("http://example.com");
}
}
The addCorsMappings
method in the WebMvcConfigurer
implementation configures global CORS settings.
3. How do you monitor and manage a Spring Boot application?
You can monitor and manage a Spring Boot application using Spring Boot Actuator.
- Add Dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- Configure Actuator:
management:
endpoints:
web:
exposure:
include: "*"
- Access Actuator Endpoints:
Actuator endpoints provide various metrics and health information. For example, you can accesshttp://localhost:8080/actuator/health
to check the application’s health status.
Spring Boot Actuator provides production-ready features such as monitoring and managing your application via HTTP endpoints.
Conclusion
Preparing for REST API interviews, especially those focusing on Java and Spring Boot, requires a solid understanding of REST principles, HTTP methods, status codes, and the ability to implement and secure APIs. By reviewing these questions and answers, you’ll be well-equipped to demonstrate your knowledge and skills during the interview process.
If you are preparing for Java interviews then checkout this.
Great job site admin! You have made it look so easy talking about that topic, providing your readers some vital information. I would love to see more helpful articles like this, so please keep posting!
rudaltoto rudaltoto rudaltoto
Really when someone doesn’t know after that its up to other users that they will assist, so
here it happens.
wdbos wdbos wdbos
These are actually great ideas in concerning blogging.
You have touched some good points here. Any way keep up wrinting.
magnificent put up, very informative. I ponder why
the other specialists of this sector don’t understand this.
You should continue your writing. I’m sure, you have a huge readers’ base already!
This post presents clear idea designed for the new people of blogging, that genuinely how to do blogging and site-building.
Simply wish to say your article is as amazing. The clarity in your submit is just excellent and that i could assume you
are a professional on this subject. Well together with your permission let me to grasp your feed to keep updated with approaching post.
Thank you one million and please keep up the gratifying work.
It’s going to be end of mine day, however
before ending I am reading this great article to increase my experience.
Hi there! Would you mind if I share your blog with my facebook group?
There’s a lot of folks that I think would really enjoy your content.
Please let me know. Thanks
Sure definitely.
This piece of writing offers clear idea in favor of the
new people of blogging, that actually how to do running a blog.
Excellent blog here! Also your site loads up
very fast! What web host are you using? Can I get your affiliate link to your host?
I wish my website loaded up as fast as yours lol
Sure will share.