53 lines
1.1 KiB
Python
53 lines
1.1 KiB
Python
from typing import Union
|
|
|
|
from fastapi import FastAPI
|
|
from pydantic import BaseModel
|
|
|
|
class Transfer(BaseModel):
|
|
amount: int
|
|
sender: str
|
|
receiver: str
|
|
|
|
app = FastAPI()
|
|
|
|
accounts = {
|
|
'1': 1000,
|
|
'2': 1000,
|
|
}
|
|
|
|
transactions: list[Transfer] = []
|
|
|
|
@app.post("/transfer")
|
|
def transfer(transfer: Transfer):
|
|
amount = transfer.amount
|
|
sender = transfer.sender
|
|
receiver = transfer.receiver
|
|
|
|
if amount <= 0:
|
|
return {"error": "Amount must be greater than 0"}
|
|
|
|
if accounts.get(sender) <= amount:
|
|
return {"error": "Sender does not have sufficient funds. "}
|
|
else:
|
|
# Minus sender's amount
|
|
accounts[sender] = accounts.get(sender) - amount
|
|
|
|
# Add receiver amount
|
|
accounts[receiver] = accounts.get(receiver) + amount
|
|
|
|
# Include the transaction
|
|
transactions.append(transfer)
|
|
|
|
print(f"transfer {amount} from {sender} to {receiver}")
|
|
print(transactions)
|
|
print(accounts.get("1"))
|
|
print(accounts.get("2"))
|
|
|
|
|
|
return {"amount": amount, "sender": sender, "receiver": receiver}
|
|
|
|
|
|
@app.get("/transactions")
|
|
def getTransactions():
|
|
return transactions
|