Multiple Response Type in RestAPI – JSON, XML

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

 

Employee.java

 

EmployeeService.java

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

EmployeeController.java

App.java

Output:

Code for download available here

 

 

 

 

 

 

Leave a Reply

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