Créer et gérer des ressources produit

Une fois que vous avez créé un ensemble de produits, vous pouvez créer des produits et les ajouter à l'ensemble de produits. Lorsque vous créez un produit, vous devez lui associer un nom à afficher et indiquer à quelle catégorie de produits il appartient. Les catégories actuellement disponibles sont les suivantes : homegoods-v2, apparel-v2, toys-v2, packagedgoods-v1, et general-v1*.

Vous pouvez également fournir une description et des libellés pour votre produit. Les libellés sont des paires clé/valeur décrivant votre produit, comme color=black ou style=mens. Vous pouvez inclure des libellés pour filtrer les résultats d'une recherche de produits et rechercher uniquement certaines images de produits.

Créer un produit

Vous pouvez utiliser une importation en ligne pour créer un produit individuel. Une fois le produit créé, vous pouvez lui ajouter une image de référence, ou l'ajouter à un ou plusieurs ensembles de produits.

API REST et ligne de commande

Avant d'utiliser les données de requête ci-dessous, effectuez les remplacements suivants :

  • project-id : votre ID de projet GCP.
  • location-id : identifiant d'emplacement valide. Les identifiants d'emplacement valides sont : us-west1, us-east1, europe-west1 et asia-east1.
  • display-name : nom à afficher (chaîne de votre choix).
  • product-description : description (chaîne de votre choix).
  • product-category : catégorie de produits valide. Les catégories de produits suivantes sont actuellement disponibles : homegoods-v2, apparel-v2, toys-v2, packagedgoods-v1 et general-v1.
  • productLabels : une ou plusieurs paires clé-valeur associées à un produit. Chaque élément key-string doit être associé à un élément value-string.

Méthode HTTP et URL :

POST https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products

Corps JSON de la requête :

{
  "displayName": "display-name",
  "description": "product-description",
  "productCategory": "product-category",
  "productLabels": [
      {
        "key": "key-string",
        "value": "value-string"
      }
  ]
}

Pour envoyer votre requête, choisissez l'une des options suivantes :

curl

.

Enregistrez le corps de la requête dans un fichier nommé request.json, puis exécutez la commande suivante :

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products

PowerShell

.

Enregistrez le corps de la requête dans un fichier nommé request.json, puis exécutez la commande suivante :

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products" | Select-Object -Expand Content

Exemple de corps de la requête :

{
  "displayName": "sample-product-1234",
  "description": "Athletic shorts",
  "productCategory": "apparel-v2",
  "productLabels": [
      {
        "key": "style",
        "value": "womens"
      },
      {
        "key": "color",
        "value": "blue"
      }
  ]
}

Si la requête aboutit, le serveur affiche un code d'état HTTP 200 OK ainsi que la réponse au format JSON.

Un résultat semblable aux lignes suivantes doit s'afficher. Vous pouvez utiliser l'ID produit (37b9811d308c4e42, dans le cas présent) pour effectuer d'autres opérations sur celui-ci.

{
  "name": "projects/project-id/locations/location-id/products/37b9811d308c4e42",
  "displayName": "sample-product-456",
  "description": "Athletic shorts",
  "productCategory": "apparel-v2",
  "productLabels": [
    {
      "key": "style",
      "value": "womens"
    },
    {
      "key": "color",
      "value": "blue"
    }
  ]
}

C#

private static int CreateProduct(CreateProductOptions opts)
{
    var client = ProductSearchClient.Create();
    var request = new CreateProductRequest
    {
        // A resource that represents Google Cloud Platform location.
        ParentAsLocationName = new LocationName(opts.ProjectID,
                                                opts.ComputeRegion),
        // Set product category and product display name
        Product = new Product
        {
            DisplayName = opts.DisplayName,
            ProductCategory = opts.ProductCategory
        },
        ProductId = opts.ProductID
    };

    // The response is the product with the `name` field populated.
    var product = client.CreateProduct(request);

    Console.WriteLine($"Product name: {product.Name}");
    return 0;
}

Go


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1"
)

