Skip to content
Related Articles

Related Articles

Spring – REST XML Response

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 15 Mar, 2022

The popularity of REST API is increasing day by day as it fulfills architecting an application in a convenient manner. A REST API is an acronym for ‘Representational state transfer’. It is also called RESTful web services. It is also a ‘Controller’, but with a difference that Rest Controller returns Data, while Controller returns a View of ‘Model-View-Controller’ architecture. REST API can work on all HTTP methods like ( GET, POST, PUT, PATCH, DELETE, etc ). These methods correspond to create, read, update, and delete (CRUD) operations, respectively. It can return many types of data. JSON is considered the standard form for data transferring between web applications. 

Data types that REST API can return are as follows: 

  1. JSON (JavaScript Object Notation)
  2. XML
  3. HTML
  4. XLT
  5. Python
  6. PHP
  7. Plain text

Pre-requisite: Though JSON is the standard form to transfer data among applications, it comes with some disadvantages which are overcome in XML format data transferring.

The advantages of XML are as follows: 

  1. It is an Extensible markup language that uses tags for data definition.
  2. It supports namespaces.
  3. It supports comments.
  4. It supports various encoding.
  5. Last but not the least, XML is more secure than JSON.

Note

  • JSON is less secure because of the absence of a JSON parser in the browser.
  • JSONP is dangerous because it allows cross-origin exchanges of data.

REST API – XML Response

  • When we create a Spring Boot project with ‘Starter Web’ dependency, we only get support for returning data in JSON format, with the help of the Jackson library.
  • To embed support for returning data in XML format we need third-party dependencies.
  • There are many libraries that support XML return format, for Example – Jackson, JAXB, etc.

Working of Rest XML Response

Project Structure – Maven

Way 1: Using Jackson 

The Jackson library is already present in the Spring framework’s classpath for our application. We just need to add an extension to the Jackson library that can work with XML data responses. To add the extension, add the following dependency in the project build.

Maven – pom.xml

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

After adding the above dependency and updating the project, the Jackson XML extension will get added in the classpath so the Spring MVC will automatically pick this up for XML responses.

A. File: pom.xml (Project configuration)

Example:

XML




<?xml version="1.0" encoding="UTF-8"?>
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>sia</groupId>
    <artifactId>GFG-RestXMLResponse</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>GFG-RestXMLResponse</name>
    <description>GeeksforGeeks</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
          
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>
          
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
  
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


B. Bootstrapping of application

Example: GfgRestXmlResponseApplication.java

Java




// Java Program to Illustrate Bootstrapping of Application
  
package gfg;
  
// Importing required classes
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
  
// Annotation
@SpringBootApplication
  
// Class
public class GfgRestXmlResponseApplication {
  
    // Main driver method
    public static void main(String[] args)
    {
        SpringApplication.run(
            GfgRestXmlResponseApplication.class, args);
    }
}


 
C. Object to be return as XML response (EntityModel.java)

This class acts as a User object ( bean ) whose fields will be mapped to XML tags respectively. It also requires Getter/Setter methods which are automatically generated using ‘@Data’ annotation of the ‘Lombok’ library. To embed the Lombok library in the project, add the following dependency in the project build.

Maven – pom.xml

<dependency>
     <groupId>org.projectlombok</groupId>
     <artifactId>lombok</artifactId>
     <optional>true</optional>
</dependency>

Example:

Java




// Java Program Illustrating Object to be return as XML
// response
  
package gfg;
  
// Importing required classes
import lombok.Data;
  
// Annotation
@Data
  
// Class
public class EntityModel {
  
    // Class data members
    String ID;
    String NAME;
    String DOB;
    String PINCODE;
}


D. REST API returning XML response (RestXMLResponseController.java)

This REST API controller is configured to return data specifically in XML format, using produces attribute of @RequestMapping annotation.

Example:

Java




// Java Program Illustrating REST API returning XML response
  
package gfg;
  
// Importing required classes
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
  
// Annotations
@RestController
@RequestMapping(path = "/xml-output",
                produces = "application/xml")
  
// Class
public class RestXMLResponseController {
  
    @GetMapping("/get")
    public ResponseEntity<EntityModel> get()
    {
  
        EntityModel model = new EntityModel();
        model.setID("1");
        model.setNAME("Darshan.G.Pawar");
        model.setDOB("05-09-2001");
        model.setPINCODE("422 009");
  
        HttpHeaders hearders = new HttpHeaders();
        ResponseEntity<EntityModel> entityModel
            = new ResponseEntity<>(model, hearders,
                                   HttpStatus.CREATED);
  
        return entityModel;
    }
  
