Multiple Response Type in RestAPI – JSON, XML:

RestAPI when implemented by default it returns JSON type. But there are situations where the client might require different content type like XML or Plain Text for the SameAPI. It is generally not a good practice to duplicate the RestAPI calls just for the purpose to content-type change.

In this article let us see an example of how the client might request for the specific content-type to be returned and how can this be handled in a single RestAPI call without duplicating the code.

In RestAPI we have @RequestHeader from which we receive the content-type that has to be returned by the API.

Let us understand with an example,

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>RestAPI</groupId>
	<artifactId>MultiResponse</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>MultiResponse</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.1.RELEASE</version>
	</parent>

	<dependencies>
		<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>
	</dependencies>
</project>

 

Employee.java

package com.javainfinite.model;

import org.springframework.stereotype.Component;

@Component
public class Employee {

	int id;
	String name;
	String department;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", department=" + department + "]";
	}

}

 

EmployeeService.java

package com.javainfinite.service;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

@Service
public class EmployeeService {

	public MediaType getContentType(String contentType) {
		MediaType mediaType = null;
		switch (contentType) {
		case "application/json":
			mediaType = mediaType.APPLICATION_JSON;
			break;

		case "application/xml":
			mediaType = mediaType.APPLICATION_XML;
			break;

		}
		return mediaType;
	}
}

I have included switch only for JSON and XML, if we want we can include for other formats too – text, xhtml etc

EmployeeController.java

import java.util.Collections;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.javainfinite.model.Employee;
import com.javainfinite.service.EmployeeService;

@RestController
public class EmployeeController {

	@Autowired
	EmployeeService eService;

	@RequestMapping(value = "/Employee")
	public Employee employeeDetails() {
		Employee employee = new Employee();
		employee.setId(1);
		employee.setName("Alpha");
		employee.setDepartment("Finance");
		return employee;
	}

	// Return type both
	@RequestMapping(value = "/EmployeeJsonXML", produces = { "application/json", "application/xml" })
	public ResponseEntity<Employee> employeeJsonXml(
			@RequestHeader(value = "Content-Type", required = true) String acceptType) {
		ResponseEntity<Employee> employee = null;
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders header = new HttpHeaders();
		header.setAccept(Collections.singletonList(eService.getContentType(acceptType)));
		HttpEntity<String> entity = new HttpEntity<>("body", header);
		employee = restTemplate.exchange("http://localhost:8181/Employee", HttpMethod.GET, entity, Employee.class);
		return employee;
	}
}

App.java

@SpringBootApplication
public class App 
{
    public static void main( String[] args )
    {
        SpringApplication.run(App.class, args);
    }
}

Output:

Code for download available here

 

 

 

 

 

 

By Sri

Leave a Reply

Your email address will not be published. Required fields are marked *