// createProduct creates a product.
func createProduct(w io.Writer, projectID string, location string, productID string, productDisplayName string, productCategory string) error {
	ctx := context.Background()
	c, err := vision.NewProductSearchClient(ctx)
	if err != nil {
		return fmt.Errorf("NewProductSearchClient: %v", err)
	}
	defer c.Close()

	req := &visionpb.CreateProductRequest{
		Parent:    fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		ProductId: productID,
		Product: &visionpb.Product{
			DisplayName:     productDisplayName,
			ProductCategory: productCategory,
		},
	}

	resp, err := c.CreateProduct(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateProduct: %v", err)
	}

	fmt.Fprintf(w, "Product name: %s\n", resp.Name)

	return nil
}

Java

/**
 * Create one product.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param productId - Id of the product.
 * @param productDisplayName - Display name of the product.
 * @param productCategory - Category of the product.
 * @throws IOException - on I/O errors.
 */
public static void createProduct(
    String projectId,
    String computeRegion,
    String productId,
    String productDisplayName,
    String productCategory)
    throws IOException {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // A resource that represents Google Cloud Platform location.
    String formattedParent = ProductSearchClient.formatLocationName(projectId, computeRegion);
    // Create a product with the product specification in the region.
    // Multiple labels are also supported.
    Product myProduct =
        Product.newBuilder()
            .setName(productId)
            .setDisplayName(productDisplayName)
            .setProductCategory(productCategory)
            .build();
    Product product = client.createProduct(formattedParent, myProduct, productId);
    // Display the product information
    System.out.println(String.format("Product name: %s", product.getName()));
  }
}

Node.js

async function createProduct() {
  // Imports the Google Cloud client library
  const vision = require('@google-cloud/vision');

  // Creates a client
  const client = new vision.ProductSearchClient();

  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const projectId = 'Your Google Cloud project Id';
  // const location = 'A compute region name';
  // const productId = 'Id of the product';
  // const productDisplayName = 'Display name of the product';
  // const productCategory = 'Catoegory of the product';

  // Resource path that represents Google Cloud Platform location.
  const locationPath = client.locationPath(projectId, location);

  const product = {
    displayName: productDisplayName,
    productCategory: productCategory,
  };

  const request = {
    parent: locationPath,
    product: product,
    productId: productId,
  };

  const [createdProduct] = await client.createProduct(request);
  console.log(`Product name: ${createdProduct.name}`);
}

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;
use Google\Cloud\Vision\V1\Product;

/**
 * Create one product
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 * @param string $productId ID of the product
 * @param string $productDisplayName Display name of the product
 * @param string $productCategory Category of the product
 */
function product_create($projectId, $location, $productId, $productDisplayName, $productCategory)
{
    $client = new ProductSearchClient();

    # a resource that represents Google Cloud Platform location.
    $locationPath = $client->locationName($projectId, $location);

    # create a product with the product specification in the region.
    # set product name and product display name.
    $product = (new Product())
        ->setDisplayName($productDisplayName)
        ->setProductCategory($productCategory);

    # the response is the product with the `name` field populated.
    $response = $client->createProduct($locationPath, $product, ['productId' => $productId]);

    # display the product information.
    printf('Product name: %s' . PHP_EOL, $response->getName());

    $client->close();
}

Python

from google.cloud import vision

def create_product(
        project_id, location, product_id, product_display_name,
        product_category):
    """Create one product.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_id: Id of the product.
        product_display_name: Display name of the product.
        product_category: Category of the product.
    """
    client = vision.ProductSearchClient()

    # A resource that represents Google Cloud Platform location.
    location_path = client.location_path(project=project_id, location=location)

    # Create a product with the product specification in the region.
    # Set product display name and product category.
    product = vision.types.Product(
        display_name=product_display_name,
        product_category=product_category)

    # The response is the product with the `name` field populated.
    response = client.create_product(
        parent=location_path,
        product=product,
        product_id=product_id)

    # Display the product information.
    print('Product name: {}'.format(response.name))

Ruby

require "google/cloud/vision"