    // Annotation
    @GetMapping("/get/{id}")
  
    // Class
    public ResponseEntity<EntityModel>
    getById(@PathVariable("id") String id)
    {
  
        EntityModel model = new EntityModel();
        model.setID(id);
        model.setNAME("Darshan.G.Pawar");
        model.setDOB("05-09-2001");
        model.setPINCODE("422 009");
  
        HttpHeaders hearders = new HttpHeaders();
        ResponseEntity<EntityModel> entityModel
            = new ResponseEntity<>(model, hearders,
                                   HttpStatus.CREATED);
  
        return entityModel;
    }
}


Output 1:

XML Response returned by get() method

Output 2:

XML Response returned by getById() method

E. ConsumeXMLResponse.java (Get the REST API response)

  • The data returned in XML format by REST API needs to be consumed and make to use.
  • Spring Framework provides a convenient way to consume REST responses with the help of Spring’s ‘RestTemplate’.
  • It benefits us by preventing the need to write boilerplate code.
  • RestTemplate provides us with methods that are HTTP methods specific.
  • Here for GET HTTP request, the ‘getForEntity()’ method is used that accepts URL to @GetMapping method, a class to which response will be mapped to and additional object parameters to URL.
  • This method will return a ResponseEntity<> object.

Java




// Java Program Illustrating Getting REST API Response
  
package gfg;
  
// Importing required classes 
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
  
// Class 
public class ConsumeXMLResponse {
   
    RestTemplate rest = new RestTemplate();
      
    public ResponseEntity<EntityModel> get(String id) {
          
        return rest.getForEntity("http://localhost:8080/xml-output/get/{id}"
                  EntityModel.class, id);
          
    }
}


F. File: OutputController.java (Regular controller)

This MVC Controller uses the above class to get the XML response returned by REST API. Also, after getting the data it returns us a modified view ( View.html)

Example:

Java




// Java Program to Illustrate Regular controller
  
package gfg;
  
// Importing required classes
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
  
// Annotation
@Controller
@RequestMapping("View")
  
// Class
public class OutputController {
  
    // Annotation
    @GetMapping("/get/{id}")
  
    public String
    getXMLOutput(@PathVariable("id") String id, Model model)
    {
  
        ConsumeXMLResponse response
            = new ConsumeXMLResponse();
        ResponseEntity<EntityModel> responseEntity
            = response.get(id);
  
        EntityModel entity = responseEntity.getBody();
        HttpHeaders headers = responseEntity.getHeaders();
  
        model.addAttribute("xml", entity);
        model.addAttribute("XMLheaders", headers);
  
        return "View";
    }
}


G. File: View.html (Display the XML response)

HTML




<!DOCTYPE html>
      xmlns:th = " http://www.thymeleaf.org " >
 <head>
 <title> GeeksforGeeks </title>
 <style>
 h2 {
    width      : 200px ;
    display    : inline-block ;
    text-align :right;
}
 h1 {
    color   : forestgreen ;
    display : inline-block ;
}
h3 {
    width : 650px ;
    color : forestgreen ;
}
</style>
</head>
<body>
<h1> Hello Geek : REST XML Response </h1> </br>
  
<h2> Id : </h2>            <h1 th:text = " ${xml.ID} " > Replaceable text </h1 > </br>
<h2> Name : </h2>          <h1 th:text = " ${xml.NAME} " > Replaceable text </h1 > </br>
<h2> Date Of Birth : </h2> <h1 th:text = " ${xml.DOB} " > Replaceable text </h1 > </br>
<h2> Pincode : </h2>       <h1 th:text = " ${xml.PINCODE} " > Replaceable text </h1 > </br>
  
<h4> Headers : </h4>
<h3 th:text = " ${XMLheaders} " ></h3>
</body>
</html>


Output:

REST XML Response in HTML

Way 2: Using JAXB

To use the JAXB library, add the following dependency in the project built.

File: Maven – pom.xml

<dependency>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxb2-maven-plugin</artifactId>
    <version>2.5.0</version>
</dependency>

To make it work you have to use @XmlRootElement annotation of the same library on an object which will be mapped to XML response.

Example: EntityModel.java

Java




package gfg;
  
import javax.xml.bind.annotation.XmlRootElement;
  
import lombok.Data;
  
@XmlRootElement
@Data
public class EntityModel {
   
    String ID;
    String NAME;
    String DOB;
    String PINCODE;
}


Note: You can also use Jersey dependency for developing RESTful APIs. The main advantage of using it is that it already has a JAX-RS library which eventually uses JAXB libraries.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!