Consuming XML in Spring Boot REST

By default, Spring Boot RESTful Web service endpoints consume and produce JSON representation. But we can easily make our RESTful Spring Boot Web service endpoints consume and produce an XML representation of a resource as well.

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 our POM.xml one additional dependency.

<!-- -->

By adding the above dependency to our project, we are making our project be able to consume and produce XML.

The Content-Type HTTP Header

In the case when our Spring Boot project supports XML, providing the Content-Type HTTP Header with a value of application/xml is optional. The HTTP Post request containing XML in the request body can omit the Content-Type HTTP headed, provided that we have the above jackson-dataformat-xml dependency added to a POM.XML file. Although our Spring Boot Web service endpoint will be able to process the request even without the Content-Type HTTP header provided, it is still a good practice to include a proper Content-Type HTTP header.

Below is an example of how to provide the Content-Type HTTP Header in Postman HTTP Client.

XML Content-Type HTTP Header in Postman

@PostMapping Consumes XML

Let’s say we have the following code that accepts HTTP Post request and reads HTTP Request Body.

public UserRest createUser(@RequestBody UserDetailsModelRequest UserDetails) {
    UserRest returnValue = new UserRest();

    return returnValue;

To make the above code be able to consume XML from the HTTP Request body and convert that XML into an object of UserDetailsModelRequest class, there is nothing special we need to do in Spring Boot. It will just work. But, if your web service endpoint does already have other media types configured in the @PostMapping annotation, then we will need to specify that additionally to other media types, it can also consume application/xml media type.

        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.

Video Tutorial

I hope that this short Spring MVC tutorial on how to enable your RESTful Web Service endpoints to return XML or JSON representation was helpful. If you have any questions, please comment below. Explore my blog to find even more tutorials on how to build RESTful Web Service with Spring MVC or Jersey JAX-RS.

Leave a Reply

Your email address will not be published.