Spring Boot RESTful Web service endpoints consume and produce JSON representation by default. But we can easily make our REST API endpoint consume and produce an XML representation of a resource as well. In this tutorial, you will learn how to do that.
Add XML Support to Spring Boot Project
To make our Spring Boot project consume and produce an XML representation of a resource, we will need to add to a POM.xml one additional dependency.
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-xml --> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> </dependency>
By adding the above dependency to our project, we are enabling our project to consume and produce XML.
The Content-Type HTTP Header
To tell the web server that we are sending XML in the HTTP Request body, we include one additional HTTP Header into the request. This HTTP Header is called Content-Type, and its value should be set to application/xml. However, if your Spring Boot application is configured to work with XML only, then including the Content-Type HTTP header becomes optional.
Below is an example of how to provide the Content-Type HTTP Header in Postman HTTP Client.
@PostMapping Consumes XML
Let’s say we have the following code that accepts HTTP Post requests and reads HTTP Request Body.
@PostMapping public UserRest createUser(@RequestBody UserDetailsModelRequest UserDetails) { UserRest returnValue = new UserRest(); ... return returnValue; }
To make the above method able to read XML from the HTTP Request body and convert that XML into an object of UserDetailsModelRequest class, there is no additional code we need to write. It will just work.
However, if we want to configure the above method to accept XML by default, then we need to explicitly configure a list of supported media types. In the below @PostMapping configuration, the XML media type is first in the list. In this case, if the HTTP request does not contain a Content-Type header, our method will expect XML in the request body.
@PostMapping( consumes = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE } )
With the above configuration of @PostMapping annotation, we are explicitly specifying that additionally to consuming and producing JSON representation, our web service endpoint can consume and produce an XML representation of a resource as well. And if no Content-Type header is included in the request, then XML is expected.
Video Tutorial
I hope that this tutorial was helpful.
Check the Spring Boot tutorials page for other tutorials and video lessons.