Top 30 – REST API Interview Questions and Answers

REST API Interview Questions

Table of Contents

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.

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

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.
FeatureRESTSOAP
Architecture StyleArchitectural style for distributed hypermedia systemsProtocol for exchanging structured information in web services
ProtocolUses HTTP protocol for communicationUses its own protocol
Data FormatCommonly uses JSON or XML for data exchangeUses XML for message format
StatelessnessStateless; each request contains all necessary informationCan maintain state between requests
FlexibilityLightweight and flexible, suitable for mobile devices and web applicationsMore rigid, suitable for enterprise-level applications
Protocol OverheadLess overhead due to simpler message formatMore overhead due to XML parsing and additional SOAP headers
SecurityTypically uses HTTPS and OAuth for securitySupports WS-Security for message integrity and confidentiality
Error HandlingStandard HTTP error codes are used for error handlingBuilt-in error handling mechanisms
InteroperabilityLess interoperable between different platforms and languagesHighly interoperable between different platforms and languages
REST vs SOAP
  • 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.

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.

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.

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.

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.

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.

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.

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?

FeaturePUTPOST
PurposeUpdates a resource or creates it if it does not existCreates a new resource
IdempotentYes, making multiple identical requests will result in the same stateNo, each request can result in a new resource creation
Resource LocationClient specifies the URI of the resourceServer determines the URI of the newly created resource
Request BodyContains the complete representation of the resource to be created or updatedContains the data for the new resource
Difference between PUT and POST
FeaturePUTPATCH
PurposeReplaces the entire resource with the given dataPartially updates the resource with the given data
IdempotentYes, making multiple identical requests will result in the same stateGenerally, yes, but partial updates might not always be idempotent
Request BodyContains the complete representation of the resourceContains only the fields to be updated
PUT vs PATCH

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).

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.

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.

  • @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.

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.

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.

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 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.

Feature@Controller@RestController
PurposeUsed to define web controllers in Spring MVCSpecialization of @Controller for REST APIs
Return TypeTypically returns a view (HTML, JSP)Returns data directly (e.g., JSON, XML)
Additional AnnotationRequires @ResponseBody on each method to return data directlyCombines @Controller and @ResponseBody, so no need for @ResponseBody on each method
  • @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.

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.

You can document a Spring Boot REST API using Swagger with Springfox. Here’s a simple setup:

  1. Add Dependencies:
   <dependency>
       <groupId>io.springfox</groupId>
       <artifactId>springfox-boot-starter</artifactId>
       <version>3.0.0</version>
   </dependency>
  1. 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();
       }
   }
  1. Access the Documentation: Visit http://localhost:8080/swagger-ui/ to see the API documentation.

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.

  1. Add Dependency:
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-hateoas</artifactId>
   </dependency>
  1. 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.

You can handle validation in Spring Boot REST APIs using the javax.validation constraints along with @Valid annotation.

  1. Add Dependency:
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-validation</artifactId>
   </dependency>
  1. 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.

Pagination in Spring Boot can be implemented using Pageable from Spring Data.

  1. Add Dependency:
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-data-jpa</artifactId>
   </dependency>
  1. 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.

You can test a Spring Boot REST API using Spring Boot’s @WebMvcTest for controller layer testing and @SpringBootTest for integration testing.

  1. 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.

  1. 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.


You can implement security in a Spring Boot REST API using Spring Security

  1. Add Dependency:
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-security</artifactId>
   </dependency>
  1. 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.

You can handle CORS in Spring Boot by using the @CrossOrigin annotation or by configuring it globally.

  1. 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.

  1. 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.

You can monitor and manage a Spring Boot application using Spring Boot Actuator.

  1. Add Dependency:
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-actuator</artifactId>
   </dependency>
  1. Configure Actuator:
   management:
     endpoints:
       web:
         exposure:
           include: "*"
  1. Access Actuator Endpoints:
    Actuator endpoints provide various metrics and health information. For example, you can access http://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.


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.

Share this article with tech community
WhatsApp Group Join Now
Telegram Group Join Now

1 Comment

  1. 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!

Leave a Reply

Your email address will not be published. Required fields are marked *