Inspect content for sensitive data (v2)

Inspect a text string for sensitive data such as phone numbers and email addresses.

Code sample

Java

To learn how to install and use the client library for Sensitive Data Protection, see Sensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.ContentItem;
import com.google.privacy.dlp.v2.Finding;
import com.google.privacy.dlp.v2.InfoType;
import com.google.privacy.dlp.v2.InspectConfig;
import com.google.privacy.dlp.v2.InspectContentRequest;
import com.google.privacy.dlp.v2.InspectContentResponse;
import com.google.privacy.dlp.v2.Likelihood;
import com.google.privacy.dlp.v2.ProjectName;

public class InspectContent {

  public static void main(String[] args) throws Exception {
    String projectId = "example-project-id";
    inspectContent(projectId);
  }

  public static void inspectContent(String projectId) throws Exception {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (DlpServiceClient client = DlpServiceClient.create()) {
      InfoType phoneInfoType = InfoType.newBuilder().setName("PHONE_NUMBER").build();
      InfoType emailInfoType = InfoType.newBuilder().setName("EMAIL_ADDRESS").build();

      InspectConfig inspectConfig =
          InspectConfig.newBuilder()
              .addInfoTypes(phoneInfoType)
              .addInfoTypes(emailInfoType)
              .setMinLikelihood(Likelihood.LIKELY)
              .setIncludeQuote(true)
              .build();

      ContentItem item =
          ContentItem.newBuilder()
              .setValue("My phone number is 206-555-0123 and email is test@example.com")
              .build();

      InspectContentRequest request =
          InspectContentRequest.newBuilder()
              .setParent(ProjectName.of(projectId).toString())
              .setInspectConfig(inspectConfig)
              .setItem(item)
              .build();

      InspectContentResponse response = client.inspectContent(request);

      System.out.println("Findings found: " + response.getResult().getFindingsCount());
      for (Finding finding : response.getResult().getFindingsList()) {
        System.out.println("Info type: " + finding.getInfoType().getName());
        System.out.println("Quote: " + finding.getQuote());
        System.out.println("Likelihood: " + finding.getLikelihood());
      }
    }
  }
}

Node.js

To learn how to install and use the client library for Sensitive Data Protection, see Sensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

'use strict';

const {DlpServiceClient} = require('@google-cloud/dlp');
const {status} = require('@grpc/grpc-js');

const client = new DlpServiceClient();

/**
 * Inspects content for sensitive information using Cloud Data Loss Prevention.
 *
 * @param {string} projectId - The Google Cloud project ID under which the inspection request runs.
 */
async function inspectContent(projectId) {
  try {
    const parent = `projects/${projectId}`;
    const inspectConfig = {
      infoTypes: [
        {name: 'PHONE_NUMBER'},
        {name: 'EMAIL_ADDRESS'},
      ],
      includeQuote: true,
      minLikelihood: 'POSSIBLE',
    };
    const item = {
      value: 'My email is test@example.com and phone is (555) 019-2834',
    };

    const request = {
      parent,
      inspectConfig,
      item,
    };

    const [response] = await client.inspectContent(request);
    const findings = response.result?.findings || [];

    console.log(`Total findings detected: ${findings.length}`);
    for (const finding of findings) {
      console.log(`Quote: ${finding.quote}`);
      console.log(`InfoType: ${finding.infoType?.name}`);
      console.log(`Likelihood: ${finding.likelihood}`);
    }
  } catch (err) {
    if (err.code === status.INVALID_ARGUMENT) {
      console.error('Invalid argument supplied to the inspection request:', err.details || err.message);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error('Caller lacks required permissions to inspect content:', err.details || err.message);
    } else {
      console.error('Inspection request failed:', err.message || err);
    }
    throw err;
  }
}

module.exports = { inspectContent };

Python

To learn how to install and use the client library for Sensitive Data Protection, see Sensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import google.api_core.exceptions
from google.cloud import dlp_v2

client = dlp_v2.DlpServiceClient()


def inspect_content(project_id: str) -> None:
    """Inspects content for sensitive data.

    Args:
        project_id: The Google Cloud project ID to run the inspection request under.
    """
    parent = f"projects/{project_id}"
    item = dlp_v2.ContentItem(
        value="My phone number is 206-555-0123 and email is user@example.com"
    )
    inspect_config = dlp_v2.InspectConfig(
        info_types=[
            dlp_v2.InfoType(name="PHONE_NUMBER"),
            dlp_v2.InfoType(name="EMAIL_ADDRESS"),
        ],
        min_likelihood=dlp_v2.Likelihood.POSSIBLE,
        include_quote=True,
    )

    try:
        response = client.inspect_content(
            request={
                "parent": parent,
                "inspect_config": inspect_config,
                "item": item,
            }
        )

        findings = response.result.findings
        if not findings:
            print("No findings identified.")
        for finding in findings:
            print(f"Quote: {finding.quote}")
            print(f"Info type: {finding.info_type.name}")
            print(f"Likelihood: {finding.likelihood.name}")
    except google.api_core.exceptions.GoogleAPICallError as error:
        print(f"Failed to inspect content: {error}")

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.