Sub topic 13
Content negotiation and media types
This chapter assumes you can write a @RestController with @GetMapping and @PostMapping methods, and that you know the Accept and Content-Type headers. It builds on the BookController, BookResponse and CreateBookRequest types from earlier chapters.
What content negotiation does
One URL can have more than one representation. A client may want JSON, XML or a custom format. Content negotiation is the process in which the client says what it can read and the server picks a format it can write.
Two headers drive it:
Acceptis sent by the client. It lists the media types the client can handle for the response.Content-Typedescribes the body that is being sent. A client sets it on a request body. The server sets it on a response.
A media type, also called a MIME type, has the form type/subtype, such as application/json. A suffix such as +json says the format is built on JSON. application/problem+json, the type used by ProblemDetail, follows this pattern.
How Spring MVC picks a format
Spring MVC does not turn objects into JSON itself. It delegates to HttpMessageConverter objects. Each converter knows which Java types it can read or write and which media types it supports.
Spring Boot registers the converters that match your classpath. With spring-boot-starter-web, you get these:
- A Jackson converter for JSON.
- A String converter for
text/plain. - A converter for
byte[]and a few others.
When a controller method returns an object, Spring follows these steps:
- Collect the media types the client accepts from the
Acceptheader, sorted by quality value (q). - Collect the media types the handler can produce. These come from
produceson the mapping, or from the registered converters ifproducesis absent. - Find the first acceptable type that is also producible.
- Pick a converter that can write the return type as that media type and set
Content-Typeon the response.
A missing Accept header, or Accept: */*, means the client takes anything. Spring then uses the first compatible converter. For a record or POJO on a standard Boot setup, that is JSON.
Declaring what a method produces and consumes
Use produces to restrict the response formats and consumes to restrict the request body formats. Both are attributes of the mapping annotations.
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(value = "/api/books", produces = MediaType.APPLICATION_JSON_VALUE)
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
@GetMapping("/{id}")
public BookResponse get(@PathVariable long id) {
return service.get(id);
}
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public BookResponse create(@RequestBody CreateBookRequest request) {
return service.create(request);
}
}Here every method on the class only produces JSON, and create only accepts a JSON body. The *_VALUE constants are String values, which annotation attributes require. The plain MediaType.APPLICATION_JSON constants are MediaType objects and do not compile in annotations.
produces and consumes also act as mapping conditions. They take part in choosing which method handles a request, as the path and HTTP method do. This lets two methods share a path and differ only in media type.
Errors: 406 and 415
Two status codes tell the client that the formats do not match. Clients mix them up often, so keep them apart.
| Situation | Status | Spring exception |
|---|---|---|
| No producible type matches `Accept` | 406 Not Acceptable | `HttpMediaTypeNotAcceptableException` |
| Request `Content-Type` is not in `consumes` | 415 Unsupported Media Type | `HttpMediaTypeNotSupportedException` |
| Body is declared as JSON but is malformed | 400 Bad Request | `HttpMessageNotReadableException` |
With spring.mvc.problemdetails.enabled=true, all three come back as ProblemDetail bodies. You do not need to write handlers for them.
A common mistake is a POST with no Content-Type header. With @RequestBody, Spring treats the content type as application/octet-stream. No converter reads that type into your DTO, so the client gets 415. In curl, -d sets application/x-www-form-urlencoded unless you add a header:
curl -i -X POST http://localhost:8080/api/books \
-H "Content-Type: application/json" \
-d '{"title":"Dune","author":"Frank Herbert"}'Quality values and several acceptable types
A client can rank formats with q values between 0 and 1. The default is 1.
curl -i http://localhost:8080/api/books/1 \
-H "Accept: application/xml;q=0.9, application/json;q=0.5"This asks for XML first and JSON as a fallback. If the method produces only JSON, Spring serves JSON, because it is the only acceptable match. If the method produces both, Spring serves XML.
Adding XML as a second format
Jackson can write XML if you add one dependency. Boot manages the version, so you do not set it.
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>With this on the classpath, Boot registers an XML converter. No controller changes are needed, as long as produces does not exclude XML. List both types when you want to be explicit:
@GetMapping(
value = "/{id}",
produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
public BookResponse get(@PathVariable long id) {
return service.get(id);
}The order in produces does not decide the winner when the client sends */*. For that case the converter order decides, and Jackson's XML converter is registered ahead of the JSON one when both are present. A client that sends no Accept header can therefore start getting XML after you add the dependency. If this matters, pin the default by setting produces to JSON first or by sending an explicit Accept header from your own clients.
Vendor media types for versioning
Some teams version an API through the media type instead of the URL. The client asks for a specific representation, and the server provides several methods for one path.
public static final String BOOK_V1 = "application/vnd.example.book-v1+json";
public static final String BOOK_V2 = "application/vnd.example.book-v2+json";
@GetMapping(value = "/{id}", produces = BOOK_V1)
public BookResponse getV1(@PathVariable long id) {
return service.get(id);
}
@GetMapping(value = "/{id}", produces = BOOK_V2)
public BookResponseV2 getV2(@PathVariable long id) {
return service.getV2(id);
}Jackson's converter supports application/*+json, so no extra setup is needed. Spring sets the response Content-Type to the version that matched. A request with Accept: application/vnd.example.book-v2+json reaches getV2.
This approach has costs. Browsers and simple tools cannot easily set Accept, caches must vary on Accept, and a client that sends */* falls to whichever method Spring ranks first. Plain URL versions such as /api/v2/books are easier to debug, so pick the media-type form only if you have a reason.
Controlling the response type directly
ResponseEntity lets you set Content-Type yourself. This is useful when the type depends on runtime data.
@GetMapping(value = "/{id}/cover", produces = MediaType.ALL_VALUE)
public ResponseEntity<byte[]> cover(@PathVariable long id) {
byte[] image = service.coverImage(id);
return ResponseEntity.ok()
.contentType(MediaType.IMAGE_PNG)
.body(image);
}produces = MediaType.ALL_VALUE keeps the mapping from rejecting clients that ask for image/png or image/*. The explicit contentType then decides what the response says.
Format selection by URL parameter
Boot's default is header-only negotiation. Spring 5.3 and later removed the path-extension strategy (/books/1.json). Spring Boot disables the query parameter strategy as well. If you need a browser-friendly switch, enable it in application.properties:
spring.mvc.contentnegotiation.favor-parameter=true
spring.mvc.contentnegotiation.parameter-name=format
spring.mvc.contentnegotiation.media-types.json=application/json
spring.mvc.contentnegotiation.media-types.xml=application/xmlAfter this, GET /api/books/1?format=xml overrides the Accept header. Without the media-types entries, the parameter value may not map to a type, and the request gets a 406.
Testing negotiation with MockMvc
Negotiation rules are easy to break when you change a mapping, so test them. A slice test can check both the 406 and the content type of a successful response.
import static org.mockito.Mockito.when;
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;
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.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(BookController.class)
class BookNegotiationTest {
@Autowired
MockMvc mockMvc;
@MockitoBean
BookService service;
@Test
void servesJsonWhenAsked() throws Exception {
when(service.get(1L)).thenReturn(new BookResponse(1L, "Dune", "Frank Herbert"));
mockMvc.perform(get("/api/books/1").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON));
}
@Test
void rejectsUnsupportedAcceptType() throws Exception {
mockMvc.perform(get("/api/books/1").accept(MediaType.APPLICATION_PDF))
.andExpect(status().isNotAcceptable());
}
}The @MockitoBean import shown is for Spring Boot 3.4 and later. In earlier versions, use @MockBean from org.springframework.boot.test.mock.mockito.
Common errors
- 406 for a client that only wants JSON. The method's
produceslists a type the client did not send. Check the mapping and the exactAcceptheader. - 415 on a POST. The
Content-Typeheader is missing or does not matchconsumes. This is the most common cause. - Compile error on
produces = MediaType.APPLICATION_JSON. Use the_VALUEconstant, which is aString. - XML appears after adding a dependency. The XML converter is now the first match for
*/*. See the warning above. - A
produceson the class seems ignored. A method-levelproducesreplaced it.
Exercise
A client sends POST /api/books with a valid JSON body but no Content-Type header. The method is annotated @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE). What status code does the client get, and what is the fix?
Show answer
The client gets 415 Unsupported Media Type, because the request does not declare a type that matches consumes. The fix is on the client side: send Content-Type: application/json. In curl, add -H "Content-Type: application/json".
Exercise
A GET /api/books/1 method has produces = MediaType.APPLICATION_JSON_VALUE. A client sends Accept: application/xml. What status code does it get, and which exception does Spring raise internally? What single change would let that client receive XML?
Show answer
The client gets 406 Not Acceptable, from HttpMediaTypeNotAcceptableException. To serve XML, add jackson-dataformat-xml to the classpath and include MediaType.APPLICATION_XML_VALUE in the method's produces array.