-2

Situation: I am designing a REST API that needs one or more, potentially large objects to do it's work

I am facing a decision to either

  1. Pass the large object by reference and have the API retrieve it
  2. Pass in the large object as a parameter

Approach 1:

@PostMapping("/api/{id}")
String getSomeObj(int id){
    //make another rest call with id and get CustomObj
    // then do some logic and return something
    //Here response time will be more as it has again another rest calls

}

Approach 2:

@PostMapping("/api/{id}")
String getSomeObj(@PathParam("id") int id, @RequestBody CustomObj obj){
    //directly do logic with the provided obj and return something
    //Here Response time would be less as we are directly getting the actual Object from Request Body
    //BUT is this a good practice to pass an object in which we need only few details?
}

Issue 1):

for(int i=0; i<100; i++){
    id = i;
    //make rest call to /api/{id} 
}

Above Unnecessary 100 internal rest calls if we follow approach 1, we can avoid above issue if we follow approach 2

Issue 2): What if a CustomObj is a Huge Nested JSON Object, of course memory taken by JSON would be very less even if JSON object has so many arrays and nested JSON objects, BUT we don't need all the information gettin from the JSON, only few details required from the Request Object. But is this a good practice sending a huge object as a request body?

So in above two, which approach is good practice?

10
  • Why not just post those few details that you do need instead of the large object? Commented Feb 23, 2020 at 14:25
  • @BenCottrell Custom Object would be dynamic, so some custom objects might be small or some object might have more data, we do not have control over custom object..
    – john
    Commented Feb 23, 2020 at 14:28
  • Any other replies pls?
    – john
    Commented Feb 23, 2020 at 17:34
  • You should briefly describe the problem or question before diving into the code. It should give a frame of reference for someone not familiar with the problem.
    – Martin K
    Commented Feb 24, 2020 at 12:20
  • 1
    I am still looking for an answer!!!!
    – john
    Commented Feb 29, 2020 at 13:43

1 Answer 1

0

For most use cases, you should pass in precisely the data needed by the API.

References: Data Transfer Object Parameter Object

1
  • Sorry, I didnt understood with above link..
    – john
    Commented Feb 25, 2020 at 4:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.