-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_example.py
More file actions
274 lines (231 loc) · 8.62 KB
/
api_example.py
File metadata and controls
274 lines (231 loc) · 8.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
"""
Example API endpoint structure for chart data.
This shows how to structure responses for API integration.
"""
from chart_data import ChartDataGenerator
from database import SplitDataDB
from typing import Dict
import json
class ChartDataAPI:
"""API wrapper for chart data generation."""
def __init__(self):
"""Initialize database connection."""
self.db = SplitDataDB()
self.generator = None
def connect(self):
"""Connect to database."""
if self.db.connect():
self.generator = ChartDataGenerator(self.db)
return True
return False
def disconnect(self):
"""Disconnect from database."""
self.db.disconnect()
def get_user_weekly_expenses_api(self, user_id: int, weeks: int = 12) -> Dict:
"""
API endpoint: Get user's weekly expenses.
Returns format:
{
"success": true,
"data": {
"x": ["2024-W01", "2024-W02", ...],
"y": [150.50, 200.00, ...],
"label": "Weekly Expenses (Last 12 weeks)"
}
}
"""
try:
if not self.generator:
return {"success": False, "error": "Database not connected"}
data = self.generator.get_user_weekly_expenses(user_id, weeks)
return {
"success": True,
"data": {
"x": data["x"],
"y": data["y"],
"label": data["label"]
}
}
except Exception as e:
return {"success": False, "error": str(e)}
def get_user_monthly_expenses_api(self, user_id: int, months: int = 12) -> Dict:
"""
API endpoint: Get user's monthly expenses.
Returns format:
{
"success": true,
"data": {
"x": ["2024-01", "2024-02", ...],
"y": [500.00, 750.00, ...],
"label": "Monthly Expenses (Last 12 months)"
}
}
"""
try:
if not self.generator:
return {"success": False, "error": "Database not connected"}
data = self.generator.get_user_monthly_expenses(user_id, months)
return {
"success": True,
"data": {
"x": data["x"],
"y": data["y"],
"label": data["label"]
}
}
except Exception as e:
return {"success": False, "error": str(e)}
def get_user_paid_owed_api(self, user_id: int) -> Dict:
"""
API endpoint: Get user's paid vs owed amounts.
Returns format:
{
"success": true,
"data": {
"paid": 1500.00,
"owed": 800.00,
"net_balance": 700.00,
"x": ["Paid", "Owed"],
"y": [1500.00, 800.00]
}
}
"""
try:
if not self.generator:
return {"success": False, "error": "Database not connected"}
data = self.generator.get_user_paid_vs_owed(user_id)
# Format for bar/pie chart
return {
"success": True,
"data": {
"paid": data["paid"],
"owed": data["owed"],
"net_balance": data["net_balance"],
"x": ["Paid", "Owed"],
"y": [data["paid"], data["owed"]]
}
}
except Exception as e:
return {"success": False, "error": str(e)}
def get_user_category_expenses_api(self, user_id: int, months: int = 12) -> Dict:
"""
API endpoint: Get user's expenses by category.
Returns format:
{
"success": true,
"data": {
"x": ["food", "travel", "entertainment", ...],
"y": [500.00, 300.00, 200.00, ...],
"label": "Expenses by Category (Last 12 months)"
}
}
"""
try:
if not self.generator:
return {"success": False, "error": "Database not connected"}
data = self.generator.get_user_expenses_by_category(user_id, months)
return {
"success": True,
"data": {
"x": data["x"],
"y": data["y"],
"label": data["label"]
}
}
except Exception as e:
return {"success": False, "error": str(e)}
def get_user_all_charts_api(self, user_id: int, weeks: int = 12, months: int = 12) -> Dict:
"""
API endpoint: Get all chart data for a user.
Perfect for dashboard page.
Returns format:
{
"success": true,
"data": {
"weekly_expenses": {"x": [...], "y": [...], "label": "..."},
"monthly_expenses": {"x": [...], "y": [...], "label": "..."},
"paid_vs_owed": {"paid": 1500.00, "owed": 800.00, ...},
"expenses_by_category": {"x": [...], "y": [...], "label": "..."},
"settlement_status": {...}
}
}
"""
try:
if not self.generator:
return {"success": False, "error": "Database not connected"}
all_data = self.generator.get_user_all_chart_data(user_id, weeks, months)
return {
"success": True,
"data": all_data
}
except Exception as e:
return {"success": False, "error": str(e)}
def get_response_json(self, response: Dict) -> str:
"""Convert response dict to JSON string."""
return json.dumps(response, indent=2, default=str)
def example_flask_endpoint():
"""
Example Flask endpoint structure.
@app.route('/api/users/<int:user_id>/charts', methods=['GET'])
def get_user_charts(user_id):
api = ChartDataAPI()
if not api.connect():
return jsonify({"success": False, "error": "Database error"}), 500
try:
weeks = request.args.get('weeks', 12, type=int)
months = request.args.get('months', 12, type=int)
result = api.get_user_all_charts_api(user_id, weeks, months)
return jsonify(result)
finally:
api.disconnect()
"""
pass
def main():
"""Test API endpoints."""
api = ChartDataAPI()
if not api.connect():
print("Failed to connect to database")
return
try:
user_id = 1
print("="*60)
print("API ENDPOINT EXAMPLES")
print("="*60)
# Test weekly expenses endpoint
print("\n1. Weekly Expenses API:")
print("-" * 60)
weekly_response = api.get_user_weekly_expenses_api(user_id, weeks=12)
print(json.dumps(weekly_response, indent=2)[:300] + "...")
# Test monthly expenses endpoint
print("\n2. Monthly Expenses API:")
print("-" * 60)
monthly_response = api.get_user_monthly_expenses_api(user_id, months=12)
print(json.dumps(monthly_response, indent=2)[:300] + "...")
# Test paid vs owed endpoint
print("\n3. Paid vs Owed API:")
print("-" * 60)
paid_owed_response = api.get_user_paid_owed_api(user_id)
print(json.dumps(paid_owed_response, indent=2))
# Test category expenses endpoint
print("\n4. Category Expenses API:")
print("-" * 60)
category_response = api.get_user_category_expenses_api(user_id, months=12)
print(json.dumps(category_response, indent=2)[:400] + "...")
# Test all charts endpoint
print("\n5. All Charts API (Dashboard):")
print("-" * 60)
all_charts_response = api.get_user_all_charts_api(user_id, weeks=12, months=12)
print(f"Response keys: {list(all_charts_response.keys())}")
print(f"Data keys: {list(all_charts_response['data'].keys())}")
# Save full response to file
with open(f'api_response_user_{user_id}.json', 'w') as f:
f.write(api.get_response_json(all_charts_response))
print(f"\n✓ Saved full API response to api_response_user_{user_id}.json")
except Exception as e:
print(f"Error: {e}")
import traceback
traceback.print_exc()
finally:
api.disconnect()
if __name__ == "__main__":
main()