Spring Framework
Building REST APIs with Spring MVC @RestController
Intermediate5 min readUpdated
Spring MVC serves JSON through the same DispatcherServlet that renders views, with message converters replacing view resolvers. This guide covers request and response mapping, status codes and headers with ResponseEntity, validation of bodies and parameters, consistent error responses with ProblemDetail, content negotiation and CORS, and the Spring 6.1 RestClient and HTTP interface clients for calling other APIs.
What you will learn
- Map JSON requests and responses with @RestController, @RequestBody and HttpMessageConverter
- Return correct status codes, Location headers and empty bodies with ResponseEntity
- Validate request bodies and query parameters and turn failures into 400 responses
- Produce consistent application/problem+json errors with ProblemDetail and @RestControllerAdvice
- Consume other REST APIs with RestClient and declarative HTTP interface clients
A REST API in Spring is Spring MVC with a different output stage: instead of resolving a view, the return value of a controller method is serialised straight into the response body by an HttpMessageConverter, and request bodies are deserialised the same way on the way in. Everything else — handler mapping, argument resolution, interceptors, exception resolvers — is shared with the view-rendering side. This guide targets Spring Framework 6.x with Jackson 2 for JSON and assumes you know how DispatcherServlet routes a request.
Mapping requests and responses
@RestController
@RequestMapping(path = "/api/products", produces = MediaType.APPLICATION_JSON_VALUE)
public class ProductController {
private final ProductService products;
public ProductController(ProductService products) {
this.products = products;
}
@GetMapping
public List<ProductResponse> list(@RequestParam(required = false) String category,
@RequestParam(defaultValue = "20") int limit) {
return products.list(category, limit).stream().map(ProductResponse::from).toList();
}
@GetMapping("/{id}")
public ProductResponse get(@PathVariable long id) {
return products.find(id).map(ProductResponse::from)
.orElseThrow(() -> new ProductNotFoundException(id));
}
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ProductResponse> create(@Valid @RequestBody CreateProductRequest request) {
Product created = products.create(request.name(), request.priceCents());
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}").buildAndExpand(created.id()).toUri();
return ResponseEntity.created(location).body(ProductResponse.from(created)); // 201 + Location
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable long id) {
products.delete(id);
}
}
public record CreateProductRequest(@NotBlank @Size(max = 120) String name,
@Positive long priceCents) {}
public record ProductResponse(long id, String name, long priceCents) {
static ProductResponse from(Product p) { return new ProductResponse(p.id(), p.name(), p.priceCents()); }
}
@RequestBody tells Spring to read the body through a converter chosen by the request's Content-Type; @RestController makes every return value go out through a converter chosen by the request's Accept header and the mapping's produces value. With Jackson on the classpath, MappingJackson2HttpMessageConverter handles application/json in both directions. Records are ideal request and response types: immutable, concise, and Jackson 2.12+ deserialises them through the canonical constructor without annotations.
Separate request, response and domain types deliberately. Serialising a JPA entity directly leaks internal fields, drags lazy associations into serialisation, and couples your API's shape to your database schema. Mapping code is boring, but it is where API compatibility is protected.
Status codes and headers with ResponseEntity
ResponseEntity<T> bundles status, headers and body. Its builders cover the common shapes:
| Situation | Code | Idiom |
|---|---|---|
| Resource created | 201 | ResponseEntity.created(location).body(dto) |
| Accepted for async processing | 202 | ResponseEntity.accepted().build() |
| Success with no body | 204 | ResponseEntity.noContent().build() or @ResponseStatus(NO_CONTENT) on void |
| Not modified (conditional GET) | 304 | ResponseEntity.ok().eTag(tag) plus WebRequest.checkNotModified(tag) |
| Client error with problem body | 4xx | ResponseEntity.status(HttpStatus.CONFLICT).body(problemDetail) |
Do not return ResponseEntity<Object> to sneak an error body past the type system; error responses belong in exception handlers, which keep controllers on the happy path.
Validation
@Valid on a @RequestBody parameter runs Jakarta Bean Validation on the deserialised object. Failure raises MethodArgumentNotValidException, which Spring maps to 400 by default. Since Spring Framework 6.1, constraints placed directly on @RequestParam, @PathVariable and @RequestHeader parameters — @Min(1) int page — are validated by Spring MVC itself, raising HandlerMethodValidationException, also a 400. Earlier versions required @Validated on the controller class and produced a ConstraintViolationException from the AOP method-validation proxy, which mapped to 500 unless you handled it; if you still see that pattern, it is legacy.
@GetMapping("/search")
public List<ProductResponse> search(@RequestParam @Size(min = 2, max = 50) String q,
@RequestParam(defaultValue = "1") @Min(1) int page) { … }
Bean Validation covers shape. Business rules — "SKU must be unique", "price cannot drop by more than 50 %" — belong in the service, where they throw a domain exception that an advice maps to 409 or 422.
Consistent error responses with ProblemDetail
Spring Framework 6.0 added first-class support for the problem-details format standardised in RFC 9457 (which obsoletes RFC 7807). A ProblemDetail object serialises as application/problem+json:
{
"type": "https://api.example.com/problems/product-not-found",
"title": "Product not found",
"status": 404,
"detail": "No product with id 42",
"instance": "/api/products/42",
"productId": 42
}
Wire it up in a @RestControllerAdvice. Extending ResponseEntityExceptionHandler makes Spring's own exceptions — malformed JSON, missing parameters, validation failures, unsupported media types — produce the same body shape:
@RestControllerAdvice
public class ApiExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(ProductNotFoundException.class)
ProblemDetail notFound(ProductNotFoundException ex) {
var problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Product not found");
problem.setType(URI.create("https://api.example.com/problems/product-not-found"));
problem.setProperty("productId", ex.id());
return problem; // Spring sets the status from the ProblemDetail
}
@ExceptionHandler(DuplicateSkuException.class)
ProblemDetail conflict(DuplicateSkuException ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, "SKU " + ex.sku() + " already exists");
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatusCode status, WebRequest request) {
var problem = ex.getBody(); // ProblemDetail prepared by Spring
problem.setProperty("errors", ex.getFieldErrors().stream()
.map(e -> Map.of("field", e.getField(), "message", String.valueOf(e.getDefaultMessage())))
.toList());
return handleExceptionInternal(ex, problem, headers, status, request);
}
}
Two alternatives exist for simple cases. Throwing ErrorResponseException (or a subclass) from anywhere carries a ProblemDetail with it, avoiding a handler. And Spring Boot 3 can enable problem-details rendering for the built-in exceptions with a single property. Whichever you pick, never let stack traces or internal class names reach the detail field; log those server-side with a correlation id and put the id in the body if support needs it. Pasting a response into the JSON formatter is a quick way to check the shape you are actually returning.
Content negotiation and CORS
The produces attribute and the client's Accept header select the response converter. Adding an XML converter (Jackson's XML module) lets the same controller serve application/xml on request; the default for a client that sends no Accept is the first producible type. Path-extension negotiation (/products.json) was switched off by default in Spring 5.3 and the underlying suffix-pattern matching was removed in 6.0, because it was a source of security issues — stick to headers, or enable a query parameter deliberately.
Browsers block cross-origin JavaScript calls unless the API opts in with CORS headers. Configure it in one place rather than per method:
@Configuration
public class ApiCorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("https://app.example.com")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowCredentials(true)
.maxAge(3600);
}
}
@CrossOrigin on a controller or method exists for exceptions. allowedOrigins("*") together with allowCredentials(true) is rejected by browsers and by Spring; use allowedOriginPatterns when you genuinely need a wildcard. When Spring Security is present, register the CORS configuration with it as well so preflight requests are not rejected before reaching MVC.
Calling other APIs: RestClient and HTTP interfaces
Spring Framework 6.1 introduced RestClient, a synchronous, fluent client that shares the converter infrastructure and works with any ClientHttpRequestFactory — the JDK HttpClient, Apache HttpClient 5, Reactor Netty or Jetty.
@Configuration
public class ClientConfig {
@Bean
RestClient inventoryClient(RestClient.Builder builder) { // Boot supplies the builder; else RestClient.builder()
return builder
.baseUrl("https://inventory.internal/api")
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.requestInterceptor((request, body, execution) -> {
request.getHeaders().setBearerAuth(Tokens.current());
return execution.execute(request, body);
})
.build();
}
}
@Service
public class InventoryGateway {
private final RestClient client;
public InventoryGateway(RestClient inventoryClient) { this.client = inventoryClient; }
public StockLevel stockFor(String sku) {
return client.get()
.uri("/stock/{sku}", sku)
.retrieve()
.onStatus(HttpStatusCode::is4xxClientError, (request, response) -> {
throw new UnknownSkuException(sku); // default would throw HttpClientErrorException
})
.body(StockLevel.class);
}
public void reserve(String sku, int quantity) {
client.post()
.uri("/reservations")
.contentType(MediaType.APPLICATION_JSON)
.body(new ReservationRequest(sku, quantity))
.retrieve()
.toBodilessEntity();
}
}
retrieve() throws RestClientResponseException subclasses for 4xx and 5xx unless onStatus overrides that; exchange() hands you the raw response when you need full control. Timeouts and connection pooling are properties of the request factory, not the client — set them there, always, because the JDK defaults are unbounded.
For clients with several operations, an HTTP interface removes the remaining boilerplate:
@HttpExchange("/api/stock")
public interface StockApi {
@GetExchange("/{sku}")
StockLevel get(@PathVariable String sku);
@PostExchange
ResponseEntity<Void> reserve(@RequestBody ReservationRequest request);
}
@Bean
StockApi stockApi(RestClient inventoryClient) {
return HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(inventoryClient))
.build()
.createClient(StockApi.class);
}
Spring generates a proxy that translates each call into an HTTP request using the annotations. The same interface can also be backed by WebClient for reactive applications. RestTemplate still works and is not deprecated, but it is the past; new code should use RestClient.
Common mistakes
Returning entities. Lazy associations trigger queries or LazyInitializationException during serialisation, bidirectional relationships recurse forever, and every schema change becomes an API change. Map to response records.
200 for everything. Returning {"error": "not found"} with status 200 breaks every client that checks status codes, including monitoring. Use the code that means what happened.
Catching exceptions in controllers. Each controller grows its own inconsistent error format. One @RestControllerAdvice gives every endpoint the same body.
Trusting @Valid for business rules. Uniqueness and state transitions need the service and the database; a constraint annotation cannot see other rows.
No timeouts on outbound calls. One slow dependency exhausts the request thread pool. Configure connect and read timeouts on the request factory of every RestClient.
CORS wildcard with credentials. Rejected by browsers; and allowing every origin to send cookies would be a serious vulnerability if it worked.
Path-extension content negotiation. Reflected file-download and content-sniffing attacks were the reason it was turned off; do not turn it back on.
Key takeaways
@RestControllerroutes return values throughHttpMessageConverters; Jackson handles JSON with no configuration.- Use dedicated request and response records, and
ResponseEntitywhen the status or headers carry meaning. @Validon bodies and constraint annotations on parameters give 400s for shape errors; business rules belong in the service.ProblemDetailwith a@RestControllerAdvicethat extendsResponseEntityExceptionHandlerproduces uniform RFC 9457 error bodies.- Configure CORS centrally and never combine a wildcard origin with credentials.
RestClient(6.1) and HTTP interface clients are the modern way to call other services; always set timeouts on the request factory.
Sources and further reading
Frequently asked questions
- What is the difference between @Controller and @RestController?
- @RestController is @Controller plus @ResponseBody at class level. Every handler's return value is written to the response body through a message converter instead of being interpreted as a view name. A @Controller can do the same per method by adding @ResponseBody, which is handy when one controller serves both pages and a few JSON endpoints.
- Should I return ResponseEntity from every endpoint?
- Only when you need to set the status or headers explicitly. A plain return type with an optional @ResponseStatus is shorter for the common 200 case, and Spring converts it identically. Use ResponseEntity for 201 Created with a Location header, 204 No Content, conditional responses and anything where the status depends on the outcome.
- Why does my API return an HTML error page instead of JSON?
- The exception escaped Spring MVC's resolvers and reached the servlet container's default error handling. Add a @RestControllerAdvice with an @ExceptionHandler for the exception (or a catch-all that returns ProblemDetail), or extend ResponseEntityExceptionHandler so Spring's own binding and conversion exceptions also produce problem+json bodies.
- Is RestTemplate deprecated?
- No, but it is in maintenance mode and receives no new features. Spring Framework 6.1 introduced RestClient, a synchronous fluent API with the same underlying HTTP client infrastructure, and it is the recommended choice for new code. RestTemplate remains supported, and RestClient.create(restTemplate) lets you migrate gradually while keeping existing interceptors and converters.