Top Spring REST Interview Questions and Answers (2025) – Topic-Wise Guide

Preparing for a Spring REST interview? This topic-wise guide offers a comprehensive list of frequently asked questions along with clear and concise answers. Use this resource to solidify your knowledge and gain confidence before stepping into your next interview.

Basics of REST and Spring REST

1. What is REST, and how does it differ from SOAP?

REST (Representational State Transfer) is an architectural style for designing networked applications. It uses HTTP methods (GET, POST, PUT, DELETE) to perform operations on resources, which are identified by URIs. REST is lightweight and stateless, making it ideal for web services. SOAP (Simple Object Access Protocol), on the other hand, is a protocol that comes with extensive standards and is more suitable for complex, enterprise-level use cases.

2. What are the core principles of a RESTful API?

The core principles include:

  • Statelessness: Each request from a client contains all the information needed to process the request.
  • Resource Identification: Resources are identified using URIs.
  • Representation: Resources are represented in formats like JSON or XML.
  • Uniform Interface: Actions are performed using standard HTTP methods.

3. What is Spring REST?

Spring REST is a module within the Spring Framework designed to simplify the development of RESTful web services. It leverages Spring MVC and provides tools like annotations (@RestController, @RequestMapping, etc.), making the creation of REST APIs straightforward.

4. Can RESTful services maintain session state with clients?

No, RESTful services are stateless by design. If session state is necessary, it must be handled on the client side, typically using cookies or tokens like JWTs.

5. Why is REST stateless?

Statelessness ensures scalability by treating each request independently. This allows RESTful services to process requests efficiently without needing to store client context on the server.


Annotations in Spring REST

1. What is the purpose of @RestController?

@RestController is a Spring annotation that combines @Controller and @ResponseBody. It indicates that the class handles HTTP requests and automatically serializes return values to JSON or XML.

2. How does @RequestMapping work?

@RequestMapping maps HTTP requests to handler methods. For example:

@RequestMapping(value = "/books", method = RequestMethod.GET)
public List<Book> getBooks() {
    return bookService.findAll();
}

It can also map a request to a specific URI pattern or HTTP method.

3. What are the differences between @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping?

These annotations are shortcuts for @RequestMapping with specific HTTP methods:

  • @GetMapping: Handles GET requests.
  • @PostMapping: Handles POST requests.
  • @PutMapping: Handles PUT requests.
  • @DeleteMapping: Handles DELETE requests.

4. What is the use of @PathVariable and @RequestParam?

  • @PathVariable extracts values from the URI path: @GetMapping("/books/{id}") public Book getBook(@PathVariable int id) { return bookService.findById(id); }
  • @RequestParam extracts query parameters from the URL: @GetMapping("/books") public List<Book> getBooks(@RequestParam String category) { return bookService.findByCategory(category); }

5. How does @ResponseStatus work in a Spring REST application?

@ResponseStatus allows you to define a custom HTTP status code for a specific method or exception. For example:

@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {}

Request and Response Handling

1. How do you handle JSON and XML responses in Spring REST?

Spring provides HttpMessageConverters to automatically convert Java objects into JSON or XML, depending on the client’s request. Common converters include MappingJackson2HttpMessageConverter (for JSON) and Jaxb2RootElementHttpMessageConverter (for XML).

2. What is @RequestBody?

The @RequestBody annotation binds the HTTP request body to a Java object. For example:

@PostMapping("/books")
public void addBook(@RequestBody Book book) {
    bookService.save(book);
}

3. What is ResponseEntity, and how is it used?

ResponseEntity represents the entire HTTP response, including status code, headers, and body. It provides more flexibility:

return new ResponseEntity<>(book, HttpStatus.OK);

4. How do you set headers in a Spring REST response?

You can set headers using ResponseEntity or directly in the HttpServletResponse object:

HttpHeaders headers = new HttpHeaders();
headers.set("Header-Key", "Header-Value");
return new ResponseEntity<>(body, headers, HttpStatus.OK);

5. How to handle large response payloads?

To handle large payloads, consider using pagination or serving data in chunks by implementing something like server-side pagination and sending page numbers in request parameters.


Exception Handling in REST APIs

1. How do you handle exceptions in Spring REST?

You can handle exceptions globally with @ControllerAdvice and @ExceptionHandler. Example:

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<String> handleNotFound(ResourceNotFoundException ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
    }
}

2. What is the purpose of ResponseStatusException?

You can use ResponseStatusException to throw exceptions with a specific HTTP status and message:

throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Book not found");

3. Can you handle exceptions at the controller level?

Yes, with the @ExceptionHandler annotation placed inside the controller:

@ExceptionHandler(IOException.class)
public ResponseEntity<String> handleIOError(IOException ex) {
    return new ResponseEntity<>("Input/Output error occurred", HttpStatus.INTERNAL_SERVER_ERROR);
}

4. What is Spring Boot’s ErrorController, and when do you use it?

The ErrorController interface can be implemented to override custom error responses for an entire application.

5. How to return meaningful error messages in REST APIs?

Define standardized error responses with useful details like timestamp, status, message, and debugging information.

Validation and Data Binding

1. What is data binding in Spring REST?

Data binding is the process of mapping incoming HTTP request data (e.g., query parameters, form fields, JSON body) to Java objects. Spring automatically handles data binding with the help of annotations like @ModelAttribute and @RequestBody.

2. How do you validate request data in Spring REST?

