Redacting sensitive data from text

Sensitive Data Protection can redact or obfuscate sensitive data from astring of text. You can feed textual information to the API using JSON overHTTP, or use one of theclient libraries to do so usingseveral popular programming languages.

Theprojects.content.deidentifyAPI takes the following as arguments:

  • A string of text.
  • Placeholder text that will replace any sensitive data detected. In thisexample, the data is replaced with its corresponding infoType.
  • A list of one or moreinfoTypes that you want toredact.

Sensitive Data Protection returns the string with any sensitive data replaced byyour chosen placeholder.

Note: If you want to specify the processing location for a de-identify request,call theprojects.locations.content.deidentify API instead. This APIlets you pass the name of the region where you wantSensitive Data Protection to process the request. For more information, seeSpecifying processing locations.

Example text redaction

For more information about using JSON with the DLP API, seetheJSON quickstart.

Important: The code on this page requires that you first set up a Sensitive Data Protection client. For more information about installing and creating a Sensitive Data Protection client, seeSensitive Data Protection client libraries. (Sending JSON to Sensitive Data Protection REST endpoints does not require a client library.)

C#

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

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

usingSystem;usingSystem.Collections.Generic;usingGoogle.Api.Gax.ResourceNames;usingGoogle.Cloud.Dlp.V2;publicclassDeidentifyWithReplaceInfotypes{publicstaticDeidentifyContentResponseDeidentifyInfo(stringprojectId,stringtext,IEnumerable<InfoType>infoTypes=null){// Instantiate the client.vardlp=DlpServiceClient.Create();// Construct the inspect config by specifying the type of info to be inspected.varinspectConfig=newInspectConfig{InfoTypes={infoTypes??newInfoType[]{newInfoType{Name="EMAIL_ADDRESS"}}}};// Construct the replace info types config.varreplaceInfoTypesConfig=newReplaceWithInfoTypeConfig();// Construct the deidentify config using replace config.vardeidentifyConfig=newDeidentifyConfig{InfoTypeTransformations=newInfoTypeTransformations{Transformations={newInfoTypeTransformations.Types.InfoTypeTransformation{PrimitiveTransformation=newPrimitiveTransformation{ReplaceWithInfoTypeConfig=replaceInfoTypesConfig}}}}};// Construct the request.varrequest=newDeidentifyContentRequest{ParentAsLocationName=newLocationName(projectId,"global"),DeidentifyConfig=deidentifyConfig,InspectConfig=inspectConfig,Item=newContentItem{Value=text}};// Call the API.varresponse=dlp.DeidentifyContent(request);// Check the de-identified content.Console.WriteLine($"De-identified content: {response.Item.Value}");returnresponse;}}

Go

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

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

import("context""fmt""io"dlp"cloud.google.com/go/dlp/apiv2""cloud.google.com/go/dlp/apiv2/dlppb")// deidentifyWithInfotype de-identifies sensitive data by replacing infoType.funcdeidentifyWithInfotype(wio.Writer,projectID,itemstring,infoTypeNames[]string)error{// projectId := "your-project-id"// item := "My email is test@example.com"// infoTypeNames := "[]string{"EMAIL_ADDRESS"}"ctx:=context.Background()// Initialize a client once and reuse it to send multiple requests. Clients// are safe to use across goroutines. When the client is no longer needed,// call the Close method to cleanup its resources.client,err:=dlp.NewClient(ctx)iferr!=nil{returnerr}// Closing the client safely cleans up background resources.deferclient.Close()// Specify the content to be de-identified.input:=&dlppb.ContentItem{DataItem:&dlppb.ContentItem_Value{Value:item,},}// Specify the type of info the inspection will look for.// See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types.varinfoTypes[]*dlppb.InfoTypefor_,it:=rangeinfoTypeNames{infoTypes=append(infoTypes,&dlppb.InfoType{Name:it})}//  Associate de-identification type with info type.transformation:=&dlppb.DeidentifyConfig_InfoTypeTransformations{InfoTypeTransformations:&dlppb.InfoTypeTransformations{Transformations:[]*dlppb.InfoTypeTransformations_InfoTypeTransformation{{PrimitiveTransformation:&dlppb.PrimitiveTransformation{Transformation:&dlppb.PrimitiveTransformation_ReplaceWithInfoTypeConfig{},},},},},}// Construct the de-identification request to be sent by the client.req:=&dlppb.DeidentifyContentRequest{Parent:fmt.Sprintf("projects/%s/locations/global",projectID),InspectConfig:&dlppb.InspectConfig{InfoTypes:infoTypes,},DeidentifyConfig:&dlppb.DeidentifyConfig{Transformation:transformation,},Item:input,}// Send the request.resp,err:=client.DeidentifyContent(ctx,req)iferr!=nil{returnerr}// Print the results.fmt.Fprintf(w,"output : %v",resp.GetItem().GetValue())returnnil}

Java

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

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

importcom.google.cloud.dlp.v2.DlpServiceClient;importcom.google.privacy.dlp.v2.ContentItem;importcom.google.privacy.dlp.v2.DeidentifyConfig;importcom.google.privacy.dlp.v2.DeidentifyContentRequest;importcom.google.privacy.dlp.v2.DeidentifyContentResponse;importcom.google.privacy.dlp.v2.InfoType;importcom.google.privacy.dlp.v2.InfoTypeTransformations;importcom.google.privacy.dlp.v2.InfoTypeTransformations.InfoTypeTransformation;importcom.google.privacy.dlp.v2.InspectConfig;importcom.google.privacy.dlp.v2.LocationName;importcom.google.privacy.dlp.v2.PrimitiveTransformation;importcom.google.privacy.dlp.v2.ReplaceWithInfoTypeConfig;importjava.io.IOException;publicclassDeIdentifyWithInfoType{publicstaticvoidmain(String[]args)throwsException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringtextToInspect="My email is test@example.com";deIdentifyWithInfoType(projectId,textToInspect);}publicstaticvoiddeIdentifyWithInfoType(StringprojectId,StringtextToRedact)throwsIOException{// 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(DlpServiceClientdlp=DlpServiceClient.create()){// Specify the content to be inspected.ContentItemitem=ContentItem.newBuilder().setValue(textToRedact).build();// Specify the type of info the inspection will look for.// See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info typesInfoTypeinfoType=InfoType.newBuilder().setName("EMAIL_ADDRESS").build();InspectConfiginspectConfig=InspectConfig.newBuilder().addInfoTypes(infoType).build();// Specify replacement string to be used for the finding.ReplaceWithInfoTypeConfigreplaceWithInfoTypeConfig=ReplaceWithInfoTypeConfig.newBuilder().build();// Define type of deidentification as replacement with info type.PrimitiveTransformationprimitiveTransformation=PrimitiveTransformation.newBuilder().setReplaceWithInfoTypeConfig(replaceWithInfoTypeConfig).build();// Associate deidentification type with info type.InfoTypeTransformationtransformation=InfoTypeTransformation.newBuilder().addInfoTypes(infoType).setPrimitiveTransformation(primitiveTransformation).build();// Construct the configuration for the Redact request and list all desired transformations.DeidentifyConfigredactConfig=DeidentifyConfig.newBuilder().setInfoTypeTransformations(InfoTypeTransformations.newBuilder().addTransformations(transformation)).build();// Construct the Redact request to be sent by the client.DeidentifyContentRequestrequest=DeidentifyContentRequest.newBuilder().setParent(LocationName.of(projectId,"global").toString()).setItem(item).setDeidentifyConfig(redactConfig).setInspectConfig(inspectConfig).build();// Use the client to send the API request.DeidentifyContentResponseresponse=dlp.deidentifyContent(request);// Parse the response and process resultsSystem.out.println("Text after redaction: "+response.getItem().getValue());}}}

Node.js

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

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

// Imports the Google Cloud Data Loss Prevention libraryconstDLP=require('@google-cloud/dlp');// Instantiates a clientconstdlp=newDLP.DlpServiceClient();// The project ID to run the API call under// const projectId = 'my-project';// The string to deidentify// const string = 'My email is test@example.com';// The string to replace sensitive information with// const infoTypes = [{name: 'EMAIL_ADDRESS'}];asyncfunctiondeIdentifyWithInfoTypeReplace(){// Define type of deidentification as replacement with info type.constprimitiveTransformation={replaceWithInfoTypeConfig:{},};// Associate deidentification type with info type.constdeidentifyConfig={infoTypeTransformations:{transformations:[{primitiveTransformation:primitiveTransformation,},],},};// Specify inspect confiugration using infotypes.constinspectConfig={infoTypes:infoTypes,};// Specify the content to be inspected.constitem={value:string,};// Combine configurations into a request for the service.constrequest={parent:`projects/${projectId}/locations/global`,item,deidentifyConfig,inspectConfig,};// Send the request and receive response from the service.const[response]=awaitdlp.deidentifyContent(request);// Print the resultsconsole.log(`Text after replacement:${response.item.value}`);}deIdentifyWithInfoTypeReplace();

PHP

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

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

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;use Google\Cloud\Dlp\V2\ContentItem;use Google\Cloud\Dlp\V2\DeidentifyConfig;use Google\Cloud\Dlp\V2\DeidentifyContentRequest;use Google\Cloud\Dlp\V2\InfoType;use Google\Cloud\Dlp\V2\InfoTypeTransformations;use Google\Cloud\Dlp\V2\InfoTypeTransformations\InfoTypeTransformation;use Google\Cloud\Dlp\V2\InspectConfig;use Google\Cloud\Dlp\V2\PrimitiveTransformation;use Google\Cloud\Dlp\V2\ReplaceWithInfoTypeConfig;/** * De-identify sensitive data by replacing with infoType. * Uses the Data Loss Prevention API to deidentify sensitive data in a string by replacing it with * the info type. * * @param string $callingProjectId  The Google Cloud project id to use as a parent resource. * @param string $string            The string to deidentify (will be treated as text). */function deidentify_replace_infotype(    // TODO(developer): Replace sample parameters before running the code.    string $callingProjectId,    string $string): void {    // Instantiate a client.    $dlp = new DlpServiceClient();    $parent = "projects/$callingProjectId/locations/global";    // Specify what content you want the service to de-identify.    $content = (new ContentItem())        ->setValue($string);    // The infoTypes of information to mask.    $phoneNumberinfoType = (new InfoType())        ->setName('PHONE_NUMBER');    $personNameinfoType = (new InfoType())        ->setName('PERSON_NAME');    $infoTypes = [$phoneNumberinfoType, $personNameinfoType];    // Create the configuration object.    $inspectConfig = (new InspectConfig())        ->setInfoTypes($infoTypes);    // Create the information transform configuration objects.    $primitiveTransformation = (new PrimitiveTransformation())        ->setReplaceWithInfoTypeConfig(new ReplaceWithInfoTypeConfig());    $infoTypeTransformation = (new InfoTypeTransformation())        ->setPrimitiveTransformation($primitiveTransformation);    $infoTypeTransformations = (new InfoTypeTransformations())        ->setTransformations([$infoTypeTransformation]);    // Create the deidentification configuration object.    $deidentifyConfig = (new DeidentifyConfig())        ->setInfoTypeTransformations($infoTypeTransformations);    // Run request.    $deidentifyContentRequest = (new DeidentifyContentRequest())        ->setParent($parent)        ->setDeidentifyConfig($deidentifyConfig)        ->setItem($content)        ->setInspectConfig($inspectConfig);    $response = $dlp->deidentifyContent($deidentifyContentRequest);    // Print the results.    printf('Text after replace with infotype config: %s', $response->getItem()->getValue());}

Python

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

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

fromtypingimportListimportgoogle.cloud.dlpdefdeidentify_with_replace_infotype(project:str,item:str,info_types:List[str])->None:"""Uses the Data Loss Prevention API to deidentify sensitive data in a    string by replacing it with the info type.    Args:        project: The Google Cloud project id to use as a parent resource.        item: The string to deidentify (will be treated as text).        info_types: A list of strings representing info types to look for.            A full list of info type categories can be fetched from the API.    Returns:        None; the response from the API is printed to the terminal.    """# Instantiate a clientdlp=google.cloud.dlp_v2.DlpServiceClient()# Convert the project id into a full resource id.parent=f"projects/{project}/locations/global"# Construct inspect configuration dictionaryinspect_config={"info_types":[{"name":info_type}forinfo_typeininfo_types]}# Construct deidentify configuration dictionarydeidentify_config={"info_type_transformations":{"transformations":[{"primitive_transformation":{"replace_with_info_type_config":{}}}]}}# Call the APIresponse=dlp.deidentify_content(request={"parent":parent,"deidentify_config":deidentify_config,"inspect_config":inspect_config,"item":{"value":item},})# Print out the results.print(response.item.value)

REST

JSON input:

{"item":{"value":"My email is test@example.com",},"deidentifyConfig":{"infoTypeTransformations":{"transformations":[            {              "primitiveTransformation": {                "replaceWithInfoTypeConfig": {}              }            }]}},"inspectConfig":{"infoTypes":{"name":"EMAIL_ADDRESS"}}}

URL:

https://dlp.googleapis.com/v2/projects/[PROJECT_ID]/content:deidentify

Sensitive Data Protection returns the following after receiving therequest:

JSON output:

{"item":{"value":"My email is [EMAIL_ADDRESS]"},"overview":{"transformedBytes":"16","transformationSummaries":[      {        "infoType":{          "name":"EMAIL_ADDRESS"        },        "transformation":{          "replaceWithInfoTypeConfig":{          }        },        "results":[          {            "count":"1",            "code":"SUCCESS"          }],"transformedBytes":"16"}]}}

You can try this out yourself using the API Explorer embedded here.

Next steps

Redaction is one form ofde-identification. To learn more about how tode-identify content, seeDe-identifying sensitive data in textcontent.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-15 UTC.