def product_search_create_product project_id = "your-project-id"
  client = Google::Cloud::Vision.product_search

  # A resource that represents Google Cloud Platform location.
  location      = "us-west1" # specify a compute region name
  location_path = client.location_path project: project_id, location: location

  # Create a product with the product specification in the region.
  # Set product display name and product category.
  product = {
    display_name:     "sample-product-1234",
    description:      "Athletic shorts",
    product_category: "apparel",
    product_labels:   [{ key: "color", value: "blue" }]
  }

  # The response is the product with the `name` field populated.
  product = client.create_product parent: location_path, product: product

  # Display the product information.
  puts "Product name: #{product.name}"
end

Ajouter un produit à un ensemble de produits

Une fois que vous disposez d'un produit et d'un ensemble de produits, vous pouvez ajouter le produit à l'ensemble.

API REST et ligne de commande

Avant d'utiliser les données de requête ci-dessous, effectuez les remplacements suivants :

  • project-id : votre ID de projet GCP.
  • location-id : identifiant d'emplacement valide. Les identifiants d'emplacement valides sont : us-west1, us-east1, europe-west1 et asia-east1.
  • product-set-id : ID de l'ensemble de produits sur lequel vous souhaitez exécuter l'opération.
  • product-name : nom complet de la ressource du produit. Format :
    • projects/project-id/locations/location-id/products/product-id

Méthode HTTP et URL :

POST https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets/product-set-id:addProduct

Corps JSON de la requête :

{
  "product": "product-name"
}

Pour envoyer votre requête, choisissez l'une des options suivantes :

curl

.

Enregistrez le corps de la requête dans un fichier nommé request.json, puis exécutez la commande suivante :

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets/product-set-id:addProduct

PowerShell

.

Enregistrez le corps de la requête dans un fichier nommé request.json, puis exécutez la commande suivante :

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets/product-set-id:addProduct" | Select-Object -Expand Content

Vous devriez recevoir une réponse JSON de ce type :

{}

C#

private static int AddProductToProductSet(AddProductToProductSetOptions opts)
{
    var client = ProductSearchClient.Create();
    var request = new AddProductToProductSetRequest
    {
        // Get the full path of the products
        ProductAsProductName = new ProductName(opts.ProjectID,
                                              opts.ComputeRegion,
                                              opts.ProductID),
        // Get the full path of the product set.
        ProductSetName = new ProductSetName(opts.ProjectID,
                                           opts.ComputeRegion,
                                           opts.ProductSetId),
    };

    client.AddProductToProductSet(request);

    Console.WriteLine("Product added to product set.");

    return 0;
}

Go


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1"
)

// addProductToProductSet adds a product to a product set.
func addProductToProductSet(w io.Writer, projectID string, location string, productID string, productSetID string) error {
	ctx := context.Background()
	c, err := vision.NewProductSearchClient(ctx)
	if err != nil {
		return fmt.Errorf("NewProductSearchClient: %v", err)
	}
	defer c.Close()

	req := &visionpb.AddProductToProductSetRequest{
		Name:    fmt.Sprintf("projects/%s/locations/%s/productSets/%s", projectID, location, productSetID),
		Product: fmt.Sprintf("projects/%s/locations/%s/products/%s", projectID, location, productID),
	}

	if err = c.AddProductToProductSet(ctx, req); err != nil {
		return fmt.Errorf("NewProductSearchClient: %v", err)
	}

	fmt.Fprintf(w, "Product added to product set.\n")

	return nil
}

Java

/**
 * Add a product to a product set.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param productId - Id of the product.
 * @param productSetId - Id of the product set.
 * @throws IOException - on I/O errors.
 */
public static void addProductToProductSet(
    String projectId, String computeRegion, String productId, String productSetId)
    throws IOException {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // Get the full path of the product set.
    String formattedName =
        ProductSearchClient.formatProductSetName(projectId, computeRegion, productSetId);

    // Get the full path of the product.
    String productPath = ProductName.of(projectId, computeRegion, productId).toString();

    // Add the product to the product set.
    client.addProductToProductSet(formattedName, productPath);

    System.out.println(String.format("Product added to product set."));
  }
}

Node.js