Use Bean Validation (JSR-380) with annotations like @NotNull, @Size, and @Pattern. Combine this with the @Valid annotation in controller methods to trigger validations:

@PostMapping("/books")
public ResponseEntity<String> addBook(@Valid @RequestBody Book book) {
    return ResponseEntity.ok("Book added successfully");
}

3. How can you customize validation messages?

Custom validation messages can be defined in the messages.properties file:

size.book.title=Title must be between {min} and {max} characters.

Then link it to the validation annotation:

@Size(min = 2, max = 100, message = "{size.book.title}")
private String title;

4. What is @InitBinder, and when do you use it?

@InitBinder is used for pre-processing the binding of request parameters to controller method arguments. For example, it can apply formatters or bind custom objects:

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
}

5. How do you handle validation exceptions?

Use @ControllerAdvice and @ExceptionHandler to handle MethodArgumentNotValidException or similar globally:

@ControllerAdvice
public class ValidationExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<String> handleValidationError(MethodArgumentNotValidException ex) {
        return new ResponseEntity<>("Validation error occurred", HttpStatus.BAD_REQUEST);
    }
}

Content Negotiation

1. What is content negotiation in REST APIs?

Content negotiation ensures that the server returns data in a format preferred by the client (e.g., JSON, XML). This is achieved using the Accept header in HTTP requests.

2. How is content negotiation implemented in Spring REST?

Spring manages content negotiation through the ContentNegotiationManager. It determines the format based on:

  • Accept headers
  • File extensions in the URL (e.g., /books.json)
  • Query parameters (e.g., ?format=json)

3. What is the role of HttpMessageConverters in content negotiation?

HttpMessageConverters read and write HTTP requests and responses in supported formats (e.g., JSON, XML). For example, MappingJackson2HttpMessageConverter handles JSON conversion.

4. How do you configure content negotiation in Spring Boot?

You can configure it in application.properties:

spring.mvc.contentnegotiation.favor-parameter=true
spring.mvc.contentnegotiation.favor-path-extension=false
spring.mvc.contentnegotiation.media-types.json=application/json
spring.mvc.contentnegotiation.media-types.xml=application/xml

5. How do you handle unsupported media types?

Return a 415 Unsupported Media Type response manually or configure a global handler.



Security in REST APIs

1. How do you secure REST APIs in Spring?

Use Spring Security to secure REST endpoints. Implement:

  • Authentication (e.g., via OAuth, JWT).
  • Authorization with roles and permissions.
  • HTTPS to encrypt communication.
  • CSRF protection for sensitive operations.

2. How does Spring Security help protect REST APIs?

Spring Security integrates filters to handle authentication and authorization. Common tools include BasicAuthenticationFilter and JwtAuthenticationFilter.

3. What is OAuth, and how is it implemented in Spring Boot?

OAuth is an authentication protocol used for secure access delegation. Spring Security OAuth2 provides easy integration with OAuth providers. Example:

spring.security.oauth2.client.registration.google.client-id=xxx
spring.security.oauth2.client.registration.google.client-secret=xxx

4. How do you implement JWT-based authentication in Spring REST?

Use the io.jsonwebtoken library to generate and validate tokens. Secure APIs by validating JWT in filters.

5. What is CORS, and how do you enable it in Spring REST?

CORS (Cross-Origin Resource Sharing) restricts resource sharing across domains. Enable it using @CrossOrigin or configuring a filter:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("http://example.com");
        }
    };
}

Pagination, Filtering, and Sorting

1. Why is pagination important in REST APIs?

Pagination optimizes performance by returning smaller data chunks instead of the complete dataset, improving load times for large resources.

2. How is pagination implemented in Spring REST?

Use Pageable and Page from Spring Data:

@GetMapping("/books")
public Page<Book> getBooks(Pageable pageable) {
    return bookRepository.findAll(pageable);
}

3. How do you enable sorting in Spring REST?

Sorting is integrated with Pageable. You can specify fields:

/books?page=0&size=10&sort=title,desc<br>

4. Can filtering be combined with pagination and sorting?

Yes, specify filtering criteria along with pagination/sorting parameters:

@GetMapping("/books")
public Page<Book> getFilteredBooks(Pageable pageable, @RequestParam String category) {
    return bookRepository.findByCategory(category, pageable);
}

5. How do you handle dynamic filtering?

Use a Specification or Criteria queries for flexible query building based on client inputs.


Testing REST APIs

1. What are the common tools for testing Spring REST APIs?

Tools include Postman, Swagger, and cURL for manual testing, and JUnit with MockMVC for automated testing.

2. How do you test REST controllers in Spring?

Use Spring’s MockMvc to test web layers:

@Test
void testGetBooks() throws Exception {
    mockMvc.perform(get("/books"))
        .andExpect(status().isOk())
        .andExpect(content().json("[{title:'Book1'}, {title:'Book2'}]"));
}

3. How do you test secured APIs?

Mock the security context or use predefined authentication tokens:

@Test
@WithMockUser(roles = "USER")
void testSecureEndpoint() throws Exception {
    mockMvc.perform(get("/secure"))
        .andExpect(status().isOk());
}

4. What is the role of integration testing in REST APIs?

Integration testing ensures all system components (database, services, controllers) work together as expected.

5. How do you generate API documentation for testing?

Use tools like Swagger or Spring REST Docs to create dynamic, interactive documentation.


This concludes the detailed topic-wise guide for Spring REST interview questions. Prepare confidently and ace your next interview!

Similar Posts

Leave a Reply

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