제품 리소스 만들기 및 관리

제품 세트를 만들었으면 이제 제품을 만든 후 제품 세트에 추가할 수 있습니다. 제품을 만들 때는 제품의 표시 이름 및 제품 카테고리를 제공해야 합니다. 현재 지원되는 카테고리는 homegoods-v2, apparel-v2, toys-v2, packagedgoods-v1, general-v1입니다.

필요에 따라 제품의 설명 및 라벨을 제공할 수도 있습니다. 라벨은 color=black 또는 style=mens와 같이 제품을 설명하는 키-값 쌍입니다. 라벨을 포함하여 제품 검색의 결과를 제한하면 특정 제품의 이미지만 검색할 수 있습니다.

제품 만들기

온라인 가져오기를 사용하여 개별 상품을 만들 수 있습니다. 상품을 만든 다음 상품에 참조 이미지를 추가하거나 상품을 하나 이상의 상품 세트에 추가할 수 있습니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트 ID입니다.
  • LOCATION_ID: 유효한 위치 식별자입니다. 유효한 위치 식별자는 us-west1, us-east1, europe-west1, asia-east1입니다.
  • DISPLAY_NAME: 선택한 문자열 표시 이름입니다.
  • PRODUCT_DESCRIPTION: 선택한 문자열 설명입니다.
  • product-category: 유효한 제품 카테고리입니다. 현재 사용할 수 있는 제품 카테고리는 homegoods-v2, apparel-v2, toys-v2, packagedgoods-v1, general-v1입니다.
  • productLabels: 제품과 연결된 하나 이상의 키-값 쌍입니다. 각 KEY_STRING에는 연결된 VALUE_STRING이 있어야 합니다.

HTTP 메서드 및 URL:

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

JSON 요청 본문:

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

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

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

요청 본문 예시:

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

요청이 성공하면 서버가 200 OK HTTP 상태 코드와 응답을 JSON 형식으로 반환합니다.

다음과 비슷한 출력이 표시됩니다. 제품 ID(이 경우 37b9811d308c4e42)를 사용하여 제품에 다른 작업을 수행할 수 있습니다.

{
  "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"
    }
  ]
}

Go

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Go API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	"cloud.google.com/go/vision/v2/apiv1/visionpb"
)

// 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: %w", 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: %w", err)
	}

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

	return nil
}

Java

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Java API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

/**
 * 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 = LocationName.format(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

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Node.js API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

// Creates a client
const client = new vision.ProductSearchClient();
async function createProduct() {
  /**
   * 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}`);
}
createProduct();

Python

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Python API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import vision
from google.protobuf import field_mask_pb2 as field_mask

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 = f"projects/{project_id}/locations/{location}"

    # Create a product with the product specification in the region.
    # Set product display name and product category.
    product = vision.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(f"Product name: {response.name}")

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 다음 .NET용 Vision API 제품 검색 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 Vision API 제품 검색 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 Vision API 제품 검색 참조 문서를 참조하세요.

제품 세트에 제품 추가

제품 및 제품 세트가 있으면 제품을 제품 세트에 추가할 수 있습니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트 ID입니다.
  • LOCATION_ID: 유효한 위치 식별자입니다. 유효한 위치 식별자는 us-west1, us-east1, europe-west1, asia-east1입니다.
  • PRODUCT_SET_ID: 작업을 실행할 제품 세트의 ID입니다.
  • PRODUCT_NAME: 제품의 전체 리소스 이름입니다. 형식:
    • projects/PROJECT_ID/locations/LOCATION_ID/products/PRODUCT_ID

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
  "product": "product-name"
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
-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

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

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

다음과 비슷한 JSON 응답이 표시됩니다.

{}

Go

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Go API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	"cloud.google.com/go/vision/v2/apiv1/visionpb"
)

// 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: %w", 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: %w", err)
	}

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

	return nil
}

Java

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Java API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


/**
 * 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 = ProductSetName.format(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

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Node.js API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

const vision = require('@google-cloud/vision');
const client = new vision.ProductSearchClient();

async function addProductToProductSet() {
  /**
   * 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.');
}
addProductToProductSet();

Python

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Python API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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.")

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 다음 .NET용 Vision API 제품 검색 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 Vision API 제품 검색 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 Vision API 제품 검색 참조 문서를 참조하세요.

제품 세트에서 제품 삭제

제품 세트에서 기존 제품을 삭제할 수도 있습니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트 ID입니다.
  • LOCATION_ID: 유효한 위치 식별자입니다. 유효한 위치 식별자는 us-west1, us-east1, europe-west1, asia-east1입니다.
  • PRODUCT_SET_ID: 작업을 실행할 제품 세트의 ID입니다.
  • PRODUCT_NAME: 제품의 전체 리소스 이름입니다. 형식:
    • projects/PROJECT_ID/locations/LOCATION_ID/products/PRODUCT_ID

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
  "product": "product-name"
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
-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

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

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

다음과 비슷한 JSON 응답이 표시됩니다.

{}

Go

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Go API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	"cloud.google.com/go/vision/v2/apiv1/visionpb"
)

// 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: %w", 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: %w", err)
	}

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

	return nil
}

Java

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Java API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


/**
 * 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 = ProductSetName.format(projectId, computeRegion, productSetId);

    // Get the full path of the product.
    String formattedName = ProductName.format(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

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Node.js API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

const vision = require('@google-cloud/vision');

const client = new vision.ProductSearchClient();

async function removeProductFromProductSet() {
  /**
   * 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.');
}
removeProductFromProductSet();

Python

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Python API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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.")

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 다음 .NET용 Vision API 제품 검색 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 Vision API 제품 검색 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 Vision API 제품 검색 참조 문서를 참조하세요.