RESTful APIs sometimes return responses in different media types (JSON, XML, and so on). The mechanism responsible for choosing the correct media type is known as content negotiation in Spring.
By default, in Spring MVC, the ContentNegotiatingViewResolver
bean will be in charge of resolving the correct content according to the content negotiation policies defined in your application.
You can have a look at ContentNegotiationManagerFactoryBean
to see how these policies are applied within Spring MVC.
Content type can be resolved with the following strategies:
Accept
header sent by the client?format=json
/myResource.json
or /myResource.xml
You can customize these strategies in your Spring configuration by overriding the configureContentNegotiation()
method of the WebMvcConfigurerAdapter
class.
By default, Spring will use the Accept
header and the path extension.
To enable XML serialization with Spring Boot, you can add the following dependency to your classpath:
compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml'
If you explore your API with your browser and go to http://localhost:8080/api/users
, you will see the result as XML, as follows:
That's because your browser doesn't usually request JSON, but XML is second after HTML. This is shown in the following screenshot:
To get JSON back, you can either go to http://localhost:8080/api/users.json
or send the appropriate Accept
header with Postman or httpie.