實作一個 RESTful API 來追蹤 IOU。
四位室友常常互相借錢,卻老是記不清誰欠誰多少錢。
你的任務是實作一個簡單的 RESTful API,它會透過 POST 請求接收 IOU,並能透過 GET 請求提供指定的摘要資訊。
{
"name": "Adam",
"owes": {
"Bob": 12.0,
"Chuck": 4.0,
"Dan": 9.5
},
"owed_by": {
"Bob": 6.5,
"Dan": 2.75
},
"balance": "<(total owed by other users) - (total owed to other users)>"
}
| 說明 | HTTP 方法 | URL | 酬載格式 | 無酬載的回應 | 含酬載的回應 |
|---|---|---|---|---|---|
| 列出使用者資訊 | GET | /users | {"users":["Adam","Bob"]} |
{"users":<List of all User objects>} |
{"users":<List of User objects for <users> (sorted by name)} |
| 建立使用者 | POST | /add | {"user":<name of new user (unique)>} |
N/A | <User object for new user> |
| 建立 IOU | POST | /iou | {"lender":<name of lender>,"borrower":<name of borrower>,"amount":5.25} |
N/A | {"users":<updated User objects for <lender> and <borrower> (sorted by name)>} |
實作RestAPI類別中的get和post方法。
你只需要撰寫處理函式,不需要實作真正的 HTTP 伺服器。你可以用一個記憶體中的物件來模擬資料庫,這個物件會包含所有已儲存的使用者。RestAPI類別的建構函式應該接受這個資料庫的實例作為引數(並在沒有傳入引數時,為它設定預設值)。
在這個實作中,若遇到GET請求,資料內容應該是 URL 的一部分,並且要像查詢參數一樣處理,例如/users?users=Adam,Bob。