from fastapi import FastAPI
db = [
{'api_key': '437af89f-38ba-44f1-9eda-924f370193d4',
'tokens': 3,
'user_id': '6ddf9779-4be7-449c-a70d-51e81c19dd0b'},
{'api_key': '48762b59-e968-459e-b28d-50e7a1ad37a4',
'tokens': 3,
'user_id': 'daf36850-68ab-40fc-86af-e6093b6797dd'},
{'api_key': 'dabbd875-acbd-4b98-a47f-a526075d41b4',
'tokens': 3,
'user_id': '5750957f-a246-4290-a35e-2dec83bcfcea'},
{'api_key': '604d5fe2-f7ce-4560-8137-eeae32091738',
'tokens': 3,
'user_id': '2d4ac462-b118-48d7-897e-163c2e8327aa'},
{'api_key': '8540cbef-de3e-4cbd-83bc-f66297a7f407',
'tokens': 3,
'user_id': 'bb435e7e-b5da-4a8c-b860-e43a8e765f67'}
]
app = FastAPI()
def update_tokens_for_user(user_id, api_key):
for user in db:
if user['user_id'] == user_id and user['api_key'] == api_key:
tokens = user['tokens']
if tokens > 0:
tokens = tokens - 1
user['tokens'] = tokens
return {'tokens': tokens}
else:
return {'tokens': tokens, 'msg': 'you need to get more tokens'}
@app.get('/test')
def test(user_id : str, api_key: str):
result = update_tokens_for_user(user_id, api_key)
if result:
return result
else:
return {'msg': 'api key or user id is not found'}