Google Retail API Client
A TypeScript client for the Google Retail API, providing easy access to search, recommendations, and predictions.
Features
- 🔍 Full Retail Search API support
- 🎯 Product recommendations
- 🔮 Predictions
- 📦 TypeScript support
- 🔐 Service Account authentication
- 🚀 Promise-based API
Installation
npm install google-retail-api-client
Authentication
This library requires a Google Cloud Service Account with appropriate permissions for the Retail API.
Getting Service Account Credentials
- Go to the Google Cloud Console
- Navigate to "IAM & Admin" > "Service Accounts"
- Click "Create Service Account"
- Grant the service account the following roles:
roles/retail.admin
or appropriate Retail API roles
- Create and download the JSON key file
- The JSON file will contain your credentials in this format:
{
"type": "service_account",
"project_id": "your-project-id",
"private_key_id": "your-private-key-id",
"private_key": "your-private-key",
"client_email": "your-client-email",
"client_id": "your-client-id"
}
Usage
Initializing the Client
import { RetailClient } from "google-retail-api-client";
const client = new RetailClient({
credentials: {
type: "service_account",
project_id: "your-project-id",
private_key: "your-private-key",
client_email: "your-client-email",
},
location: "global",
catalogId: "default_catalog",
});
Searching Products
const results = await client.search({
query: "blue jeans",
pageSize: 10,
});
const filteredResults = await client.search({
query: "t-shirt",
filter: "price.value > 20 AND price.value < 50",
pageSize: 20,
offset: 0,
orderBy: "price desc",
});
Getting Recommendations
const recommendations = await client.getPredictions({
productId: "product123",
pageSize: 12,
filter: "availability: IN_STOCK",
});
const homePageRecommendations = await client.getPredictions({
pageSize: 12,
eventType: "home-page-view",
});
Error Handling
The client throws RetailApiError
for any API or authentication errors:
try {
const results = await client.search({ query: "shoes" });
} catch (error) {
if (error instanceof RetailApiError) {
console.error(error.message);
console.error(error.code);
console.error(error.details);
}
}
Security Considerations
⚠️ Important Security Notes:
- Never commit service account credentials to version control
- Store credentials securely using environment variables or secret management systems
- Follow the principle of least privilege when assigning roles to the service account
- Regularly rotate service account keys
- Never expose service account credentials in client-side/browser code
API Reference
For detailed API documentation, please refer to the Google Retail API Documentation.
License
MIT