Spring MVC REST Controllers Interview Questions and Answers
Master Spring MVC REST Controllers with interview questions covering REST APIs, @RestController, REST principles, HTTP methods, ResponseEntity, content negotiation, HttpMessageConverter, RESTful URL design, HATEOAS, and production best practices.
Introduction
Modern enterprise applications rarely return HTML pages.
Instead, they expose REST APIs that communicate using JSON or XML.
Examples
- Banking Mobile Apps
- E-Commerce Websites
- Payment Gateways
- Insurance Platforms
- Healthcare Systems
- Microservices
Spring Boot makes building REST APIs simple through @RestController.
A REST Controller handles
- HTTP requests
- Request validation
- Business delegation
- JSON/XML responses
- HTTP status codes
REST Controller Architecture
flowchart LR
MobileApp --> DispatcherServlet
DispatcherServlet --> RestController
RestController --> Service
Service --> Repository
Repository --> Database
Service --> ResponseDTO
ResponseDTO --> JSON
JSON --> MobileApp
Q1. What is a REST Controller?
Answer
A REST Controller is a Spring component that exposes RESTful web services.
It returns
- JSON
- XML
instead of HTML pages.
Example
@RestController
@RequestMapping("/customers")
public class CustomerController {
}
Spring automatically serializes Java objects into JSON.
Q2. What is REST?
REST stands for
Representational State Transfer
It is an architectural style for designing web services.
REST principles
- Client-Server
- Stateless
- Cacheable
- Uniform Interface
- Layered Architecture
- Resource-Oriented
REST APIs communicate using HTTP.
Q3. What are REST Resources?
Everything in REST is treated as a resource.
Examples
Customer
Order
Payment
Account
Product
Resources are identified using URLs.
Example
/customers
/payments
/orders
Q4. Which HTTP methods are commonly used?
| Method | Operation |
|---|---|
| GET | Read |
| POST | Create |
| PUT | Update |
| PATCH | Partial Update |
| DELETE | Remove |
Example
@GetMapping("/{id}")
Choose methods according to REST semantics.
Q5. What is ResponseEntity?
ResponseEntity provides complete control over the HTTP response.
Example
return ResponseEntity
.ok(customer);
Capabilities
- Status code
- Headers
- Response body
Example
return ResponseEntity
.status(201)
.body(order);
Q6. What is Content Negotiation?
Clients specify the desired response format using the Accept header.
Example
Accept:
application/json
or
Accept:
application/xml
Spring selects the appropriate HttpMessageConverter.
Content Negotiation
flowchart LR
Client --> AcceptHeader
AcceptHeader --> DispatcherServlet
DispatcherServlet --> HttpMessageConverter
HttpMessageConverter --> JSONorXML
Q7. What is HttpMessageConverter?
It converts
Java Object
↓
JSON/XML
and vice versa.
Example
@RequestBody
@ResponseBody
Spring automatically invokes the correct converter.
Q8. What are RESTful URL Best Practices?
Good
/customers
/orders/101
/payments/500
Avoid
/getCustomer
/createOrder
/deletePayment
REST URLs should represent resources, not actions.
Q9. What is HATEOAS?
HATEOAS
Hypermedia As The Engine Of Application State
Responses include hyperlinks.
Example
{
"id":101,
"_links":{
"self":"/customers/101",
"orders":"/customers/101/orders"
}
}
Useful for discoverable APIs.
Q10. REST Controller Best Practices
Use DTOs
Never expose entities.
Return Proper Status Codes
Follow HTTP standards.
Validate Requests
Use Bean Validation.
Use Global Exception Handling
Return consistent errors.
Version APIs
Example
/api/v1/customers
Banking Example
flowchart TD
MobileApp --> PaymentRestController
PaymentRestController --> PaymentService
PaymentService --> PostgreSQL
PaymentService --> PaymentDTO
PaymentDTO --> JSON
JSON --> MobileApp
REST Controllers provide clean APIs for mobile and web applications.
Common Interview Questions
- What is a REST Controller?
- What is REST?
- What are REST resources?
- Explain HTTP methods.
- What is ResponseEntity?
- What is Content Negotiation?
- What is HttpMessageConverter?
- REST URL best practices?
- What is HATEOAS?
- REST Controller best practices?
Quick Revision
| Topic | Summary |
|---|---|
| REST Controller | Returns JSON/XML |
| REST | Resource-based architecture |
| Resource | Business entity |
| HTTP Methods | CRUD operations |
| ResponseEntity | Complete HTTP response |
| HttpMessageConverter | JSON/XML conversion |
| Content Negotiation | Select response format |
| DTO | API object |
| HATEOAS | Hypermedia links |
| API Versioning | /api/v1 |
REST API Lifecycle
sequenceDiagram
Client->>DispatcherServlet: HTTP Request
DispatcherServlet->>RestController: Invoke
RestController->>Validator: Validate
Validator-->>RestController: Success
RestController->>Service: Business Logic
Service->>Repository: Database
Repository-->>Service: Result
Service-->>RestController: DTO
RestController->>HttpMessageConverter: Serialize
HttpMessageConverter-->>Client: JSON Response
Production Example – Banking Fund Transfer REST API
A banking application exposes a REST endpoint for fund transfers.
API
POST /api/v1/payments
Request
{
"fromAccount": "10010001",
"toAccount": "20020002",
"amount": 5000
}
Workflow
-
Mobile application sends a POST request.
-
@RequestBodyconverts JSON intoPaymentRequest. -
Bean Validation validates the request.
-
PaymentRestControllerdelegates toPaymentService. -
Business logic:
- Balance validation.
- Fraud detection.
- Database transaction.
-
Service returns
PaymentResponseDTO. -
ResponseEntity.created()returns HTTP 201 Created.
@RestController
@RequestMapping("/api/v1/payments")
public class PaymentController {
@PostMapping
public ResponseEntity<PaymentResponse> transfer(
@Valid
@RequestBody PaymentRequest request){
PaymentResponse response =
paymentService.transfer(request);
return ResponseEntity
.status(201)
.body(response);
}
}
flowchart LR
MobileApp --> DispatcherServlet
DispatcherServlet --> PaymentRestController
PaymentRestController --> BeanValidation
BeanValidation --> PaymentService
PaymentService --> FraudService
PaymentService --> PostgreSQL
PaymentService --> PaymentResponseDTO
PaymentResponseDTO --> HttpMessageConverter
HttpMessageConverter --> JSON
JSON --> MobileApp
REST API Status Code Guidelines
| HTTP Status | Meaning | Typical Usage |
|---|---|---|
| 200 OK | Successful request | GET, PUT |
| 201 Created | Resource created | POST |
| 204 No Content | Successful with no body | DELETE |
| 400 Bad Request | Validation failure | Invalid input |
| 401 Unauthorized | Authentication required | Missing/invalid token |
| 403 Forbidden | Access denied | Insufficient permissions |
| 404 Not Found | Resource missing | Invalid ID |
| 409 Conflict | Duplicate resource | Existing account/order |
| 500 Internal Server Error | Unexpected server error | Unhandled exception |
REST API Design Guidelines
| Recommendation | Reason |
|---|---|
| Use plural resource names | /customers, /payments |
| Use nouns instead of verbs | REST models resources |
| Return DTOs | Avoid exposing entities |
| Use proper HTTP status codes | Standards compliance |
| Validate input | Prevent invalid requests |
| Version APIs | Backward compatibility |
| Document APIs with OpenAPI/Swagger | Easier integration |
| Secure endpoints with JWT/OAuth2 | Enterprise security |
Key Takeaways
@RestControlleris the preferred approach for building RESTful APIs in Spring Boot, automatically returning JSON or XML responses.- REST is a resource-oriented architectural style that relies on standard HTTP methods and stateless communication.
- ResponseEntity provides complete control over status codes, headers, and response bodies.
- HttpMessageConverters automatically serialize Java objects to JSON/XML and deserialize request bodies into Java objects.
- Content Negotiation enables clients to request different response formats using the
Acceptheader. - RESTful APIs should use resource-based URLs, meaningful HTTP status codes, and DTOs rather than exposing entities.
- API versioning, request validation, global exception handling, and standardized error responses are essential for enterprise-grade REST services.
- Following REST best practices results in scalable, maintainable, and secure APIs suitable for microservices and modern distributed systems.