Aggregate values in REST APIs
Asked Answered
K

2

9

I am working on an application which requires some double entry bookkeeping. Currently there are two endpoints

/account
/transaction

While /account handles general data of the accounts, /transaction handles transactions for deposits/withdrawal. Account balance is calculated based on the related transactions. I kept them separated to get consistency in the bookkeeping when transferring value from one to another account.

My question is how to represent the balance of an account at the /account endpoint as it always will be calculated on request time. Should a response just contain the balance as a read-only field? This smells like bad API design since all fields but this one would be writeable/updateable.

The alternative coming to my mind would be to extend the endpoint to

/account/{id}/balance

returning only the balance of the regarding account. However, this would always require a second call to get the balance in addition to the remaining data of the account. Maybe the answer could generalized on how to represent aggregated values.

Karen answered 30/10, 2015 at 15:17 Comment(0)
M
0

Very good question. I run into situations like this, often. I would say two things:

  1. You probably have other "read-only" fields, like "id"
  2. You may not want to incur the time it takes to calculate the current balance every time you get an account details.

I think I would opt for /account/{id}/balance ... but maybe name it /account/{id}/calculatebalance to indicate that it does take some time to run this methods. And, then it is obvious that the value is a calculated value. If you had "several" calculated values, then I would rethink my opinion.

2 cents.

Meteoric answered 18/11, 2015 at 20:42 Comment(1)
You usually don't have any actions in the rest endpoints. By action I mean, "calculatebalance". Specifying the resource name is the usual REST convention.Creasy
O
0

You usually don't write aggregate properties, so it is natural that the property is read only. It is a sing that you are starting to have a service instead of a database with HTTP interface. Recalculating for each request is not necessary if you can cache it somewhere, though it depends on your needs. I see this is a very old question, idk. how I clicked on it.

Ozieozkum answered 22/10, 2022 at 12:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.