forked from TrueSelph/jvspatial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthenticated_endpoints_example.py
More file actions
1211 lines (1088 loc) · 39.8 KB
/
Copy pathauthenticated_endpoints_example.py
File metadata and controls
1211 lines (1088 loc) · 39.8 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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Authenticated CRUD API Example
This example demonstrates a realistic CRUD API using the unified @endpoint decorator
with both functions and Walker classes. It showcases proper authentication, authorization,
response schemas, and real-world API patterns using the persistence layer.
Usage:
python authenticated_endpoints_example.py
Then visit http://localhost:8000/docs to see the Swagger UI
Key Features:
- Complete CRUD operations for Users and Products
- Proper authentication and authorization
- Realistic response schemas with examples
- Permission-based access control
- Automatic OpenAPI schema generation
- Walker-based complex operations
- Real persistence using the graph database
"""
import asyncio
from datetime import datetime
from typing import Any, Dict, List, Optional
from jvspatial.api import Server, endpoint
from jvspatial.api.decorators import EndpointField
from jvspatial.api.endpoints.response import (
ResponseField,
error_response,
response_schema,
success_response,
)
from jvspatial.core import Node, Walker
# =============================================================================
# DATA MODELS
# =============================================================================
class UserNode(Node):
"""User node in the graph database."""
name: str = ""
email: str = ""
role: str = "user"
department: Optional[str] = None
created_at: Optional[str] = None
updated_at: Optional[str] = None
last_login: Optional[str] = None
class ProductNode(Node):
"""Product node in the graph database."""
name: str = ""
price: float = 0.0
category: str = ""
stock: int = 0
description: Optional[str] = None
created_at: Optional[str] = None
updated_at: Optional[str] = None
# =============================================================================
# SERVER SETUP
# =============================================================================
# Create server with authentication enabled
server = Server(
title="Authenticated CRUD API Example",
description="Realistic CRUD API showcasing @endpoint decorator with authentication and response schemas",
version="1.0.0",
host="127.0.0.1",
port=8000,
# Database configuration
db_type="json",
db_path="./jvdb",
# Enable authentication
auth_enabled=True,
jwt_auth_enabled=True,
jwt_secret="demo-secret-key-2024", # pragma: allowlist secret
jwt_expire_minutes=60,
)
# Server is automatically set as current server upon instantiation
# =============================================================================
# AUTHENTICATION ENDPOINTS
# =============================================================================
# Note: Authentication endpoints are automatically registered by the server
# when auth_enabled=True. These are provided by the jvspatial library:
# - POST /auth/register (user registration)
# - POST /auth/login (user login)
# - POST /auth/logout (user logout)
# =============================================================================
# SYSTEM ENDPOINTS
# =============================================================================
@endpoint(
"/health",
methods=["GET"],
response=success_response(
data={
"status": ResponseField(
field_type=str,
description="Health status of the service",
example="healthy",
),
"timestamp": ResponseField(
field_type=str,
description="Current timestamp",
example="2024-01-01T00:00:00Z",
),
"version": ResponseField(
field_type=str, description="Service version", example="1.0.0"
),
"uptime": ResponseField(
field_type=str, description="Service uptime", example="2d 14h 32m"
),
}
),
)
async def health_check() -> Dict[str, Any]:
"""Health check endpoint."""
return {
"status": "healthy",
"timestamp": datetime.now().isoformat(),
"version": "1.0.0",
"uptime": "2d 14h 32m",
}
# =============================================================================
# USER MANAGEMENT ENDPOINTS
# =============================================================================
@endpoint(
"/users",
methods=["GET"],
auth=True,
permissions=["read_users"],
response=success_response(
data={
"users": ResponseField(
field_type=List[Dict[str, Any]],
description="List of users",
example=[
{
"id": "1",
"name": "John Doe",
"email": "john@example.com",
"role": "user",
},
{
"id": "2",
"name": "Jane Smith",
"email": "jane@example.com",
"role": "admin",
},
],
),
"total": ResponseField(
field_type=int, description="Total number of users", example=2
),
"page": ResponseField(
field_type=int, description="Current page number", example=1
),
"per_page": ResponseField(
field_type=int, description="Number of users per page", example=10
),
"total_pages": ResponseField(
field_type=int, description="Total number of pages", example=5
),
"has_previous": ResponseField(
field_type=bool,
description="Whether there's a previous page",
example=False,
),
"has_next": ResponseField(
field_type=bool, description="Whether there's a next page", example=True
),
"previous_page": ResponseField(
field_type=Optional[int], description="Previous page number", example=None # type: ignore[arg-type]
),
"next_page": ResponseField(
field_type=Optional[int], description="Next page number", example=2 # type: ignore[arg-type]
),
}
),
)
async def list_users(
page: int = 1,
per_page: int = 10,
search: Optional[str] = None,
role: Optional[str] = None,
) -> Dict[str, Any]:
"""List all users with pagination and filtering."""
from jvspatial.core.pager import ObjectPager
# Build filters for pagination
filters = {}
if role:
filters["context.role"] = role
# Create pager with filters
pager = ObjectPager(UserNode, page_size=per_page, filters=filters)
# Get the requested page
users: List[Any] = await pager.get_page(page=page)
# Apply text search if provided (post-filter on results)
if search:
search_lower = search.lower()
users = [
u
for u in users
if search_lower in u.name.lower() or search_lower in u.email.lower()
]
# Convert to dictionaries using export
users_list = await asyncio.gather(
*[u.export(exclude={"updated_at", "last_login"}) for u in users]
)
# Get pagination info from pager
pagination_info = pager.to_dict()
return {
"users": users_list,
"total": pagination_info["total_items"],
"page": pagination_info["current_page"],
"per_page": pagination_info["page_size"],
"total_pages": pagination_info["total_pages"],
"has_previous": pagination_info["has_previous"],
"has_next": pagination_info["has_next"],
"previous_page": pagination_info["previous_page"],
"next_page": pagination_info["next_page"],
}
@endpoint(
"/users",
methods=["POST"],
auth=True,
permissions=["create_users"],
response=success_response(
data={
"user": ResponseField(
field_type=Dict[str, Any],
description="Created user information",
example={
"id": "4",
"name": "New User",
"email": "new@example.com",
"role": "user",
"created_at": "2024-01-04T00:00:00Z",
},
),
"message": ResponseField(
field_type=str,
description="Success message",
example="User created successfully",
),
}
),
)
async def create_user(
name: str, email: str, role: str = "user", department: Optional[str] = None
) -> Dict[str, Any]:
"""Create a new user."""
# Check if user with this email already exists using entity-centric approach
existing = await UserNode.find(email=email)
if existing:
from fastapi import HTTPException
raise HTTPException(
status_code=409, detail="User with this email already exists"
)
# Create new user node using entity-centric approach
user = await UserNode.create(
name=name,
email=email,
role=role,
department=department,
created_at=datetime.now().isoformat(),
)
return {
"user": await user.export(),
"message": "User created successfully",
}
@endpoint(
"/users/{user_id}",
methods=["GET"],
auth=True,
permissions=["read_users"],
response=success_response(
data={
"user": ResponseField(
field_type=Dict[str, Any],
description="User information",
example={
"id": "1",
"name": "John Doe",
"email": "john@example.com",
"role": "user",
"created_at": "2024-01-01T00:00:00Z",
},
)
}
),
)
async def get_user(user_id: str) -> Dict[str, Any]:
"""Get a specific user by ID."""
# Retrieve user using entity-centric approach
user = await UserNode.get(user_id)
if not user:
from fastapi import HTTPException
raise HTTPException(status_code=404, detail="User not found")
return {"user": await user.export()}
@endpoint(
"/users/{user_id}",
methods=["PUT"],
auth=True,
permissions=["update_users"],
response=success_response(
data={
"user": ResponseField(
field_type=Dict[str, Any],
description="Updated user information",
example={
"id": "1",
"name": "John Doe Updated",
"email": "john.updated@example.com",
"role": "user",
"updated_at": "2024-01-15T12:00:00Z",
},
),
"message": ResponseField(
field_type=str,
description="Success message",
example="User updated successfully",
),
}
),
)
async def update_user(
user_id: str,
name: Optional[str] = None,
email: Optional[str] = None,
role: Optional[str] = None,
department: Optional[str] = None,
) -> Dict[str, Any]:
"""Update a user."""
# Retrieve user using entity-centric approach
user = await UserNode.get(user_id)
if not user:
from fastapi import HTTPException
raise HTTPException(status_code=404, detail="User not found")
# Update fields if provided
if name is not None:
user.name = name
if email is not None:
# Check if email is already taken by another user
existing = await UserNode.find(email=email)
if existing and existing[0].id != user_id:
from fastapi import HTTPException
raise HTTPException(
status_code=409, detail="Email already in use by another user"
)
user.email = email
if role is not None:
user.role = role
if department is not None:
user.department = department
user.updated_at = datetime.now().isoformat()
# Save the updated user using entity-centric approach
await user.save()
return {
"user": await user.export(),
"message": "User updated successfully",
}
@endpoint(
"/users/{user_id}",
methods=["DELETE"],
auth=True,
permissions=["delete_users"],
response=success_response(
data={
"message": ResponseField(
field_type=str,
description="Success message",
example="User deleted successfully",
),
"deleted_user_id": ResponseField(
field_type=str, description="ID of the deleted user", example="1"
),
}
),
)
async def delete_user(user_id: str) -> Dict[str, Any]:
"""Delete a user."""
# Retrieve user using entity-centric approach
user = await UserNode.get(user_id)
if not user:
from fastapi import HTTPException
raise HTTPException(status_code=404, detail="User not found")
# Delete user using entity-centric approach
await user.delete()
return {"message": "User deleted successfully", "deleted_user_id": user_id}
# =============================================================================
# PRODUCT MANAGEMENT ENDPOINTS
# =============================================================================
@endpoint(
"/products",
methods=["GET"],
auth=True,
permissions=["read_products"],
response=success_response(
data={
"products": ResponseField(
field_type=List[Dict[str, Any]],
description="List of products",
example=[
{
"id": "1",
"name": "Laptop",
"price": 999.99,
"category": "Electronics",
"stock": 50,
},
{
"id": "2",
"name": "Book",
"price": 19.99,
"category": "Education",
"stock": 100,
},
],
),
"total": ResponseField(
field_type=int, description="Total number of products", example=2
),
"page": ResponseField(
field_type=int, description="Current page number", example=1
),
"per_page": ResponseField(
field_type=int, description="Number of products per page", example=10
),
"total_pages": ResponseField(
field_type=int, description="Total number of pages", example=1
),
"has_previous": ResponseField(
field_type=bool,
description="Whether there's a previous page",
example=False,
),
"has_next": ResponseField(
field_type=bool,
description="Whether there's a next page",
example=False,
),
"previous_page": ResponseField(
field_type=Optional[int], # type: ignore[arg-type]
description="Previous page number",
example=None,
),
"next_page": ResponseField(
field_type=Optional[int], description="Next page number", example=None # type: ignore[arg-type]
),
}
),
)
async def list_products(
page: int = 1,
per_page: int = 10,
category: Optional[str] = None,
min_price: Optional[float] = None,
max_price: Optional[float] = None,
in_stock: bool = True,
) -> Dict[str, Any]:
"""List products with pagination and filtering."""
from jvspatial.core.pager import ObjectPager
# Build filters for pagination
filters = {}
if category:
filters["context.category"] = category
# Create pager with filters
pager = ObjectPager(ProductNode, page_size=per_page, filters=filters)
# Get the requested page
products: List[Any] = await pager.get_page(page=page)
# Apply price filters and stock filter (post-filter on results)
if min_price is not None:
products = [p for p in products if p.price >= min_price]
if max_price is not None:
products = [p for p in products if p.price <= max_price]
if in_stock:
products = [p for p in products if p.stock > 0]
# Convert to dictionaries using export
products_list = await asyncio.gather(
*[p.export(exclude={"updated_at"}) for p in products]
)
# Get pagination info from pager
pagination_info = pager.to_dict()
return {
"products": products_list,
"total": pagination_info["total_items"],
"page": pagination_info["current_page"],
"per_page": pagination_info["page_size"],
"total_pages": pagination_info["total_pages"],
"has_previous": pagination_info["has_previous"],
"has_next": pagination_info["has_next"],
"previous_page": pagination_info["previous_page"],
"next_page": pagination_info["next_page"],
}
@endpoint(
"/products",
methods=["POST"],
auth=True,
permissions=["create_products"],
response=success_response(
data={
"product": ResponseField(
field_type=Dict[str, Any],
description="Created product information",
example={
"id": "4",
"name": "New Product",
"price": 49.99,
"category": "General",
"stock": 25,
"created_at": "2024-01-04T00:00:00Z",
},
),
"message": ResponseField(
field_type=str,
description="Success message",
example="Product created successfully",
),
}
),
)
async def create_product(
name: str,
price: float,
category: str,
stock: int = 0,
description: Optional[str] = None,
) -> Dict[str, Any]:
"""Create a new product."""
# Create new product node using entity-centric approach
product = await ProductNode.create(
name=name,
price=price,
category=category,
stock=stock,
description=description,
created_at=datetime.now().isoformat(),
)
return {
"product": await product.export(),
"message": "Product created successfully",
}
@endpoint(
"/products/{product_id}",
methods=["GET"],
auth=True,
permissions=["read_products"],
response=success_response(
data={
"product": ResponseField(
field_type=Dict[str, Any],
description="Product information",
example={
"id": "1",
"name": "Laptop",
"price": 999.99,
"category": "Electronics",
"stock": 50,
"created_at": "2024-01-01T00:00:00Z",
},
)
}
),
)
async def get_product(product_id: str) -> Dict[str, Any]:
"""Get a specific product by ID."""
# Retrieve product using entity-centric approach
product = await ProductNode.get(product_id)
if not product:
from fastapi import HTTPException
raise HTTPException(status_code=404, detail="Product not found")
return {"product": await product.export()}
@endpoint(
"/products/{product_id}",
methods=["PUT"],
auth=True,
permissions=["update_products"],
response=success_response(
data={
"product": ResponseField(
field_type=Dict[str, Any],
description="Updated product information",
example={
"id": "1",
"name": "Laptop Updated",
"price": 1099.99,
"category": "Electronics",
"stock": 45,
"updated_at": "2024-01-15T12:00:00Z",
},
),
"message": ResponseField(
field_type=str,
description="Success message",
example="Product updated successfully",
),
}
),
)
async def update_product(
product_id: str,
name: Optional[str] = None,
price: Optional[float] = None,
category: Optional[str] = None,
stock: Optional[int] = None,
description: Optional[str] = None,
) -> Dict[str, Any]:
"""Update a product."""
# Retrieve product using entity-centric approach
product = await ProductNode.get(product_id)
if not product:
from fastapi import HTTPException
raise HTTPException(status_code=404, detail="Product not found")
# Update fields if provided
if name is not None:
product.name = name
if price is not None:
product.price = price
if category is not None:
product.category = category
if stock is not None:
product.stock = stock
if description is not None:
product.description = description
product.updated_at = datetime.now().isoformat()
# Save the updated product using entity-centric approach
await product.save()
return {
"product": await product.export(),
"message": "Product updated successfully",
}
@endpoint(
"/products/{product_id}",
methods=["DELETE"],
auth=True,
permissions=["delete_products"],
response=success_response(
data={
"message": ResponseField(
field_type=str,
description="Success message",
example="Product deleted successfully",
),
"deleted_product_id": ResponseField(
field_type=str, description="ID of the deleted product", example="1"
),
}
),
)
async def delete_product(product_id: str) -> Dict[str, Any]:
"""Delete a product."""
# Retrieve product using entity-centric approach
product = await ProductNode.get(product_id)
if not product:
from fastapi import HTTPException
raise HTTPException(status_code=404, detail="Product not found")
# Delete product using entity-centric approach
await product.delete()
return {
"message": "Product deleted successfully",
"deleted_product_id": product_id,
}
# =============================================================================
# ANALYTICS AND REPORTING WALKERS
# =============================================================================
@endpoint(
"/analytics/users",
methods=["POST"],
auth=True,
permissions=["read_analytics"],
response=success_response(
data={
"analysis": ResponseField(
field_type=Dict[str, Any],
description="User analysis results",
example={
"total_users": 150,
"active_users": 120,
"new_users_this_month": 25,
"departments": {
"engineering": 45,
"marketing": 30,
"sales": 40,
"support": 35,
},
"engagement_score": 8.5,
},
),
"insights": ResponseField(
field_type=List[str],
description="Key insights from the analysis",
example=[
"High user engagement in engineering",
"Growth opportunity in sales",
"Support team needs more resources",
],
),
"recommendations": ResponseField(
field_type=List[str],
description="Actionable recommendations",
example=[
"Increase marketing budget",
"Hire more support staff",
"Implement user training program",
],
),
"generated_at": ResponseField(
field_type=str,
description="Analysis generation timestamp",
example="2024-01-15T14:30:00Z",
),
}
),
)
class UserAnalyticsWalker(Walker):
"""Analyze user data and generate insights."""
department: str = EndpointField(
default="all",
description="Department to analyze",
examples=["engineering", "marketing", "sales", "support", "all"],
)
# These properties will automatically be exposed as endpoint parameters
include_inactive: bool = True
time_period: str = "30d" # 7d, 30d, 90d, 1y
analysis_depth: str = "comprehensive" # basic, detailed, comprehensive
include_predictions: bool = False
async def analyze_users(self) -> Dict[str, Any]:
"""Analyze users and generate insights using real data."""
# Query all users from database using entity-centric approach
if self.department != "all":
all_users = await UserNode.find(department=self.department)
else:
all_users = await UserNode.find()
# Calculate statistics
total_users = len(all_users)
active_users = (
total_users # Assume all users are active if include_inactive is True
)
if not self.include_inactive:
# Filter out users who haven't logged in recently
# For this example, we'll consider users with last_login as active
active_users = len([u for u in all_users if u.last_login])
# Count by department
departments: Dict[str, int] = {}
for user in all_users:
dept = user.department or "unassigned"
departments[dept] = departments.get(dept, 0) + 1
# Calculate new users based on time period
now = datetime.now()
cutoff_days = {
"7d": 7,
"30d": 30,
"90d": 90,
"1y": 365,
}.get(self.time_period, 30)
new_users = 0
for user in all_users:
if user.created_at:
try:
created = datetime.fromisoformat(
user.created_at.replace("Z", "+00:00")
)
days_ago = (now - created.replace(tzinfo=None)).days
if days_ago <= cutoff_days:
new_users += 1
except (ValueError, AttributeError):
pass
# Generate insights
insights = []
if total_users > 0:
insights.append(
f"Total of {total_users} users in {'all departments' if self.department == 'all' else self.department}"
)
if active_users < total_users * 0.8:
insights.append("Low user engagement detected")
if new_users > total_users * 0.2:
insights.append("High growth rate observed")
else:
insights.append("No users found in the database")
# Recommendations
recommendations = []
if total_users > 0:
if len(departments) < 3:
recommendations.append("Consider diversifying departments")
if active_users < total_users * 0.7:
recommendations.append("Implement user engagement campaigns")
if new_users < total_users * 0.1:
recommendations.append("Increase user acquisition efforts")
if self.include_predictions:
insights.append(
f"Predicted growth: {int(new_users * 1.15)} new users next period"
)
recommendations.append("Prepare infrastructure for user growth")
return {
"analysis": {
"total_users": total_users,
"active_users": active_users,
"new_users_this_month": new_users,
"departments": departments,
"engagement_score": (
round(active_users / total_users * 10, 1) if total_users > 0 else 0
),
"time_period": self.time_period,
"analysis_depth": self.analysis_depth,
},
"insights": insights,
"recommendations": recommendations,
"generated_at": datetime.now().isoformat(),
}
@endpoint(
"/analytics/products",
methods=["POST"],
auth=True,
permissions=["read_analytics"],
response=success_response(
data={
"sales_summary": ResponseField(
field_type=Dict[str, Any],
description="Product sales summary",
example={
"total_revenue": 125000.50,
"units_sold": 250,
"top_selling_category": "Electronics",
"average_order_value": 500.00,
},
),
"product_performance": ResponseField(
field_type=List[Dict[str, Any]],
description="Individual product performance",
example=[
{
"product_id": "1",
"name": "Laptop",
"revenue": 50000.00,
"units_sold": 50,
"growth_rate": 15.5,
},
{
"product_id": "2",
"name": "Book",
"revenue": 2000.00,
"units_sold": 100,
"growth_rate": -5.2,
},
],
),
"trends": ResponseField(
field_type=List[str],
description="Sales trends and patterns",
example=[
"Electronics showing strong growth",
"Education category declining",
"Seasonal patterns detected",
],
),
"generated_at": ResponseField(
field_type=str,
description="Analysis generation timestamp",
example="2024-01-15T14:30:00Z",
),
}
),
)
class ProductAnalyticsWalker(Walker):
"""Analyze product performance and sales data."""
category: str = EndpointField(
default="all",
description="Product category to analyze",
examples=["Electronics", "Education", "Clothing", "Home", "all"],
)
# These properties will automatically be exposed as endpoint parameters
time_period: str = "30d" # 7d, 30d, 90d, 1y
include_trends: bool = True
min_revenue: float = 0.0
sort_by: str = "revenue" # revenue, units_sold, growth_rate
async def analyze_products(self) -> Dict[str, Any]:
"""Analyze product performance using real data."""
# Query products from database using entity-centric approach
if self.category != "all":
all_products = await ProductNode.find(category=self.category)
else:
all_products = await ProductNode.find()
# Calculate product performance (simulate revenue based on price and stock)
# In a real system, you'd have actual sales data
products = []
for p in all_products:
# Simulate revenue as price * (stock * 0.8) - assuming 80% sell-through
revenue = p.price * (p.stock * 0.8)
units_sold = int(p.stock * 0.8)
# Simulate growth rate based on stock level (more stock = positive growth)
growth_rate = (p.stock / 100.0) - 50.0 if p.stock > 0 else -10.0
if revenue >= self.min_revenue:
products.append(
{
"product_id": p.id,
"name": p.name,
"category": p.category,
"revenue": round(revenue, 2),
"units_sold": units_sold,
"growth_rate": round(growth_rate, 1),
}
)
# Sort products
if self.sort_by == "revenue":