Sub topic 13
Content Negotiation and Media Types
This chapter assumes you can write a @RestController, map methods with @GetMapping and @PostMapping, and read the Accept and Content-Type HTTP headers. Here you will see how Spring MVC picks the format of a response and how to restrict what an endpoint accepts and produces.
What content negotiation does
Content negotiation is the process where client and server agree on a representation of a resource, such as JSON or XML. Two headers drive it:
Acceptis sent by the client. It lists the media types the client can read, for exampleAccept: application/json.Content-Typedescribes the body that is being sent. A client sets it on a request, and the server sets it on a response.
A media type (also called a MIME type) is a label of the form type/subtype, such as application/json or text/plain. Spring exposes the common ones as constants on MediaType.
How Spring chooses a response format
After your method returns a value, Spring MVC looks for an HttpMessageConverter that can write that value as one of the media types the client accepts. With spring-boot-starter-web, Jackson is on the classpath, so JSON is available by default. XML is only available if you add an XML converter, such as jackson-dataformat-xml.
If the client sends no Accept header, or sends */*, Spring uses the first suitable type, which is JSON for a typical Boot application.
Restricting media types with `produces` and `consumes`
Mapping annotations accept two attributes that narrow a handler method:
produceslists the media types the method can return. It is matched againstAccept.consumeslists the media types the method can read. It is matched against the requestContent-Type.
import java.util.List;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
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("/api/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public List<BookResponse> list() {
return service.search("");
}
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public BookResponse create(@RequestBody CreateBookRequest request) {
return service.create(request);
}
}The two attributes fail differently:
| Mismatch | Status returned |
|---|---|
| `Accept` does not match `produces` | 406 Not Acceptable |
| `Content-Type` does not match `consumes` | 415 Unsupported Media Type |
A request with Content-Type: text/plain sent to the create method above receives 415 before your code runs.
Setting the type for one response
When you return ResponseEntity, you can set the Content-Type directly. This is useful when a single endpoint returns a type that differs from the rest of the controller:
@GetMapping(value = "/{id}/summary", produces = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<String> summary(@PathVariable long id) {
BookResponse book = service.get(id);
return ResponseEntity.ok()
.contentType(MediaType.TEXT_PLAIN)
.body(book.title() + " by " + book.author());
}Serving several formats from one method
Listing more than one type in produces lets the same method answer in either format. Spring picks the converter that fits the Accept header. This only works if a converter exists for each type. If you list application/xml without an XML converter on the classpath, requests for XML fail with a server error or a 406.
@GetMapping(value = "/{id}", produces = {
MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE })
public BookResponse get(@PathVariable long id) {
return service.get(id);
}Common errors
- Getting 406 on an endpoint you expect to work. Check that the client's
Acceptvalue is compatible withproduces, and that a converter for that type is installed. - Getting 415 on a POST. The client usually forgot
Content-Type: application/json. - Error responses ignoring your
produces. When an exception handler returns aProblemDetail, Spring usesapplication/problem+jsonfor it, which can conflict with a narrowAcceptheader.
Exercise
A client sends a POST with Content-Type: application/xml to a method declared with consumes = MediaType.APPLICATION_JSON_VALUE. Which status code does it get, and which attribute would produce a 406 instead?
Show answer
It gets 415 Unsupported Media Type, because the request Content-Type does not match consumes. A 406 Not Acceptable comes from the produces attribute, when the Accept header asks for a type the method cannot return.