async function addProductToProductSet() {
  const vision = require('@google-cloud/vision');

  const client = new vision.ProductSearchClient();

  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const projectId = 'Your Google Cloud project Id';
  // const location = 'A compute region name';
  // const productId = 'Id of the product';
  // const productSetId = 'Id of the product set';

  const productPath = client.productPath(projectId, location, productId);
  const productSetPath = client.productSetPath(
    projectId,
    location,
    productSetId
  );

  const request = {
    name: productSetPath,
    product: productPath,
  };

  await client.addProductToProductSet(request);
  console.log('Product added to product set.');
}

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;

/**
 * Create a product set
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 * @param string $productId ID of the product
 * @param string $productSetId ID of the product set
 */
function product_set_add_product($projectId, $location, $productId, $productSetId)
{
    $client = new ProductSearchClient();

    # get the name of the product set
    $productSetPath = $client->productSetName($projectId, $location, $productSetId);

    # get the name of the product.
    $productPath = $client->productName($projectId, $location, $productId);

    # add product to product set
    $client->addProductToProductSet($productSetPath, $productPath);
    print('Product added to product set.' . PHP_EOL);

    $client->close();
}

Python

from google.cloud import vision

def add_product_to_product_set(
        project_id, location, product_id, product_set_id):
    """Add a product to a product set.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_id: Id of the product.
        product_set_id: Id of the product set.
    """
    client = vision.ProductSearchClient()

    # Get the full path of the product set.
    product_set_path = client.product_set_path(
        project=project_id, location=location,
        product_set=product_set_id)

    # Get the full path of the product.
    product_path = client.product_path(
        project=project_id, location=location, product=product_id)

    # Add the product to the product set.
    client.add_product_to_product_set(
        name=product_set_path, product=product_path)
    print('Product added to product set.')

Ruby

require "google/cloud/vision"

def product_search_add_product_to_product_set \
    project_id     = "your-project-id",
    location       = "us-west1",
    product_id     = "your-product-id",
    product_set_id = "your-product-set-id"

  client = Google::Cloud::Vision.product_search

  # Get the full path of the product set.
  product_set_path = client.product_set_path project:     project_id,
                                             location:    location,
                                             product_set: product_set_id

  # Get the full path of the product.
  product_path = client.product_path project:  project_id,
                                     location: location,
                                     product:  product_id

  # Add the product to the product set.
  client.add_product_to_product_set name:    product_set_path,
                                    product: product_path

  puts "Product #{product_id} added to product set #{product_set_id}."
end

Supprimer un produit d'un ensemble de produits

Vous pouvez également supprimer un produit existant d'un ensemble de produits.

API REST et ligne de commande

Avant d'utiliser les données de requête ci-dessous, effectuez les remplacements suivants :

  • project-id : votre ID de projet GCP
  • location-id : identifiant d'emplacement valide. Les identifiants d'emplacement valides sont : us-west1, us-east1, europe-west1 et asia-east1.
  • product-set-id : ID de l'ensemble de produits sur lequel vous souhaitez exécuter l'opération.
  • product-name : nom complet de la ressource du produit. Format :
    • projects/project-id/locations/location-id/products/product-id

Méthode HTTP et URL :

POST https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets/product-set-id:removeProduct

Corps JSON de la requête :

{
  "product": "product-name"
}

Pour envoyer votre requête, choisissez l'une des options suivantes :

curl

.

Enregistrez le corps de la requête dans un fichier nommé request.json, puis exécutez la commande suivante :

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets/product-set-id:removeProduct

PowerShell

.

Enregistrez le corps de la requête dans un fichier nommé request.json, puis exécutez la commande suivante :

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets/product-set-id:removeProduct" | Select-Object -Expand Content

Vous devriez recevoir une réponse JSON de ce type :

{}

C#

private static int RemoveProductFromProductSet(RemoveProductFromProductSetOptions opts)
{
    var client = ProductSearchClient.Create();
    var request = new RemoveProductFromProductSetRequest
    {
        // Get the full path of the product.
        ProductAsProductName = new ProductName(opts.ProjectID,
                                              opts.ComputeRegion,
                                              opts.ProductID),
        // Get the full path of the product set.
        ProductSetName = new ProductSetName(opts.ProjectID,
                                           opts.ComputeRegion,
                                            opts.ProductSetId)
    };
    client.RemoveProductFromProductSet(request);
    Console.WriteLine("Product removed from product set.");
    return 0;
}

