Como listar detectores de InfoType integrados

InfoTypes são tipos de dados confidenciais. O Cloud Data Loss Prevention (DLP) é compatível com infoTypes integrados e personalizados. É possível ver todos os infoTypes integrados na referência de infoTypes ou usar a API Cloud DLP para listar todos os infoTypes integrados via programação.

O método infoTypes.list lista todos os infoTypes integrados que são atualmente compatíveis com o Cloud DLP. Cada infoType inclui as seguintes informações:

  • O identificador de infoType (ID), o nome interno do infoType.
  • O nome de exibição do infoType, um nome de infoType legível.
  • Compatibilidade do infoType para operações de inspeção ou de análise de risco.

Exemplos de código

Para listar todos os detectores de infoType integrados:

Console

  1. No Console do Cloud, abra o Cloud DLP.

    Acessar a IU do Cloud DLP

  2. Clique na guia Configuração e em InfoTypes.

  3. Uma tabela contendo todos os detectores de infoType integrados será exibida.

Protocolo

Entrada JSON:

GET https://dlp.googleapis.com/v2/infoTypes?key={YOUR_API_KEY}

A solicitação anterior, quando enviada ao endpoint indicado, retorna uma lista de todos os detectores predefinidos no seguinte formato, em que:

  • [INFOTYPE-NAME] representa o nome do detector de infoType.
  • [INFOTYPE-DISPLAY-NAME] representa o nome de exibição do detector
  • "supportedBy" está definido como "INSPECT", "RISK_ANALYSIS" ou ambos, dependendo de o detector ser compatível com operações de inspeção ou de análise de risco
  • [INFOTYPE-DESCRIPTION] representa a descrição do detector.

Saída JSON:

{
  "infoTypes":[
    {
      "name":"[INFOTYPE-NAME]",
      "displayName":"[INFOTYPE-DISPLAY-NAME]",
      "supportedBy":[
        "INSPECT"
      ],
      "description":"[INFOTYPE-DESCRIPTION]"
    },
    ...
  ]
}

Java


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.InfoTypeDescription;
import com.google.privacy.dlp.v2.ListInfoTypesRequest;
import com.google.privacy.dlp.v2.ListInfoTypesResponse;
import java.io.IOException;

public class InfoTypesList {

  public static void main(String[] args) throws IOException {
    listInfoTypes();
  }

  // Lists the types of sensitive information the DLP API supports.
  public static void listInfoTypes() throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DlpServiceClient dlpClient = DlpServiceClient.create()) {

      // Construct the request to be sent by the client
      ListInfoTypesRequest listInfoTypesRequest =
          ListInfoTypesRequest.newBuilder()
              // Only return infoTypes supported by certain parts of the API.
              // Supported filters are "supported_by=INSPECT" and "supported_by=RISK_ANALYSIS"
              // Defaults to "supported_by=INSPECT"
              .setFilter("supported_by=INSPECT")
              // BCP-47 language code for localized infoType friendly names.
              // Defaults to "en_US"
              .setLanguageCode("en-US")
              .build();

      // Use the client to send the API request.
      ListInfoTypesResponse response = dlpClient.listInfoTypes(listInfoTypesRequest);

      // Parse the response and process the results
      System.out.println("Infotypes found:");
      for (InfoTypeDescription infoTypeDescription : response.getInfoTypesList()) {
        System.out.println("Name : " + infoTypeDescription.getName());
        System.out.println("Display name : " + infoTypeDescription.getDisplayName());
      }
    }
  }
}

Node.js

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlp = new DLP.DlpServiceClient();

// The project ID to run the API call under
// const projectId = 'my-project';

// The BCP-47 language code to use, e.g. 'en-US'
// const languageCode = 'en-US';

// The filter to use
// const filter = 'supported_by=INSPECT'

async function listInfoTypes() {
  const [response] = await dlp.listInfoTypes({
    languageCode: languageCode,
    filter: filter,
  });
  const infoTypes = response.infoTypes;
  console.log('Info types:');
  infoTypes.forEach(infoType => {
    console.log(`\t${infoType.name} (${infoType.displayName})`);
  });
}

listInfoTypes();

Python

def list_info_types(language_code=None, result_filter=None):
    """List types of sensitive information within a category.
    Args:
        language_code: The BCP-47 language code to use, e.g. 'en-US'.
        filter: An optional filter to only return info types supported by
                certain parts of the API. Defaults to "supported_by=INSPECT".
    Returns:
        None; the response from the API is printed to the terminal.
    """
    # Import the client library
    import google.cloud.dlp

    # Instantiate a client.
    dlp = google.cloud.dlp_v2.DlpServiceClient()

    # Make the API call.
    response = dlp.list_info_types(
        request={"parent": language_code, "filter": result_filter}
    )

    # Print the results to the console.
    print("Info types:")
    for info_type in response.info_types:
        print(
            u"{name}: {display_name}".format(
                name=info_type.name, display_name=info_type.display_name
            )
        )

Go

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2"
)

// infoTypes returns the info types in the given language and matching the given filter.
func infoTypes(w io.Writer, languageCode, filter string) error {
	// languageCode := "en-US"
	// filter := "supported_by=INSPECT"
	ctx := context.Background()
	client, err := dlp.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("dlp.NewClient: %v", err)
	}

	req := &dlppb.ListInfoTypesRequest{
		LanguageCode: languageCode,
		Filter:       filter,
	}
	resp, err := client.ListInfoTypes(ctx, req)
	if err != nil {
		return fmt.Errorf("ListInfoTypes: %v", err)
	}
	for _, it := range resp.GetInfoTypes() {
		fmt.Fprintln(w, it.GetName())
	}
	return nil
}

PHP

Ver no GitHub (em inglês) Feedback
/**
 * Lists all Info Types for the Data Loss Prevention (DLP) API.
 */
use Google\Cloud\Dlp\V2\DlpServiceClient;

/** Uncomment and populate these variables in your code */
// $filter = ''; // (Optional) filter to use, empty for ''.
// $languageCode = ''; // (Optional) language code, empty for 'en-US'.

// Instantiate a client.
$dlp = new DlpServiceClient();

// Run request
$response = $dlp->listInfoTypes([
    'languageCode' => $languageCode,
    'filter' => $filter
]);

// Print the results
print('Info Types:' . PHP_EOL);
foreach ($response->getInfoTypes() as $infoType) {
    printf(
        '  %s (%s)' . PHP_EOL,
        $infoType->getDisplayName(),
        $infoType->getName()
    );
}

C#


using System;
using Google.Cloud.Dlp.V2;

public class InfoTypesList
{
    public static ListInfoTypesResponse ListInfoTypes(string languageCode, string filter)
    {
        var dlp = DlpServiceClient.Create();
        var response = dlp.ListInfoTypes(
            new ListInfoTypesRequest
            {
                LanguageCode = languageCode,
                Filter = filter
            });

        // Uncomment to print infotypes
        // Console.WriteLine("Info Types:");
        // foreach (var InfoType in response.InfoTypes)
        // {
        //     Console.WriteLine($"\t{InfoType.Name} ({InfoType.DisplayName})");
        // }

        return response;
    }
}

APIs Explorer

É possível listar detectores de infoType usando as APIs Explorer:

  1. Acesse as APIs Explorer na página de referência da API para infoTypes.list clicando no botão a seguir:

    Abra as APIs Explorer

  2. Desmarque Google OAuth 2.0.

  3. Clique em Executar.

As APIs Explorer enviam uma solicitação ao Cloud DLP, que envia um objeto JSON que contém todos os detectores de infoType compatíveis.