user10866653
user10866653

Reputation: 11

Returning Multiple Objects in one Method

My problem is quite simple example has two methods. One returns an Account and another a Customer object.

I have about 10 other different requests that should be made for a WebApp page.

Is it correct to make 10 different requests on the WebApp or just create 1 with everything that I need?

If so, what is the correct way to do this? Do I need to create a custom object that holds all the other objects that I need in the page and then return it or is there a better way?

What is the correct approach?

@GetMapping("/customer")
public Customer getCustomer(@RequestParam String customerNumber) {
    return customer.getCustomer(customerNumber);
}

@GetMapping("/account")
public Account getAccountFromCustomer(@RequestParam String customerNumber, @RequestParam String accountNumber) {
    return account.getAccountFromCustomer(customerNumber, accountNumber);
}

Upvotes: 1

Views: 76

Answers (2)

leftbit
leftbit

Reputation: 838

You might want to think about the object relationship between Customer and Accounts. Usually a Customer would aggregate zero to many Accounts and youl'd retrieve Accounts via the Customer object.

What is your use case? Does it make sense to work retrieve an Account without corresponding Customer data? If not, you don't need a custom object holder because the Customer fulfills that role nicely.

Of course your buisiness case might differ...

Upvotes: 0

davidxxx
davidxxx

Reputation: 131396

You define an API according to the client requirements.
For this point, REST services are not different of service.
Why expose 10 operations that the client has to invoke to gather the result if you can return to it the aggregated result ? Besides HTTP requests are not "free".

As a side note, API has to be unitary tested and REST service are API. In your case you will need to test 10 methods instead of a 1.

All that seems not the right path.
So yes in your case favor object aggregation to multiple requests.

Note that in some cases you want to define very fine grained operations but only when the client may need to request just one entity and not a graph of objects.
It is not your case, keep the things simple.

Upvotes: 1

Related Questions