Build a REST Service That Consumes Any Type of Request Format
Join the DZone community and get the full member experience.
Join For FreeSometimes, 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.
xxxxxxxxxx
public class Employee {
private int id;
private String firstName;
private String lastName;
private String department;
//setters & getters
//toString()
You may also like: Spring Boot: The Most Notable Features You Should Know.
Here is my REST service, EmployeeController.Java.
public class EmployeeController {
(path = "/get-diff-data/", consumes = MediaType.ALL_VALUE)
public ResponseEntity<?> getDetails( Employee emp) {
ResponseEntity<?> response = null;
try {
response = ResponseEntity.status(HttpStatus.OK).body(emp);
} catch (Exception e) {
response = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
return response;
}
}
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:
xxxxxxxxxx
<employee>
<department>IT</department>
<firstName>Santosh</firstName>
<id>123</id>
<lastName>Devkate</lastName>
</employee>
For the above input, this is the response we get in JSON:
xxxxxxxxxx
{
"id": 123,
"firstName": "Santosh",
"lastName": "Devkate",
"department": "IT"
}
Here is a snapshot of the entire service call:
Next, we will test it based on JSON input:
xxxxxxxxxx
{
"id": 123,
"firstName": "Santosh",
"lastName": "Devkate",
"department": "IT"
}
The expected response will be the same JSON:
{
"id": 123,
"firstName": "Santosh",
"lastName": "Devkate",
"department": "IT"
}
Thanks for reading this blog. Please feel free to post any comments on this if you have any questions!
Further Reading
- Step-By-Step Spring Boot RESTful Web Service Complete Example.
- XML Parsing Using Java org.w3c.dom.
- All About Spring Boot [Tutorials and Articles].
Opinions expressed by DZone contributors are their own.
Comments