-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathWalmartResponse.py
More file actions
816 lines (628 loc) · 24.1 KB
/
WalmartResponse.py
File metadata and controls
816 lines (628 loc) · 24.1 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
"""Module for Walmart API responses in object form."""
from __future__ import annotations
import sys
from html import unescape
from typing import Any, Final, cast
# pyright: basic
if sys.version_info >= (3, 12):
from typing import override
else:
from typing_extensions import override
# pyright: strict
__all__ = (
"OverallRating",
"RatingDistributions",
"ReviewStatistics",
"WalmartCatalog",
"WalmartProduct",
"WalmartReview",
"WalmartSearch",
"WalmartStore",
"WalmartTaxonomy",
)
class _ResponseHandler:
"""Exposes JSON data safely to get attributes."""
def __init__(self, payload: dict[str, Any]) -> None:
self.payload: Final[dict[str, Any]] = payload
@override
def __str__(self) -> str:
return str(self.payload)
def keys(self):
return self.payload.keys()
def items(self):
return self.payload.items()
def values(self):
return self.payload.values()
def get_attribute(self, attr: str) -> Any | None:
"""Attempt to get the attribute from a payload."""
return self.payload.get(attr)
def get_attribute_text(self, attr: str) -> str | None:
"""Get clean unescaped html text."""
try:
return unescape(self.payload.get(attr) or "")
except TypeError:
return None
def get_attribute_float(self, attr: str) -> float | None | Any:
"""Safe extraction of a float attribute from the payload."""
try:
return float(self.payload.get(attr)) # pyright: ignore[reportArgumentType]
except ValueError:
return self.payload.get(attr)
def get_attribute_int(self, attr: str) -> int | None | Any:
"""Safe extraction of an int attribute from the payload."""
try:
return int(self.payload.get(attr)) # pyright: ignore[reportArgumentType]
except ValueError:
return self.payload.get(attr)
class _WalmartResponse:
"""Base class for Walmart responses."""
def __init__(self, payload: dict[str, Any]) -> None:
self.response_handler: Final[_ResponseHandler] = _ResponseHandler(payload)
@override
def __str__(self) -> str:
return str(self.response_handler)
def __getitem__(self, key: str):
return self.response_handler.get_attribute(key)
def get_attr(self, attr: str):
"""
Another way to get attributes.
The function call helps in case an attribute is added to Walmart API but not here.
Parameters
----------
attr: str
JSON attribute to get from product response
"""
return self.response_handler.get_attribute(attr)
def keys(self):
return self.response_handler.keys()
def items(self):
return self.response_handler.items()
def values(self):
return self.response_handler.values()
class WalmartProduct(_WalmartResponse):
"""
A Walmart Products as an object.
Not all properties exist for all products. To get a more in-depth look, visit
(https://walmart.io/docs/affiliate/item_response_groups)
Each property of this class will safely return a value or `None` if the product does not have
that attribute.
Base Responses are Marked by `Base Response`
"""
@property
def itemId(self):
"""
A positive integer that uniquely identifies an item.
`Base Response`
"""
return self.response_handler.get_attribute_int("itemId")
@property
def parentItemId(self):
"""
Item Id of the base version for this item.
This is present only if item is a variant of the base version,
such as a different color or size.
"""
return self.response_handler.get_attribute_int("parentItemId")
@property
def name(self):
"""
Standard name of the item.
`Base Response`
"""
return self.response_handler.get_attribute("name")
@property
def msrp(self):
"""
Manufacturer suggested retail price.
`Base Response`
"""
return self.response_handler.get_attribute("msrp")
@property
def salePrice(self):
"""
Selling price for the item in USD.
`Base Response`
"""
return self.response_handler.get_attribute_float("salePrice")
@property
def upc(self):
"""
Unique Product Code.
`Base Response`
"""
return self.response_handler.get_attribute("upc")
@property
def categoryPath(self):
"""
Breadcrumb for the item.
This string describes the category level hierarchy that the item falls under.
`Base Response`
"""
return self.response_handler.get_attribute("categoryPath")
@property
def categoryNode(self):
"""
Category id for the category of this item.
This value can be passed to APIs to pull this item's category level information.
"""
return self.response_handler.get_attribute("categoryNode")
@property
def shortDescription(self):
"""Short description for the item."""
return self.response_handler.get_attribute_text("shortDescription")
@property
def longDescription(self):
"""
Long description for the item.
`Base Response`
"""
return self.response_handler.get_attribute("longDescription")
@property
def brandName(self):
"""Item's brand."""
return self.response_handler.get_attribute("brandName")
@property
def thumbnailImage(self):
"""
Small size image for the item in jpeg format with dimensions 100 x 100 pixels.
Returns URL of image
`Base Response`
"""
return self.response_handler.get_attribute("thumbnailImage")
@property
def mediumImage(self):
"""
Medium size image for the item in jpeg format with dimensions 180 x 180 pixels.
Returns URL of image
"""
return self.response_handler.get_attribute("mediumImage")
@property
def largeImage(self):
"""
Large size image for the item in jpeg format with dimensions 450 x 450 pixels.
Returns URL of image
"""
return self.response_handler.get_attribute("largeImage")
@property
def productTrackingUrl(self):
"""
Affiliate URL.
Deep linked URL that directly links to the product page of this item on walmart.com, and
uniquely identifies the affiliate sending this request via a impact radius tracking id
|PUBID|. The PUBID parameter needs to be replaced with your impact radius tracking id,
and is used by Walmart to correctly attribute the sales from your channel on walmart.com.
Actual commission numbers will be made available through your impact radius account.
`Base Response`
"""
return self.response_handler.get_attribute("productTrackingUrl")
@property
def ninetySevenCentShipping(self):
"""
Whether the item qualifies for 97 cent shipping.
Returns
-------
Bool
"""
return self.response_handler.get_attribute("ninetySevenCentShipping")
@property
def standardShipRate(self):
"""
Shipping rate for this item for standard shipping (3 to 5 business days).
`Base Response`
"""
return self.response_handler.get_attribute("standardShipRate")
@property
def twoThreeDayShippingRate(self):
"""Expedited shipping rate for this item (2 to 3 business days)."""
return self.response_handler.get_attribute("twoThreeDayShippingRate")
@property
def size(self):
"""Size attribute for the item."""
return self.response_handler.get_attribute("size")
@property
def color(self):
"""Color attribute for the item."""
return self.response_handler.get_attribute("color")
@property
def marketplace(self):
"""
Whether this item is from one of the Walmart marketplace sellers.
In this case, the item cannot be returned back to Walmart stores or walmart.com.
It must be returned to the marketplace seller in accordance with their returns policy.
`Base Response`
"""
return self.response_handler.get_attribute("marketplace")
@property
def sellerInfo(self):
"""Name of the marketplace seller, applicable only for marketplace items."""
return self.response_handler.get_attribute("sellerInfo")
@property
def shipToStore(self):
"""Whether the item can be shipped to the nearest Walmart store."""
return self.response_handler.get_attribute("shipToStore")
@property
def freeShipToStore(self):
"""
Whether the item qualifies for free shipping to the nearest Walmart store.
Returns
-------
Bool
"""
return self.response_handler.get_attribute("freeShipToStore")
@property
def modelNumber(self):
"""Model number attribute for the item."""
return self.response_handler.get_attribute("modelNumber")
@property
def availableOnline(self):
"""
Whether the item is currently available for sale on Walmart.com.
`Base Response`
"""
return self.response_handler.get_attribute("availableOnline")
@property
def stock(self):
"""
Indicative quantity of the item available online.
Possible values are [Available, Limited Supply, Last few items, Not available].
* Limited supply: can go out of stock in the near future,
so needs to be refreshed for availability more frequently.
* Last few items: can go out of stock very quickly,
so could be avoided in case you only need to show available items to your users.
"""
return self.response_handler.get_attribute("stock")
@property
def customerRating(self):
"""Average customer rating out of 5."""
return self.response_handler.get_attribute_float("customerRating")
@property
def numReviews(self):
"""Number of customer reviews available on this item on Walmart.com."""
return self.response_handler.get_attribute_int("numReviews")
@property
def clearance(self):
"""Whether the item is on clearance on Walmart.com."""
return self.response_handler.get_attribute("clearance")
@property
def preOrder(self):
"""Whether this item is available on pre-order on Walmart.com."""
return self.response_handler.get_attribute("preOrder")
@property
def preOrderShipsOn(self):
"""Date the item will ship on if it is a pre-order item."""
return self.response_handler.get_attribute("preOrderShipsOn")
@property
def offerType(self):
"""
Indicates whether the item is sold ONLINE_ONLY, ONLINE_AND_STORE, STORE_ONLY.
`Base Response`
"""
return self.response_handler.get_attribute("offerType")
@property
def rhid(self):
"""Indicates the offer category id for this item."""
return self.response_handler.get_attribute("rhid")
@property
def bundle(self):
"""Indicates if the item is a bundle."""
return self.response_handler.get_attribute("bundle")
@property
def attributes(self):
"""Various attributes for the item."""
return self.response_handler.get_attribute("attributes")
@property
def affiliateAddToCartUrl(self):
"""
Affiliate Url for directly sending user to cart.
Impact Radius tracking url to add the item on Walmart.com cart page and uniquely identifies
the affiliate via a impact radius tracking id. The impact radius tracking id is used by
Walmart to correctly attribute the sales from your channel on walmart.com. Actual
commission numbers will be made available through your impact radius account.
"""
return self.response_handler.get_attribute("affiliateAddToCartUrl")
@property
def freeShippingOver35Dollars(self):
"""Indicates if the item is eligible for free shipping over 35 dollars."""
return self.response_handler.get_attribute("freeShippingOver35Dollars")
@property
def gender(self):
"""Indicates the gender for the item."""
return self.response_handler.get_attribute("gender")
@property
def age(self):
"""Indicates the age range for the item."""
return self.response_handler.get_attribute("age")
@property
def imageEntities(self):
"""
Primary and secondary images of the item on Walmart.com.
Each image are in thumbnail, medium and large sizes
`Base Response`
"""
return self.response_handler.get_attribute("imageEntities")
@property
def isTwoDayShippingEligible(self):
"""
Indicates whether the item is eligible for two day shipping.
`Base Response`
"""
return self.response_handler.get_attribute("isTwoDayShippingEligible")
@property
def customerRatingImage(self):
"""Image of average customer rating."""
return self.response_handler.get_attribute("customerRatingImage")
@property
def giftOptions(self):
"""
Indicates the gift options of the item.
Whether gift wrap, gift message, gift receipt are allowed.
`Base Response`
"""
return self.response_handler.get_attribute("giftOptions")
@property
def bestMarketplacePrice(self):
"""
Information about best price on marketplace.
Including:
price, sellerInfo, standardShipRate, twoThreeDayShippingRate, availableOnline,
clearance, and offerType
"""
return self.response_handler.get_attribute("bestMarketplacePrice")
@property
def variants(self):
"""The itemIds of the item's variants, if variants exist."""
return self.response_handler.get_attribute("variants")
# hi :p
class WalmartCatalog(_WalmartResponse):
"""Walmart Catalog Products response object."""
@property
def category(self):
"""Category id of the desired category. This should match the id field from Taxonomy API."""
return self.response_handler.get_attribute("category")
@property
def format(self):
"""Format of response. Should be json."""
return self.response_handler.get_attribute("format")
@property
def nextPage(self):
"""
URI of next page.
Pass this back into `catalog_product` as `nextPage=data.nextPage` to get next page response.
"""
return self.response_handler.get_attribute("nextPage")
@property
def nextPageExist(self) -> bool:
"""Boolean of if there is a next page."""
return cast(bool, self.response_handler.get_attribute("nextPageExist"))
@property
def totalPages(self):
"""Amount of pages that fit the category."""
return self.response_handler.get_attribute("totalPages")
@property
@override
def items(self) -> list[WalmartProduct]: # pyright: ignore[reportIncompatibleMethodOverride]
"""List of Walmart items returned from the response."""
response: list[dict[str, Any]] = self.response_handler.get_attribute("items") or []
return [WalmartProduct(item) for item in response]
class WalmartReview(_WalmartResponse):
"""Walmart reviews object."""
@property
def name(self):
"""Standard name of the item."""
return self.response_handler.get_attribute("name")
@property
def overallRating(self):
"""`OverallRating` for the rating of the item overallRating."""
return OverallRating(self.response_handler.get_attribute("overallRating") or {})
@property
def reviewer(self):
"""Reviewer's Name."""
return self.response_handler.get_attribute("reviewer")
@property
def reviewText(self):
"""Customer review text."""
return self.response_handler.get_attribute("reviewText")
@property
def submissionTime(self):
"""Timestamp at which customer submitted review."""
return self.response_handler.get_attribute("submissionTime")
@property
def title(self):
"""Title of review."""
return self.response_handler.get_attribute("title")
@property
def upVotes(self):
"""Count of up votes given to customer review."""
return self.response_handler.get_attribute("upVotes")
@property
def downVotes(self):
"""Count of down votes given to customer review."""
return self.response_handler.get_attribute("downVotes")
class OverallRating(_WalmartResponse):
"""Overall rating of a product."""
@property
def label(self):
"""Type of rating."""
return self.response_handler.get_attribute("label")
@property
def rating(self):
"""Customer rating."""
return self.response_handler.get_attribute("rating")
class RatingDistributions(_WalmartResponse):
"""Rating distribution of reviews for Walmart products."""
@property
def ratingValue(self):
"""Rating distribution for the rating value."""
return self.response_handler.get_attribute("ratingValue")
@property
def count(self):
"""Count of customer ratings for rating of ratingValue."""
return self.response_handler.get_attribute("count")
class ReviewStatistics(_WalmartResponse):
"""Statistics of a products reviews."""
@property
def averageOverallRating(self):
"""Overall customer rating for the item."""
return self.response_handler.get_attribute("averageOverallRating")
@property
def overallRatingRange(self):
"""Range of the customer rating."""
return self.response_handler.get_attribute("overallRatingRange")
@property
def ratingDistributions(self) -> list[RatingDistributions]:
"""Customer Rating Distribution."""
response: list[dict[str, Any]] = (
self.response_handler.get_attribute("ratingDistributions") or []
)
return [RatingDistributions(dist) for dist in response]
@property
def totalReviewCount(self):
"""Total no of customer reviews."""
return self.response_handler.get_attribute("totalReviewCount")
class WalmartReviewResponse(_WalmartResponse):
"""The entire response from https://walmart.io/docs/affiliate/reviews API call."""
@property
def itemId(self):
"""Item Id."""
return self.response_handler.get_attribute("itemId")
@property
def name(self):
"""Standard name of the item."""
return self.response_handler.get_attribute("name")
@property
def salePrice(self):
"""Sales Price of the item."""
return self.response_handler.get_attribute("salePrice")
@property
def upc(self):
"""Unique Product Code."""
return self.response_handler.get_attribute("upc")
@property
def categoryPath(self):
"""This string describes the Reporting Hierarchy level names that the item falls under.""" # noqa: D404
return self.response_handler.get_attribute("categoryPath")
@property
def brandName(self):
"""Item's brand."""
return self.response_handler.get_attribute("brandName")
@property
def productTrackingUrl(self):
"""Product's tracking URL using publisher id."""
return self.response_handler.get_attribute("productTrackingUrl")
@property
def categoryNode(self):
"""This string describes the Reporting Hierarchy level Ids that the item falls under.""" # noqa: D404
return self.response_handler.get_attribute("categoryNode")
@property
def reviews(self) -> list[WalmartReview]:
"""Array of `WalmartReview` reviews for the item."""
response: list[dict[str, Any]] = self.response_handler.get_attribute("reviews") or []
return [WalmartReview(review) for review in response]
@property
def reviewStatistics(self) -> ReviewStatistics:
"""Customer review stats for the item."""
return ReviewStatistics(self.response_handler.get_attribute("reviewStatistics") or {})
@property
def nextPage(self):
"""URL next page of customer Review."""
return self.response_handler.get_attribute("nextPage")
@property
def availableOnline(self) -> bool:
"""Item available online (true/false)."""
return cast(bool, self.response_handler.get_attribute("availableOnline"))
class WalmartStore(_WalmartResponse):
"""Walmart Store container from search API (store)."""
@property
def no(self):
"""Store number."""
return self.response_handler.get_attribute_int("no")
@property
def name(self):
"""Name."""
return self.response_handler.get_attribute("name")
@property
def country(self):
"""Country."""
return self.response_handler.get_attribute("country")
@property
def coordinates(self) -> list[float]:
"""Coordinates Array."""
return self.response_handler.get_attribute("coordinates") or []
@property
def streetAddress(self):
"""Street Address."""
return self.response_handler.get_attribute("streetAddress")
@property
def city(self):
"""City."""
return self.response_handler.get_attribute("city")
@property
def stateProvCode(self):
"""State Province Code."""
return self.response_handler.get_attribute("stateProvCode")
@property
def zip(self):
"""Zip Code."""
return self.response_handler.get_attribute("zip")
@property
def phoneNumber(self):
"""Store's Phone Number."""
return self.response_handler.get_attribute("phoneNumber")
class WalmartSearch(_WalmartResponse):
"""Response from Walmart Search API."""
@property
def query(self):
"""Search text - whitespace separated sequence of keywords to search for."""
return self.response_handler.get_attribute("query")
@property
def sort(self):
"""Sort type - [relevance, price, title, bestseller, customerRating, new]."""
return self.response_handler.get_attribute("sort")
@property
def responseGroup(self):
"""[base, full] Item Response Groups type."""
return self.response_handler.get_attribute("responseGroup")
@property
def totalResults(self):
"""Int of amount of items in search."""
return self.response_handler.get_attribute_int("totalResults")
@property
def start(self):
"""Starting point of the results within the matching set of items."""
return self.response_handler.get_attribute("start")
@property
def numItems(self):
"""Number of matching items to be returned, max value 25."""
return self.response_handler.get_attribute_int("numItems")
@property
@override
def items(self) -> list[WalmartProduct]: # pyright: ignore[reportIncompatibleMethodOverride]
"""List[`WalmartProduct`]."""
response: list[dict[str, Any]] = self.response_handler.get_attribute("items") or []
return [WalmartProduct(item) for item in response]
@property
def facets(self):
"""The facets for the search."""
return self.response_handler.get_attribute("facets")
class WalmartTaxonomy(_WalmartResponse):
"""Taxonomy used to categorize items on Walmart.com."""
@property
def id(self):
"""
Category id for this category.
These values are used as an input parameter to other APIs.
"""
return self.response_handler.get_attribute("id")
@property
def name(self):
"""Name for this category as specified on Walmart.com."""
return self.response_handler.get_attribute("name")
@property
def children(self):
"""List of categories that have the current category as a parent in the taxonomy."""
response: list[dict[str, Any]] = self.response_handler.get_attribute("children") or []
return [WalmartTaxonomy(child) for child in response]
@property
def path(self):
"""Category path for this category."""
return self.response_handler.get_attribute("path")