Go


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1"
)

// removeProductFromProductSet removes a product from a product set.
func removeProductFromProductSet(w io.Writer, projectID string, location string, productID string, productSetID string) error {
	ctx := context.Background()
	c, err := vision.NewProductSearchClient(ctx)
	if err != nil {
		return fmt.Errorf("NewProductSearchClient: %v", err)
	}
	defer c.Close()

	req := &visionpb.RemoveProductFromProductSetRequest{
		Name:    fmt.Sprintf("projects/%s/locations/%s/productSets/%s", projectID, location, productSetID),
		Product: fmt.Sprintf("projects/%s/locations/%s/products/%s", projectID, location, productID),
	}

	if err = c.RemoveProductFromProductSet(ctx, req); err != nil {
		return fmt.Errorf("NewProductSearchClient: %v", err)
	}

	fmt.Fprintf(w, "Product removed from product set.\n")

	return nil
}

Java

/**
 * Remove a product from a product set.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param productId - Id of the product.
 * @param productSetId - Id of the product set.
 * @throws IOException - on I/O errors.
 */
public static void removeProductFromProductSet(
    String projectId, String computeRegion, String productId, String productSetId)
    throws IOException {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // Get the full path of the product set.
    String formattedParent =
        ProductSearchClient.formatProductSetName(projectId, computeRegion, productSetId);

    // Get the full path of the product.
    String formattedName =
        ProductSearchClient.formatProductName(projectId, computeRegion, productId);

    // Remove the product from the product set.
    client.removeProductFromProductSet(formattedParent, formattedName);

    System.out.println(String.format("Product removed from product set."));
  }
}

Node.js

async function removeProductFromProductSet() {
  const vision = require('@google-cloud/vision');

  const client = new vision.ProductSearchClient();

  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  const productSetPath = client.productSetPath(
    projectId,
    location,
    productSetId
  );

  const productPath = client.productPath(projectId, location, productId);

  const request = {
    name: productSetPath,
    product: productPath,
  };

  await client.removeProductFromProductSet(request);
  console.log('Product removed from product set.');
}

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;

/**
 * Create a product set
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 * @param string $productId ID of the product
 * @param string $productSetId ID of the product set
 */
function product_set_remove_product($projectId, $location, $productId, $productSetId)
{
    $client = new ProductSearchClient();

    # get the name of the product set
    $productSetPath = $client->productSetName($projectId, $location, $productSetId);

    # get the name of the product.
    $productPath = $client->productName($projectId, $location, $productId);

    # add product to product set
    $client->removeProductFromProductSet($productSetPath, $productPath);
    print('Product removed product set.' . PHP_EOL);

    $client->close();
}

Python

from google.cloud import vision

def remove_product_from_product_set(
        project_id, location, product_id, product_set_id):
    """Remove a product from a product set.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_id: Id of the product.
        product_set_id: Id of the product set.
    """
    client = vision.ProductSearchClient()

    # Get the full path of the product set.
    product_set_path = client.product_set_path(
        project=project_id, location=location,
        product_set=product_set_id)

    # Get the full path of the product.
    product_path = client.product_path(
        project=project_id, location=location, product=product_id)

    # Remove the product from the product set.
    client.remove_product_from_product_set(
        name=product_set_path, product=product_path)
    print('Product removed from product set.')

Ruby

require "google/cloud/vision"

def product_search_remove_product_from_product_set \
    project_id     = "your-project-id",
    location       = "us-west1",
    product_set_id = "your-product-set-id",
    product_id     = "your-product-id"

  client = Google::Cloud::Vision.product_search

  # Get the full path of the product set.
  product_set_path = client.product_set_path project:     project_id,
                                             location:    location,
                                             product_set: product_set_id

  # Get the full path of the product.
  product_path = client.product_path project:  project_id,
                                     location: location,
                                     product:  product_id

  # Remove the product from the product set.
  client.remove_product_from_product_set name:    product_set_path,
                                         product: product_path

  puts "Product #{product_id} removed from product set #{product_set_id}."
end