Python client library for Google Cloud Retail API enabling end-to-end personalized recommendation systems
npx @tessl/cli install tessl/pypi-google-cloud-retail@2.5.0Python 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.
pip install google-cloud-retailimport google.cloud.retailFor stable API (recommended for production):
from google.cloud import retailFor specific API versions:
from google.cloud import retail_v2
from google.cloud import retail_v2alpha # Alpha features
from google.cloud import retail_v2beta # Beta featuresFor async clients (optimal for async frameworks like FastAPI, asyncio applications):
from google.cloud.retail import ProductServiceAsyncClient
from google.cloud.retail import SearchServiceAsyncClient
from google.cloud.retail import UserEventServiceAsyncClient
# All service clients have corresponding async variantsfrom google.cloud import retail
# Initialize a product service client
client = retail.ProductServiceClient()
# Create a product
project_id = "your-project-id"
location = "global"
catalog = "default_catalog"
branch = "default_branch"
parent = f"projects/{project_id}/locations/{location}/catalogs/{catalog}/branches/{branch}"
product = retail.Product(
id="product-123",
title="Example Product",
categories=["Electronics", "Computers"],
price_info=retail.PriceInfo(
price=299.99,
currency_code="USD"
)
)
request = retail.CreateProductRequest(
parent=parent,
product=product,
product_id=product.id
)
created_product = client.create_product(request=request)
print(f"Created product: {created_product.name}")
# Search for products
search_client = retail.SearchServiceClient()
search_request = retail.SearchRequest(
placement=f"projects/{project_id}/locations/{location}/catalogs/{catalog}/placements/search",
query="computers",
page_size=10
)
search_response = search_client.search(request=search_request)
for result in search_response.results:
print(f"Found product: {result.product.title}")import asyncio
from google.cloud.retail import ProductServiceAsyncClient
async def manage_products_async():
# Initialize async client
async_client = ProductServiceAsyncClient()
# Create product asynchronously
project_id = "your-project-id"
location = "global"
catalog = "default_catalog"
branch = "default_branch"
parent = f"projects/{project_id}/locations/{location}/catalogs/{catalog}/branches/{branch}"
product = retail.Product(
id="async-product-123",
title="Async Example Product",
categories=["Electronics"],
price_info=retail.PriceInfo(price=199.99, currency_code="USD")
)
request = retail.CreateProductRequest(
parent=parent,
product=product,
product_id=product.id
)
# Await async operation
created_product = await async_client.create_product(request=request)
print(f"Async created product: {created_product.name}")
# Close the async client
await async_client.close()
# Run async function
# asyncio.run(manage_products_async())The Google Cloud Retail API is organized around several core concepts:
The library supports three API versions with different stability levels:
Core product catalog operations including creating, updating, and managing product information, inventory, and fulfillment details.
class ProductServiceClient:
def create_product(self, request: CreateProductRequest) -> Product: ...
def get_product(self, request: GetProductRequest) -> Product: ...
def list_products(self, request: ListProductsRequest) -> ListProductsResponse: ...
def update_product(self, request: UpdateProductRequest) -> Product: ...
def delete_product(self, request: DeleteProductRequest) -> None: ...
def set_inventory(self, request: SetInventoryRequest) -> Operation: ...
def import_products(self, request: ImportProductsRequest) -> Operation: ...
class ProductServiceAsyncClient:
async def create_product(self, request: CreateProductRequest) -> Product: ...
async def get_product(self, request: GetProductRequest) -> Product: ...
async def list_products(self, request: ListProductsRequest) -> ListProductsResponse: ...
async def update_product(self, request: UpdateProductRequest) -> Product: ...
async def delete_product(self, request: DeleteProductRequest) -> None: ...
async def set_inventory(self, request: SetInventoryRequest) -> Operation: ...
async def import_products(self, request: ImportProductsRequest) -> Operation: ...Search functionality with filtering, faceting, ranking, and query auto-completion capabilities.
class SearchServiceClient:
def search(self, request: SearchRequest) -> SearchResponse: ...
class CompletionServiceClient:
def complete_query(self, request: CompleteQueryRequest) -> CompleteQueryResponse: ...Machine learning-based prediction and recommendation services for personalized customer experiences.
class PredictionServiceClient:
def predict(self, request: PredictRequest) -> PredictResponse: ...
class ModelServiceClient:
def create_model(self, request: CreateModelRequest) -> Operation: ...
def tune_model(self, request: TuneModelRequest) -> Operation: ...
def get_model(self, request: GetModelRequest) -> Model: ...Collection and management of user interaction events that power recommendation algorithms and analytics.
class UserEventServiceClient:
def write_user_event(self, request: WriteUserEventRequest) -> UserEvent: ...
def collect_user_event(self, request: CollectUserEventRequest) -> HttpBody: ...
def import_user_events(self, request: ImportUserEventsRequest) -> Operation: ...Management of catalog settings, attributes, branches, and completion configurations.
class CatalogServiceClient:
def list_catalogs(self, request: ListCatalogsRequest) -> ListCatalogsResponse: ...
def update_catalog(self, request: UpdateCatalogRequest) -> Catalog: ...
def get_completion_config(self, request: GetCompletionConfigRequest) -> CompletionConfig: ...
def add_catalog_attribute(self, request: AddCatalogAttributeRequest) -> AttributesConfig: ...Analytics data export and metrics collection for business intelligence and reporting.
class AnalyticsServiceClient:
def export_analytics_metrics(self, request: ExportAnalyticsMetricsRequest) -> Operation: ...Enhanced capabilities including business rules, serving configurations, and generative AI features.
class ControlServiceClient:
def create_control(self, request: CreateControlRequest) -> Control: ...
def list_controls(self, request: ListControlsRequest) -> ListControlsResponse: ...
class ServingConfigServiceClient:
def create_serving_config(self, request: CreateServingConfigRequest) -> ServingConfig: ...
def add_control(self, request: AddControlRequest) -> ServingConfig: ...
class GenerativeQuestionServiceClient:
def update_generative_questions_feature_config(self, request: UpdateGenerativeQuestionsFeatureConfigRequest) -> GenerativeQuestionsFeatureConfig: ...# Core product entity
class Product:
id: str
title: str
categories: List[str]
price_info: PriceInfo
availability: ProductAvailability
attributes: Dict[str, CustomAttribute]
# User interaction event
class UserEvent:
event_type: str
visitor_id: str
product_details: List[ProductDetail]
purchase_transaction: PurchaseTransaction
# Pricing information
class PriceInfo:
price: float
currency_code: str
cost: float
price_effective_time: Timestamp
# Search request parameters
class SearchRequest:
placement: str
query: str
visitor_id: str
page_size: int
filter: str
facet_specs: List[FacetSpec]All service methods may raise google.api_core.exceptions.GoogleAPIError and its subclasses. Common exceptions include:
NotFound: Resource not foundAlreadyExists: Resource already existsInvalidArgument: Invalid request parametersPermissionDenied: Insufficient permissionsResourceExhausted: Quota exceededfrom google.api_core import exceptions
try:
product = client.get_product(request=request)
except exceptions.NotFound:
print("Product not found")
except exceptions.InvalidArgument as e:
print(f"Invalid request: {e}")