0
# Google Cloud Retail
1
2
Python client library for Google Cloud Retail API that enables customers to build end-to-end personalized recommendation systems without requiring high-level expertise in machine learning or recommendation systems. The library provides comprehensive tools for product catalog management, search functionality, AI-powered recommendations, user event tracking, and analytics.
3
4
## Package Information
5
6
- **Package Name**: google-cloud-retail
7
- **Language**: Python
8
- **Installation**: `pip install google-cloud-retail`
9
10
## Core Imports
11
12
```python
13
import google.cloud.retail
14
```
15
16
For stable API (recommended for production):
17
18
```python
19
from google.cloud import retail
20
```
21
22
For specific API versions:
23
24
```python
25
from google.cloud import retail_v2
26
from google.cloud import retail_v2alpha # Alpha features
27
from google.cloud import retail_v2beta # Beta features
28
```
29
30
For async clients (optimal for async frameworks like FastAPI, asyncio applications):
31
32
```python
33
from google.cloud.retail import ProductServiceAsyncClient
34
from google.cloud.retail import SearchServiceAsyncClient
35
from google.cloud.retail import UserEventServiceAsyncClient
36
# All service clients have corresponding async variants
37
```
38
39
## Basic Usage
40
41
```python
42
from google.cloud import retail
43
44
# Initialize a product service client
45
client = retail.ProductServiceClient()
46
47
# Create a product
48
project_id = "your-project-id"
49
location = "global"
50
catalog = "default_catalog"
51
branch = "default_branch"
52
53
parent = f"projects/{project_id}/locations/{location}/catalogs/{catalog}/branches/{branch}"
54
55
product = retail.Product(
56
id="product-123",
57
title="Example Product",
58
categories=["Electronics", "Computers"],
59
price_info=retail.PriceInfo(
60
price=299.99,
61
currency_code="USD"
62
)
63
)
64
65
request = retail.CreateProductRequest(
66
parent=parent,
67
product=product,
68
product_id=product.id
69
)
70
71
created_product = client.create_product(request=request)
72
print(f"Created product: {created_product.name}")
73
74
# Search for products
75
search_client = retail.SearchServiceClient()
76
search_request = retail.SearchRequest(
77
placement=f"projects/{project_id}/locations/{location}/catalogs/{catalog}/placements/search",
78
query="computers",
79
page_size=10
80
)
81
82
search_response = search_client.search(request=search_request)
83
for result in search_response.results:
84
print(f"Found product: {result.product.title}")
85
```
86
87
### Async Usage
88
89
```python
90
import asyncio
91
from google.cloud.retail import ProductServiceAsyncClient
92
93
async def manage_products_async():
94
# Initialize async client
95
async_client = ProductServiceAsyncClient()
96
97
# Create product asynchronously
98
project_id = "your-project-id"
99
location = "global"
100
catalog = "default_catalog"
101
branch = "default_branch"
102
103
parent = f"projects/{project_id}/locations/{location}/catalogs/{catalog}/branches/{branch}"
104
105
product = retail.Product(
106
id="async-product-123",
107
title="Async Example Product",
108
categories=["Electronics"],
109
price_info=retail.PriceInfo(price=199.99, currency_code="USD")
110
)
111
112
request = retail.CreateProductRequest(
113
parent=parent,
114
product=product,
115
product_id=product.id
116
)
117
118
# Await async operation
119
created_product = await async_client.create_product(request=request)
120
print(f"Async created product: {created_product.name}")
121
122
# Close the async client
123
await async_client.close()
124
125
# Run async function
126
# asyncio.run(manage_products_async())
127
```
128
129
## Architecture
130
131
The Google Cloud Retail API is organized around several core concepts:
132
133
- **Projects**: Top-level containers for all retail resources
134
- **Catalogs**: Collections of products within a project location
135
- **Branches**: Separate product data environments (e.g., staging, production)
136
- **Products**: Individual items in your catalog with attributes, pricing, and availability
137
- **User Events**: Customer interactions (views, purchases, add-to-cart) used for recommendations
138
- **Models**: Machine learning models for personalized recommendations
139
- **Serving Configs**: Configuration for search and recommendation serving
140
141
The library supports three API versions with different stability levels:
142
- **v2**: Production-stable core functionality
143
- **v2beta**: Beta features with broader testing
144
- **v2alpha**: Experimental features under active development
145
146
## Capabilities
147
148
### Product Management
149
150
Core product catalog operations including creating, updating, and managing product information, inventory, and fulfillment details.
151
152
```python { .api }
153
class ProductServiceClient:
154
def create_product(self, request: CreateProductRequest) -> Product: ...
155
def get_product(self, request: GetProductRequest) -> Product: ...
156
def list_products(self, request: ListProductsRequest) -> ListProductsResponse: ...
157
def update_product(self, request: UpdateProductRequest) -> Product: ...
158
def delete_product(self, request: DeleteProductRequest) -> None: ...
159
def set_inventory(self, request: SetInventoryRequest) -> Operation: ...
160
def import_products(self, request: ImportProductsRequest) -> Operation: ...
161
162
class ProductServiceAsyncClient:
163
async def create_product(self, request: CreateProductRequest) -> Product: ...
164
async def get_product(self, request: GetProductRequest) -> Product: ...
165
async def list_products(self, request: ListProductsRequest) -> ListProductsResponse: ...
166
async def update_product(self, request: UpdateProductRequest) -> Product: ...
167
async def delete_product(self, request: DeleteProductRequest) -> None: ...
168
async def set_inventory(self, request: SetInventoryRequest) -> Operation: ...
169
async def import_products(self, request: ImportProductsRequest) -> Operation: ...
170
```
171
172
[Product Management](./product-management.md)
173
174
### Search and Discovery
175
176
Search functionality with filtering, faceting, ranking, and query auto-completion capabilities.
177
178
```python { .api }
179
class SearchServiceClient:
180
def search(self, request: SearchRequest) -> SearchResponse: ...
181
182
class CompletionServiceClient:
183
def complete_query(self, request: CompleteQueryRequest) -> CompleteQueryResponse: ...
184
```
185
186
[Search and Discovery](./search-discovery.md)
187
188
### AI-Powered Recommendations
189
190
Machine learning-based prediction and recommendation services for personalized customer experiences.
191
192
```python { .api }
193
class PredictionServiceClient:
194
def predict(self, request: PredictRequest) -> PredictResponse: ...
195
196
class ModelServiceClient:
197
def create_model(self, request: CreateModelRequest) -> Operation: ...
198
def tune_model(self, request: TuneModelRequest) -> Operation: ...
199
def get_model(self, request: GetModelRequest) -> Model: ...
200
```
201
202
[AI-Powered Recommendations](./ai-recommendations.md)
203
204
### User Event Tracking
205
206
Collection and management of user interaction events that power recommendation algorithms and analytics.
207
208
```python { .api }
209
class UserEventServiceClient:
210
def write_user_event(self, request: WriteUserEventRequest) -> UserEvent: ...
211
def collect_user_event(self, request: CollectUserEventRequest) -> HttpBody: ...
212
def import_user_events(self, request: ImportUserEventsRequest) -> Operation: ...
213
```
214
215
[User Event Tracking](./user-events.md)
216
217
### Catalog Configuration
218
219
Management of catalog settings, attributes, branches, and completion configurations.
220
221
```python { .api }
222
class CatalogServiceClient:
223
def list_catalogs(self, request: ListCatalogsRequest) -> ListCatalogsResponse: ...
224
def update_catalog(self, request: UpdateCatalogRequest) -> Catalog: ...
225
def get_completion_config(self, request: GetCompletionConfigRequest) -> CompletionConfig: ...
226
def add_catalog_attribute(self, request: AddCatalogAttributeRequest) -> AttributesConfig: ...
227
```
228
229
[Catalog Configuration](./catalog-config.md)
230
231
### Analytics and Export
232
233
Analytics data export and metrics collection for business intelligence and reporting.
234
235
```python { .api }
236
class AnalyticsServiceClient:
237
def export_analytics_metrics(self, request: ExportAnalyticsMetricsRequest) -> Operation: ...
238
```
239
240
[Analytics and Export](./analytics-export.md)
241
242
### Advanced Features
243
244
Enhanced capabilities including business rules, serving configurations, and generative AI features.
245
246
```python { .api }
247
class ControlServiceClient:
248
def create_control(self, request: CreateControlRequest) -> Control: ...
249
def list_controls(self, request: ListControlsRequest) -> ListControlsResponse: ...
250
251
class ServingConfigServiceClient:
252
def create_serving_config(self, request: CreateServingConfigRequest) -> ServingConfig: ...
253
def add_control(self, request: AddControlRequest) -> ServingConfig: ...
254
255
class GenerativeQuestionServiceClient:
256
def update_generative_questions_feature_config(self, request: UpdateGenerativeQuestionsFeatureConfigRequest) -> GenerativeQuestionsFeatureConfig: ...
257
```
258
259
[Advanced Features](./advanced-features.md)
260
261
## Common Data Types
262
263
```python { .api }
264
# Core product entity
265
class Product:
266
id: str
267
title: str
268
categories: List[str]
269
price_info: PriceInfo
270
availability: ProductAvailability
271
attributes: Dict[str, CustomAttribute]
272
273
# User interaction event
274
class UserEvent:
275
event_type: str
276
visitor_id: str
277
product_details: List[ProductDetail]
278
purchase_transaction: PurchaseTransaction
279
280
# Pricing information
281
class PriceInfo:
282
price: float
283
currency_code: str
284
cost: float
285
price_effective_time: Timestamp
286
287
# Search request parameters
288
class SearchRequest:
289
placement: str
290
query: str
291
visitor_id: str
292
page_size: int
293
filter: str
294
facet_specs: List[FacetSpec]
295
```
296
297
## Error Handling
298
299
All service methods may raise `google.api_core.exceptions.GoogleAPIError` and its subclasses. Common exceptions include:
300
301
- `NotFound`: Resource not found
302
- `AlreadyExists`: Resource already exists
303
- `InvalidArgument`: Invalid request parameters
304
- `PermissionDenied`: Insufficient permissions
305
- `ResourceExhausted`: Quota exceeded
306
307
```python
308
from google.api_core import exceptions
309
310
try:
311
product = client.get_product(request=request)
312
except exceptions.NotFound:
313
print("Product not found")
314
except exceptions.InvalidArgument as e:
315
print(f"Invalid request: {e}")
316
```