0

Background
We are consuming the API from a 3rd-party vendor

Problem Statement:
I am building a wrapper API around another API. The same exact JSON payload that I will be receiving from the client to the wrapper API will also be used to make an HTTP request to the original API.

Currently I'm converting JSON which deserializes to a String. Is this the right approach if the payload is just passing through the wrapper API to the original API? In other words, is the @RequestBody type String okay for my use case or do I still need to deserialize to a Java Object?

Use Case for wrapper
If multiple teams consumed the API from the 3rd-party vendor, all teams would have to make changes if we were to switch vendors. If we create a wrapper, only one team would have to make the changes. There is no processing in this wrapper.

Controller Code:

@RestController
@RequestMapping(value = FolderController.PATH, produces = MediaType.APPLICATION_JSON_VALUE)
public class PersonController(){
    static final String PATH = "/person";
    private final PersonService personService;

@Autowired
public PersonController(PersonService personService){
    this.personService = personService
}

@PostMapping
@ResponseBody
public String createPerson(@RequestBody String requestBody){ 
    return personService.createPerson(requestBody);
}   
ShadyBears
  • 3,955
  • 13
  • 44
  • 66

2 Answers2

2

Whether you need to deserialize depends on what processing is necessary for your wrapper. If you just want to pass the request further without changing it, this should work.

However, if you just need to proxy the request, consider using Smiley's HTTP Proxy Servlet for this task. Or if you are wrapping the API to implement security around it, then consider using Spring cloud gateway

Oskars Pakers
  • 699
  • 3
  • 11
  • 1
    @ShadyBears I am highly skeptical that it makes sense to have this wrapper, but if you're going to, you definitely should be using Spring Cloud Gateway as recommended by this answer. If you have to write out a shim in the future, then you can do controllers by hand. – chrylis -cautiouslyoptimistic- Mar 30 '20 at 05:55
1

It is always better to follow coding practices and convert the request body to a java POJO class instead of a string. Converting to POJO has several advantages :

  • You could provide additional validations for the request body.
  • Incase the request body changes or if there are any issues it could be identified easily.
  • Provides better control over the request structure.In future , if the API that you are consuming changes the request body structure, you could change it from your API instead of adapting it at every API that consumes your API.
Ananthapadmanabhan
  • 5,706
  • 6
  • 22
  • 39