I am implementing a REST api using Spring MVC. The requirement is:
/transactions returns an array of transactions./transactions?groupByCategory returns transactions grouped by categories.For example request #1 returns:
[
{ "id": 1, "category": "auto", "amount": 100 },
{ "id": 2, "category": "misc", "amount": 200 },
{ "id": 3, "category": "auto", "amount": 300 }
]
whereas request #2 groups this result by category and returns the sum of each category:
[
{ "category": "auto", "amount": 400 },
{ "category": "misc", "amount": 200 }
]
Obviously the return value from these requests is of different types. How do I do this in Spring MVC? So far I have:
@RequestMapping("/transactions")
public List<Transaction> getTransactions(
@RequestParam(value="groupByCategory", required=false) String groupByCategory
) {
...
}
But this fixes the return type to List<Transaction>. How do I accommodate the second type: List<TransactionSummaryByCategory>?
Edit: I found one solution, i.e. to specify the return type as Object. That seems to work and the response is serialized correctly based on the object type. However, I wonder if this is a best practice!
public Object getTransactions(...) {
...
}
You can simply provide two methods in your controller. First one returning List<Transaction> mapped using
@RequestMapping("/transactions")
and the second one returning List<TransactionSummaryByCategory> and mapped using
@RequestMapping(value = "/transactions", params = "groupByCategory")
You can return a generic List.
public List<?> getTransactions()
{
}
Based on the request params you can populate the list with the appropriate objects
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With