{{announcement.body}}
{{announcement.title}}

Build a REST Service That Consumes Any Type of Request Format

DZone 's Guide to

Build a REST Service That Consumes Any Type of Request Format

In this article we discuss how to build a REST service that can consume any type of request format, including XML and JSON.

· Integration Zone ·
Free Resource

Sometimes, we have demands from clients that require a REST service that consumes JSON/XML or any other format dynamically. In this tutorial, we're going to show you how to do exactly that with Spring Boot. 

Here is the class that I am taking as a request body in my API. Here, I am using @XmlRootElement annotation to mark an Employee class as a root. For more details about this annotation, please click here.

Java
 


xxxxxxxxxx
1
15
 
1
@XmlRootElement
2
 
          
3
public class Employee {
4
 
          
5
private int id;
6
 
          
7
private String firstName;
8
 
          
9
private String lastName;
10
 
          
11
private String department;
12
 
          
13
//setters & getters 
14
 
          
15
//toString()


You may also like: Spring Boot: The Most Notable Features You Should Know.

Here is my REST service, EmployeeController.Java.

Java
 


x
15
1
@RestController
2
public class EmployeeController {
3
 
          
4
    @PostMapping(path = "/get-diff-data/", consumes = MediaType.ALL_VALUE)
5
    public ResponseEntity<?> getDetails(@RequestBody Employee emp) {
6
        ResponseEntity<?> response = null;
7
        try {
8
            response = ResponseEntity.status(HttpStatus.OK).body(emp);
9
        } catch (Exception e) {
10
            response = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
11
        }
12
        return response;
13
    }
14
 
          
15
}


After this, let's make sure that the service API is working properly. Here, I'll be using Postman. First, we will check with XML:

XML
 


xxxxxxxxxx
1
1
<?xml version="1.0" encoding="UTF-8"?>
2
<employee>
3
   <department>IT</department>
4
   <firstName>Santosh</firstName>
5
   <id>123</id>
6
   <lastName>Devkate</lastName>
7
</employee>


For the above input, this is the response we get in JSON:

JSON
 


xxxxxxxxxx
1
 
1
{
2
    "id": 123,
3
    "firstName": "Santosh",
4
    "lastName": "Devkate",
5
    "department": "IT"
6
}


Here is a snapshot of the entire service call:

XML service call

XML service call

Next, we will test it based on JSON input:

JSON


The expected response will be the same JSON:

JSON


Thanks for reading this blog. Please feel free to post any comments on this if you have any questions!


Further Reading

Topics:
rest services ,rest api ,java ,spring boot ,tutorial ,json ,xml

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}