Skip to content

About

Skyflow SDK for the Go programming language.

Topics

Resources

Contributing

Security policy

Stars

20 stars

Watchers

14 watching

Forks

Repository files navigation

Description

This is the current, recommended version of the Skyflow SDK. V2.2.0 brings flexible auth, multi-vault support, native data types, rich error diagnostics, and the Detect APIs for de-identifying and re-identifying strings and files.

⚠️ skyflow-go v1 reached End of Life on October 31, 2026 and is no longer supported. It will not receive any further security patches, bug fixes, or updates. Please upgrade to the latest skyflow-go v2 Latest skyflow-go v2 release using the Migration Guide.

The Skyflow Go SDK is designed to help with integrating Skyflow into a go backend.

Note

This README covers SkyVault vaults (module github.com/skyflowapi/skyflow-go/v2). For FlowVault vaults, use the FlowVault SDK (module github.com/skyflowapi/skyflow-go/flowvault): see the FlowVault README.

CI GitHub release License

Table of Contents

Overview

Important

This readme documents SDK version 2. For version 1 see the v1 README. For more information on how to migrate see docs/migrate_to_v2.md.

  • Authenticate using a Skyflow service account and generate bearer tokens for secure access.

  • Perform Vault API operations such as inserting, retrieving, and tokenizing sensitive data with ease.

  • Invoke connections to third-party APIs without directly handling sensitive data, ensuring compliance and data protection.

  • De-identify and re-identify sensitive data in text and files, and screen text with guardrails, using Detect.

  • See the v1 README for documentation related to v1.

Install

Requirements

  • go 1.26.11 and above

Configuration

Make sure your project is using Go Modules (it will have a go.mod file in its root if it already is):

go mod init

Then, reference skyflow-go in a Go program with import:

import (
"github.com/skyflowapi/skyflow-go/v2/client"
"github.com/skyflowapi/skyflow-go/v2/utils/common"
"github.com/skyflowapi/skyflow-go/v2/utils/logger"
)

Alternatively, go get <package_name> can also be used to download the required dependencies

Quickstart

Get started quickly with the essential steps: authenticate, initialize the client, and perform a basic vault operation. This section provides a minimal setup to help you integrate the SDK efficiently.

Authenticate

You can use an API key or a bearer token to directly authenticate and authorize requests with the SDK. Use API keys for long-term service authentication. Use bearer tokens for optimal security.

API Key

skyflowCredentials := common.Credentials{ApiKey: "<YOUR_API_KEY>"} // Replace <API_KEY> with your actual API key

Bearer Token (static)

skyflowCredentials := common.Credentials{Token: "<BEARER_TOKEN>"}

For authenticating via generated bearer tokens including support for scoped tokens, context-aware access tokens, and more, refer to the Authenticate with bearer tokens section.

Initialize the client

To get started, you must first initialize the skyflow client. While initializing the skyflow client, you can specify different types of credentials.

import (
	"context"
	"fmt"
	"github.com/skyflowapi/skyflow-go/v2/client"
	"github.com/skyflowapi/skyflow-go/v2/utils/common"
	"github.com/skyflowapi/skyflow-go/v2/utils/logger"
)

func main() {
        creds := common.Credentials{
              Path: "<YOUR_CREDENTIALS_FILE_PATH_1>"
          }    // Replace with the path to the credentials file
        vaultConfig1 := common.VaultConfig{
            VaultId: "<VAULT_ID1>", 
            ClusterId: "<CLUSTER_ID1>", 
            Env: common.DEV, 
            Credentials: creds
            } // Replace with the Cluster and Vault ID of the first vault, Set the environment (e.g., DEV, STAGE, PROD)
        var arr []common.VaultConfig
        arr = append(arr, vaultConfig1)
       // Create a Skyflow client and add vault configurations
        skyflowClient, err := client.NewSkyflow(
          client.WithVaults(arr...), // Add the first vault configuration
          client.WithCredentials(common.Credentials{
            Token: "<BEARER_TOKEN>"
          }), // Add the first vault configuration
          client.WithLogLevel(logger.DEBUG), // Enable debugging for detailed logs
	)
}	

See docs/advanced_initialization.md for advanced initialization examples including multiple vaults and different credential types.

Insert data into the vault, get tokens back

To insert data into your vault, use the Insert method. The InsertRequest struct creates an insert request, which includes the values to be inserted as a list of records. Below is a simple example to get started. For advanced options, check out Insert data into the vault section.

/**
 * This example demonstrates how to insert sensitive data (e.g., card information) into a Skyflow vault using the Skyflow client.
 *
 * 1. Initializes the Skyflow client.
 * 2. Prepares a record with sensitive data (e.g., card number and cardholder name).
 * 3. Creates an insert request for inserting the data into the Skyflow vault.
 * 4. Prints the response of the insert operation.
 */
package main

import (
  "context"
  "fmt"
  "github.com/skyflowapi/skyflow-go/v2/client"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
  "github.com/skyflowapi/skyflow-go/v2/utils/logger"
)

func main() {
  // Initialize Skyflow client

  // Step 1: Initialize data to be inserted into the Skyflow vault
  ctx := context.TODO() // Create a context for the operation.

  // Create a slice to hold the data records for insertion.
  values := make([]map[string]interface{}, 0)

  // Add a record with sensitive fields (e.g., card number and cardholder name).
  values = append(values, map[string]interface{}{
    "card_number":     "4111111111111111",// Replace with actual card number (sensitive data)
    "cardholder_name": "john doe",         // Replace with the actual cardholder name  (sensitive data)
  })
  insertRequest := common.InsertRequest{
    Table:  "table1", // Specify the table in the vault where the data will be inserted
    Values: values,   // Attach the data (records) to be inserted
  }
  insertOptions := common.InsertOptions{
    ReturnTokens:    true,  // Request tokenized values to be returned in the response.
  }
  // Step 2: Obtain a Vault service instance for performing operations.
  service, serviceError := skyflowClient.Vault("9f27764a10f7946fe56b3258e117") // Replace the vault ID "9f27764a10f7946fe56b3258e117" with your actual Skyflow vault ID
  if serviceError != nil {
    // Handle errors while getting the vault service instance.
    fmt.Println("Error obtaining Vault service:", serviceError)
  }

  // Step 3: Perform the insert operation using the Skyflow client
  insert, err4 := service.Insert(ctx, insertRequest, insertOptions)
  if err4 != nil {
    // Step 4: Handle any errors that occur during the insert operation.
    fmt.Println("Error occurred: ", *err4)
  } else {
    // Step 5: Print the response from the insert operation.
    fmt.Println("Insert Response: ", insert)
  }
}

Skyflow returns tokens for the record that was just inserted.

Insert Response: {
	"InsertedFields": [{
		"card_number": "5484-7829-1702-9110",
		"RequestIndex": "0",
		"SkyflowId": "9fac9201-7b8a-4446-93f8-5244e1213bd1",
		"cardholder_name": "b2308e2a-c1f5-469b-97b7-1f193159399b",
	}],
	"Errors": []
}

Upgrade from v1 to v2

Upgrade from skyflow-go v1 using the dedicated guide in docs/migrate_to_v2.md.

Vault

The Vault module performs operations on the vault, including inserting records, detokenizing tokens, and retrieving tokens associated with a SkyflowId.

Insert data into the vault

Apart from using the Insert method to insert data into your vault covered in Quickstart, you can also specify options in InsertRequest, such as returning tokenized data, upserting records, or continuing the operation in case of errors.

Construct an insert request

package main

import (
  "context"
  "fmt"
  "github.com/skyflowapi/skyflow-go/v2/client"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
  "github.com/skyflowapi/skyflow-go/v2/utils/logger"
)
/**
 * Example program to demonstrate inserting data into a Skyflow vault, along with corresponding InsertRequest schema.
 *
 */

func main() {
  //  Initialise Skyflow client

  // Step 1: Prepare the data to be inserted into the Skyflow vault.
  ctx := context.TODO() // Create a context for the operation.

  // Create the first record with field names and their respective values
  values := make([]map[string]interface{}, 0)

  // Add the first record with field names and their respective values.
  values = append(values, map[string]interface{}{
    "<FIELD_NAME1_1>": "<VALUE_1>", // Replace with actual field name and value.
  })

  // Create the second record with field names and their respective values
  values = append(values, map[string]interface{}{
    "<FIELD_NAME_2>": "<VALUE_1>", // Replace with actual field name and value.
  })
  // Step 2: Build an InsertRequest object with the table name and the data to insert
  insertRequest := common.InsertRequest{
    Table:  "<TABLE_NAME>", // Replace with the actual table name in your Skyflow vault.
    Values: values,         // Attach the data to be inserted.
  }
  
  // Step 3: Use the Skyflow client to perform the insert operation
  //Obtain a Vault service instance for performing operations. 
  service, err := skyflowClient.Vault("<VAULT_ID>") // Replace <VAULT_ID> with your actual vault ID
  if err != nil {
    // Handle errors while getting the vault service instance.
    fmt.Println("Error obtaining Vault service:", err)
  }
  // Step 4: Perform the insert operation using the Vault service.
  insert, errs := service.Insert(ctx, insertRequest)
  if errs != nil {
    // Handle any exceptions that occur during the insert operation
    fmt.Println("Error occurred while inserting data: ", *err4)
  } else {
    // Print the response from the insert operation
    fmt.Println("Insert Response: ", insert)
  }
}

InsertOptions fields:

Field Type Description
ReturnTokens bool Return tokens for the inserted records.
Upsert string Column name to use for upsert (must be unique in schema).
ContinueOnError bool Continue inserting remaining records if one fails.
Homogeneous bool Set to true when all records in the batch have identical fields; enables a more efficient bulk-insert path.
TokenMode BYOT Bring-Your-Own-Token mode: ENABLE, DISABLE, ENABLE_STRICT.
Tokens []map[string]interface{} BYOT tokens to associate with inserted records.
CustomHeaders map[CustomHeaderKey]string Request-level custom headers for this call.

Insert example with ContinueOnError option

Set the ContinueOnError flag to true to allow insert operations to proceed despite encountering partial errors.

Tip

See the full example in the samples directory: insert_records.go

/**
 * This example demonstrates how to insert multiple records into a Skyflow vault using the Skyflow client.
 *
 * 1. Initializes the Skyflow client.
 * 2. Prepares multiple records with sensitive data (e.g., card number and cardholder name).
 * 3. Creates an insert request with the records to insert into the Skyflow vault.
 * 4. Specifies options to continue on error and return tokens.
 * 5. Prints the response of the insert operation.
 */
package main

import (
  "context"
  "fmt"
  "github.com/skyflowapi/skyflow-go/v2/client"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
  "github.com/skyflowapi/skyflow-go/v2/utils/logger"
)

func main() {
  // Initialize Skyflow client
  // Step 1: Initialize a list to hold the data records to be inserted into the vault
    ctx := context.TODO() // Create a context for the operation.

  // Create a slice to hold the data records for insertion.
  insertData := make([]map[string]interface{}, 0)

  // Step 2: Create the first record with card number and cardholder name
  insertRecord1 := map[string]interface{}{
    "card_number":     "4111111111111111", // Replace with the actual card number.
    "cardholder_name": "john doe",         // Replace with the actual cardholder name.
  }
  // Step 3: Create the second record with card number and cardholder name
    insertRecord2 := map[string]interface{}{
      "card_number":     "42222222222222222", // Replace with the actual card number.
      "cardholder_name": "john doe",         // Replace with the actual cardholder name.
    }
  // Step 4: Add the records to the insertData map
  insertData = append(insertData, insertRecord1)
  insertData = append(insertData, insertRecord2)
  
  // Step 5: Build the InsertRequest object with the data records to insert
   insertRequest := common.InsertRequest{
     Table:  "table1", // Replace with the actual table name in your Skyflow vault.
     Values: insertData,   // Attach the prepared data for insertion.
   }
  // Step 6: Create insert options to support the continue on error 
   insertOptions := common.InsertOptions{
     ContinueOnError: true,  // Specify to continue inserting records even if an error occurs for some records
     ReturnTokens:    true,  // Specify if tokens should be returned upon successful insertion
   }
   
  // Step 7: Obtain a Vault service instance for performing operations.
  service, serviceError := skyflowClient.Vault("9f27764a10f7946fe56b3258e117") // Replace with your actual vault ID.
  if serviceError != nil {
    // Handle errors while getting the vault service instance.
    fmt.Println("Error obtaining Vault service:", serviceError)

  }
  
  // Step 8: Perform the insert operation using the Vault service.
  insert, err4 := service.Insert(ctx, insertRequest , insertOptions)
  if err4 != nil {
    // Handle any errors that occur during the insert operation.
    fmt.Println("Error occurred: ", *err4)
  } else {
    // Print the response from the insert operation.
    fmt.Println("Insert Response: ", insert)
  }
}

Sample response :

{
  "InsertedFields": [{
    "card_number": "5484-7829-1702-9110",
    "RequestIndex": "0",
    "SkyflowId": "9fac9201-7b8a-4446-93f8-5244e1213bd1",
    "cardholder_name": "b2308e2a-c1f5-469b-97b7-1f193159399b",
  }],
  "Errors": [{
    "RequestIndex": "1",
    "error": "Insert failed. Column card_numbe is invalid. Specify a valid column."
  }]
}

Upsert request

Turn an insert into an update-or-insert operation using the upsert option. The vault checks for an existing record with the same value in the specified column. If a match exists, the record updates; otherwise, a new record inserts.

Note

The column used for upsert must have the unique constraint configured in the vault.

package main

import (
  "context"
  "fmt"
  "github.com/skyflowapi/skyflow-go/v2/client"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
  "github.com/skyflowapi/skyflow-go/v2/utils/logger"
)

/**
 * This example demonstrates how to insert or upsert a record into a Skyflow vault using the Skyflow client, with the option to return tokens.
 *
 * 1. Initializes the Skyflow client.
 * 2. Prepares a record to insert or upsert (e.g., cardholder name).
 * 3. Creates an insert request with the data to be inserted or upserted into the Skyflow vault.
 * 4. Specifies the field (cardholder_name) for upsert operations.
 * 5. Prints the response of the insert or upsert operation.
 */

func main() {
  // Initialize Skyflow client
  // Step 1: Initialize a list to hold the data records for the insert/upsert operation
  upsertData := make([]map[string]interface{}, 0)
  ctx := context.TODO()

  // Step 2: Create a record with the field 'cardholder_name' to insert or upsert
  upsertRecord := map[string]interface{}{
    "cardholder_name": "jane doe", // Replace with the actual cardholder name
  }
  // Step 3: Add the record to the upsertData list
  upsertData = append(upsertData, upsertRecord)

  // Step 4: Build the InsertRequest object with the upsertData
    insertRequest := common.InsertRequest{
      Table:  "table1", // Specify the table in the vault where data will be inserted/upserted
      Values: upsertData, // Attach the data records to be inserted/upserted
    }
   // Step 5: Create the insert options object 
  insertOptions := common.InsertOptions{
    ReturnTokens: true, // Specify if tokens should be returned upon successful operation
    Upsert: "cardholder_name", // Specify the field to be used for upsert operations (e.g., cardholder_name)
  }

  // Step 5: Obtain a Vault service instance for performing operations.
  service, serviceError := skyflowClient.Vault("<VAULT_ID>")
  if serviceError != nil {
    fmt.Println("Error obtaining Vault service:", serviceError)
  }

  // Step 6: Perform the insert/upsert operation using the Skyflow client
  insert, err4 := service.Insert(ctx, insertRequest, insertOptions)
  if err4 != nil {
    fmt.Println("Error occurred", *err4)
  } else {
    fmt.Println("RESPONSE:", insert)
  }
}

Sample response :

{
  "InsertedFields": [{
    "SkyflowId": "9fac9201-7b8a-4446-93f8-5244e1213bd1",
    "cardholder_name": "73ce45ce-20fd-490e-9310-c1d4f603ee83"
  }],
  "Errors": []
}

Detokenize

To retrieve tokens from your vault, use the Detokenize method. The DetokenizeRequest struct requires a list of detokenization data as input. Additionally, you can provide optional parameters, such as the redaction type and the option to continue on error.

Construct a detokenize request

package vaultapi

import (
  "context"
  "fmt"
  "github.com/skyflowapi/skyflow-go/v2/client"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
  "github.com/skyflowapi/skyflow-go/v2/utils/logger"
)
/**
 * This example demonstrates how to detokenize sensitive data from tokens stored in a Skyflow vault, along with corresponding DetokenizeRequest schema.
 *
 */

func main() {
  // Configure the vaults and Skyflow client
  ctx := context.TODO() // Create a context for the detokenization operation.

  // Step 1: Create the DetokenizeRequest with tokens and per-token redaction types
  detokenizeRequest := common.DetokenizeRequest{
    DetokenizeData: []common.DetokenizeData{
      {Token: "<TOKEN1>", RedactionType: common.PLAIN_TEXT},
      {Token: "<TOKEN2>", RedactionType: common.PLAIN_TEXT},
    },
  }
  // Step 2: Create the DetokenizeOptions object with ContinueOnError
  options := common.DetokenizeOptions{
    ContinueOnError: true, // Continue even if one token cannot be detokenized.
  }
  
  // Step 3: Obtain a Vault service instance for performing operations.
  service, serviceError := skyflowClient.Vault("<VAULT_ID>") // Replace <VAULT_ID> with the specific vault ID.
  if serviceError != nil {
    // Handle errors while getting the vault service instance.
    fmt.Println("Error obtaining Vault service:", serviceError)

  }
  // Step 4: Call the Skyflow vault to detokenize the provided tokens
  res, err := service.Detokenize(ctx, detokenizeRequest, options)
  if err != nil {
    // Step 5: Handle any errors that occur during the detokenization process.
    fmt.Println("Error occurred ", err)
  } else {
    // Step 6: Print the detokenization response.
    fmt.Println("RESPONSE: ", res)
  }
}

DetokenizeOptions fields:

Field Type Description
ContinueOnError bool Continue detokenizing if one token fails. Defaults to true.
DownloadUrl bool Return a pre-signed download URL for file-type tokens instead of inline data.
CustomHeaders map[CustomHeaderKey]string Request-level custom headers for this call.

Notes:

  • RedactionType is set per token on DetokenizeData, not on the request.
  • ContinueOnError defaults to true.

Tip

See the full example in the samples directory: detokenize.go

package vaultapi

import (
  "context"
  "fmt"
  "github.com/skyflowapi/skyflow-go/v2/client"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
  "github.com/skyflowapi/skyflow-go/v2/utils/logger"
)
/**
 * This example demonstrates how to detokenize sensitive data from tokens stored in a Skyflow vault.
 *
 * 1. Initializes the Skyflow client.
 * 2. Creates a list of tokens (e.g., credit card tokens) that represent the sensitive data.
 * 3. Builds a detokenization request using the provided tokens and specifies how the redacted data should be returned.
 * 4. Calls the Skyflow vault to detokenize the tokens and retrieves the detokenized data.
 * 5. Prints the detokenization response, which contains the detokenized values or errors.
 */
func main() {
  // Initialize Skyflow client
  ctx := context.TODO() // Create a context for the detokenization operation.

  // Step 1: Create the DetokenizeRequest with tokens and per-token redaction types.
  detokenizeRequest := common.DetokenizeRequest{
    DetokenizeData: []common.DetokenizeData{
      {Token: "9738-1683-0486-1480", RedactionType: common.PLAIN_TEXT},
      {Token: "6184-6357-8409-6668", RedactionType: common.PLAIN_TEXT},
      {Token: "4914-9088-2814-3840", RedactionType: common.PLAIN_TEXT},
    },
  }
  // Step 3: Obtain a Vault service instance for performing operations.
  service, serviceError := skyflowClient.Vault("9f27764a10f7946fe56b3258e117")             // Replace "9f27764a10f7946fe56b3258e117" with your actual Skyflow vault ID
  if serviceError != nil {
    // Handle errors while getting the vault service instance.
    fmt.Println("Error obtaining Vault service:", serviceError)

  }
  options := common.DetokenizeOptions{
    ContinueOnError: false, // Continue even if one token cannot be detokenized.
  }
  // Step 4: Perform the detokenization operation using the Vault service.
  res, errDetokenize := service.Detokenize(ctx, detokenizeRequest, options)
  
  if errDetokenize != nil {
    // Step 5: Handle any errors that occur during the detokenization process.
    fmt.Println("Error occurred: ", errDetokenize)
  } else {
    // Step 6: Print the detokenization response.
    fmt.Println("RESPONSE: ", res)
  }
}

Sample response:

{
  "DetokenizedFields": [{
    "token": "9738-1683-0486-1480",
    "value": "4111111111111115",
    "type": "STRING"
  }, {
    "token": "6184-6357-8409-6668",
    "value": "4111111111111119",
    "type": "STRING"
  }, {
    "token": "4914-9088-2814-3840",
    "value": "4111111111111118",
    "type": "STRING"
  }],
  "Errors": []
}

Tip

See the full example with ContinueOnError in the samples directory: detokenize.go

package vaultapi

import (
  "context"
  "fmt"
  "github.com/skyflowapi/skyflow-go/v2/client"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
  "github.com/skyflowapi/skyflow-go/v2/utils/logger"
)
/**
 * This example demonstrates how to detokenize sensitive data (e.g., credit card numbers) from tokens in a Skyflow vault.
 *
 * 1. Initializes the Skyflow client.
 * 2. Creates a list of tokens (e.g., credit card tokens) to be detokenized.
 * 3. Builds a detokenization request with the tokens and specifies the redaction type for the detokenized data.
 * 4. Calls the Skyflow vault to detokenize the tokens and retrieves the detokenized data.
 * 5. Prints the detokenization response, which includes the detokenized values or errors.
 */
func main() {
  // Initialize Skyflow client
  // Step 1: Create the DetokenizeRequest with tokens and per-token redaction types
  request := common.DetokenizeRequest{
    DetokenizeData: []common.DetokenizeData{
      {Token: "9738-1683-0486-1480", RedactionType: common.PLAIN_TEXT},
      {Token: "6184-6357-8409-6668", RedactionType: common.PLAIN_TEXT},
      {Token: "4914-9088-2814-3840", RedactionType: common.PLAIN_TEXT},
    },
  }
  options := common.DetokenizeOptions{
    ContinueOnError: false, // Continue even if one token cannot be detokenized.
  }
  ctx := context.TODO() // Create a context for the detokenization operation.

  // Step 3: Obtain a Vault service instance for performing operations.
  service, serviceError := skyflowClient.Vault("9f27764a10f7946fe56b3258e117")             // Replace "9f27764a10f7946fe56b3258e117" with your actual Skyflow vault ID
  
  if serviceError != nil {
    // Handle errors while getting the vault service instance.
    fmt.Println("Error obtaining Vault service:", serviceError)

  }
  
  // Step 4: Call the Skyflow vault to detokenize the provided tokens
  res, errDetokenize := service.Detokenize(ctx, request, options)
  if errDetokenize != nil {
    // Step 5: Handle any errors that occur during the detokenization process.
    fmt.Println("Error occurred ", errDetokenize)
  } else {
    // Step 6: Print the detokenization response, which contains the detokenized data or errors 
	  fmt.Println("RESPONSE: ", res)
  }
}

Sample response:

{
  "DetokenizedFields": [{
    "token": "9738-1683-0486-1480",
    "value": "4111111111111115",
    "type": "STRING"
  }, {
    "token": "6184-6357-8409-6668",
    "value": "4111111111111119",
    "type": "STRING"
  }],
  "Errors": [{
    "token": "4914-9088-2814-384",
    "error": "Token Not Found"
  }]
}

Tokenize

Tokenization replaces sensitive data with unique identifier tokens. This approach protects sensitive information by securely storing the original data while allowing the use of tokens within your application.

To tokenize data, use the Tokenize method. The TokenizeRequest creates a tokenize request. In this request, you specify the values parameter, which is a list of ColumnValue objects. Each ColumnValue contains two properties: Value and ColumnGroup.

Constructing your Tokenize request

package vaultapi

import (
  "context"
  "fmt"
  "github.com/skyflowapi/skyflow-go/v2/client"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
  "github.com/skyflowapi/skyflow-go/v2/utils/logger"
)

/**
 * This example demonstrates how to tokenize sensitive data (e.g., credit card information)
 * using the Skyflow client, along with corresponding TokenizeRequest schema.
 */
func main() {
  // Initialize Skyflow client
	
  // Step 1: Create a TokenizeRequest array to hold sensitive data
  ctx := context.TODO()
  var reqArray []common.TokenizeRequest

  // Step 2: Create column values for each sensitive data field (e.g., card number and cardholder name)
  columnValue1 := common.TokenizeRequest{
    ColumnGroup: "<COLUMN_GROUP>", 
    Value:       "<VALUE>",           // Replace <VALUE> and <COLUMN_GROUP> with actual data
  }
  columnValue2 := common.TokenizeRequest{
    ColumnGroup: "<COLUMN_GROUP>", 
    Value:       "<VALUE>",           
  } // Replace <VALUE> and <COLUMN_GROUP> with actual data
  
  // Add the created column values to the TokenizeRequest array
  reqArray = append(reqArray, columnValue1)
  reqArray = append(reqArray, columnValue2)


  // Step 3: Access the vault
  service, serviceErr := skyflowClient.Vault("<VAULT_ID>")
  if serviceErr != nil {
    //  Handle error accessing the vault
    fmt.Println(serviceErr)
  } else {

    // Step 4: Call the Skyflow vault to tokenize the sensitive data
    res, tokenizeErr := service.Tokenize(ctx, reqArray)
    if tokenizeErr != nil {
      // Step 5: Handle error during the tokenization process
      fmt.Println("Error occurred: ", tokenizeErr)
    } else {
      // Step 6: Print the tokenization response, which contains the generated tokens or errors 
      fmt.Println("RESPONSE: ", res)
    }
  }
}

Tip

See the full example in the samples directory: tokenize_records.go

import (
"context"
"fmt"
"github.com/skyflowapi/skyflow-go/v2/utils/common"
)

/**
 * This example demonstrates how to tokenize sensitive data (e.g., credit card information) using the Skyflow client.
 *
 * 1. Initializes the Skyflow client.
 * 2. Creates a column value for sensitive data (e.g., credit card number).
 * 3. Builds a tokenize request with the column value to be tokenized.
 * 4. Sends the request to the Skyflow vault for tokenization.
 * 5. Prints the tokenization response, which includes the token or errors.
 **/
func main() {
    // Initialize Skyflow client
    // Step 1: Initialize a array of column values to be tokenized (replace with actual sensitive data)
    ctx := context.TODO()
    var reqArray []common.TokenizeRequest

    // Step 2: Create a column value for the sensitive data (e.g., card number with its column group)
    columnValue := common.TokenizeRequest{
        ColumnGroup: "card_number_cg",   // Replace with actual column group name
        Value:       "4111111111111111", // Replace with the actual sensitive data (e.g., card number)
    }
    //Step 3:  Add the created column value to the list
    reqArray = append(reqArray, columnValue)

    // Access the vault
    service, serviceErr := skyflowClient.Vault("9f27764a10f7946fe56b3258e117") // Replace "9f27764a10f7946fe56b3258e117" with your actual Skyflow vault ID

    if serviceErr != nil {
        //  Handle error accessing the vault
    fmt.Println(serviceErr)
    } else {
        // Step 4 : Call the Skyflow vault to tokenize the sensitive data
        res, tokenizeErr := service.Tokenize(ctx, reqArray)
        if tokenizeErr != nil {
        // Handle error during the tokenization process
            fmt.Println("Error occurred ", tokenizeErr)
        } else {
             // Step 5: Print the tokenization response, which contains the generated tokens or errors
            fmt.Println("RESPONSE: ", res)
        }
    }
}

Sample response:

{
  "tokens": [5479-4229-4622-1393]
}

Get

To retrieve data using Skyflow IDs or unique column values, use the Get method. The GetRequest struct creates a get request, where you specify parameters such as the table name, redaction type, Skyflow IDs, column names, column values, and whether to return tokens.

Note

You can't use both Skyflow IDs and column name/value pairs in the same request.

Constructing your get request:

package vaultapi

import (
  "context"
  "fmt"
  "github.com/skyflowapi/skyflow-go/v2/client"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
)

/**
 * This example demonstrates how to retrieve data from the Skyflow vault using different methods,
 * along with corresponding GetRequest schema.
 */
func main() {
  // Initialize Skyflow client
  // Step 1: Initialize a array of Skyflow IDs to retrieve records (replace with actual Skyflow IDs)
  ctx := context.TODO() // Prepare the context for the request
  ids := []string{"<SKYFLOW_ID_1>", "<SKYFLOW_ID_2>"} // Replace with actual Skyflow ID

  // Step 2: Create a GetRequest and GetOptions to retrieve records by Skyflow ID without returning tokens
  getRequest := common.GetRequest{
    Table: "<TABLE_NAME>",       // Replace with the actual table name
    Ids:   ids,
  }
  options := common.GetOptions{
    ReturnTokens: false, // Set to false to avoid returning tokens
    RedactionType: common.PLAIN_TEXT, // Redact data as plain text
  }
  
  //  Initialize the Skyflow service and replace <VAULT_ID> with your actual Skyflow vault ID
  service, serviceError := skyflowClient.Vault("<VAULT_ID>")
  if serviceError != nil {
    // Handle any errors during initialization
    fmt.Println("Error occurred while initializing Skyflow service:", serviceError)

  }

  // Send the request to the Skyflow vault and retrieve the records
  res, getErr := service.Get(ctx, getRequest, options)
  if getErr != nil {
    // Handle any errors during the retrieval process
    fmt.Println("Error occurred while retrieving records by ID:", getErr)
  } else {
    // Print the retrieved records
    fmt.Println("Response for records by ID:", res.Data)
  }

  // Step 3: Create another GetRequest and GetOptions to retrieve records by Skyflow ID with tokenized values
  getTokensRequest := common.GetRequest{
    Table: "<TABLE_NAME>",       // Replace with the actual table name
    Ids:   ids, // Replace with actual Skyflow IDs
  }
  options := common.GetOptions{
    ReturnTokens: true, // Set to true to return tokenized values
  }
  
  // Send the request to the Skyflow vault and retrieve the tokenized records
  resWithTokens, getErrWithTokens := service.Get(ctx, getTokensRequest, options)
  if getErrWithTokens != nil {
    // Handle any errors during the retrieval process
    fmt.Println("Error occurred while retrieving tokenized records:", getErrWithTokens)
  } else {
    // Print the retrieved tokenized records
    fmt.Println("Response for tokenized records:", resWithTokens.Data)
  }

  // Step 4: Retrieve records based on specific column values
  // ColumnName and ColumnValues belong on GetOptions, not GetRequest
  columnValues := []string{"<COLUMN_VALUE_1>", "<COLUMN_VALUE_2>"}
  getByColumnResponse, getErrByColumn := service.Get(ctx, common.GetRequest{
    Table: "<TABLE_NAME>",
  }, common.GetOptions{
    ColumnName:   "<COLUMN_NAME>",  // Column to filter by (must be unique in schema)
    ColumnValues: columnValues,     // Values to match in that column
    RedactionType: common.PLAIN_TEXT,
  })
  if getErrByColumn != nil {
    // Handle any errors during the retrieval process
    fmt.Println("Error occurred while retrieving records by column values:", getErrByColumn)
  } else {
    // Print the retrieved records filtered by column values
    fmt.Println("Response for records by column values:", getByColumnResponse.Data)
  }
}

Get by skyflow IDs

Retrieve specific records using SkyflowIds. Ideal for fetching exact records when IDs are known.

Tip

See the full example in the samples directory: get_records.go

package vaultapi

import (
  "context"
  "fmt"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
)

/**
 * This example demonstrates how to retrieve data from the Skyflow vault using a list of Skyflow IDs.
 *
 * 1. Initializes the Skyflow client with a given vault ID.
 * 2. Creates a request to retrieve records based on Skyflow IDs.
 * 3. Specifies that the response should not return tokens.
 * 4. Uses plain text redaction type for the retrieved records.
 * 5. Prints the response to display the retrieved records.
 */
func main() {
  // Initialize Skyflow client
  // Step 1: Initialize a list of Skyflow IDs (replace with actual Skyflow IDs)
  ids := []string{
    "a581d205-1969-4350-acbe-a2a13eb871a6", // Replace with actual Skyflow ID
    "5ff887c3-b334-4294-9acc-70e78ae5164a", // Replace with actual Skyflow ID
  }

  // Step 2: Create a GetRequest and GetOptions to retrieve records based on Skyflow IDs
  // The request specifies:
  // - `ids`: The list of Skyflow IDs to retrieve
  // - `table`: The table from which the records will be retrieved
  getRequest := common.GetRequest{
    Table: "table1", // Replace with the actual table name
    Ids: ids,
  }
  // The options specifies:
  // - `ReturnTokens`: Set to false, meaning tokens will not be returned in the response
  // - `RedactionType`: Set to PLAIN_TEXT, meaning the retrieved records will have data redacted as plain text
  getOptions := common.GetOptions{
    ReturnTokens: false, // Tokens will not be returned
    RedactionType: common.PLAIN_TEXT, // Data will be redacted as plain text
  } 
  
  // Initialize the Skyflow service
  // Replace <VAULT_ID> with your actual Skyflow vault ID
  service, serviceError := skyflowClient.Vault("<VAULT_ID>")
  if serviceError != nil {
    // Step 4: Handle any errors that occur during the initialization process
    fmt.Println("Error occurred while initializing Skyflow service:", serviceError)

  }

  ctx := context.TODO()
  // Step 3: Send the request to the Skyflow vault and retrieve the records
  res, getErr := service.Get(ctx, getRequest, getOptions)
  if getErr != nil {
    // Step 4: Handle any errors that occur during the data retrieval process
    fmt.Println("Error occurred while retrieving records:", getErr)
  } else {
    // Step 5: Print the retrieved records from the response
    fmt.Println("Response:", res.Data)
  }
}

Sample response:

{
  "Data": [{
    "card_number": "4555555555555553",
    "email": "john.doe@gmail.com",
    "name": "john doe",
    "SkyflowId": "a581d205-1969-4350-acbe-a2a13eb871a6",
  }, {
    "card_number": "4555555555555559",
    "email": "jane.doe@gmail.com",
    "name": "jane doe",
    "SkyflowId": "5ff887c3-b334-4294-9acc-70e78ae5164a",
  }],
  "Errors": []
}

Get tokens

Return tokens for records. Ideal for securely processing sensitive data while maintaining data privacy.

Tip

See the full example in the samples directory: get_records.go

/**
 * This example demonstrates how to retrieve data from the Skyflow vault and return tokens along with the records.
 *
 * 1. Initializes the Skyflow client with a given vault ID.
 * 2. Creates a request to retrieve records based on Skyflow IDs and ensures tokens are returned.
 * 3. Prints the response to display the retrieved records along with the tokens.
 */
func main() {
    // Initialize Skyflow client
    // Step 1: Initialize a list of Skyflow IDs (replace with actual Skyflow IDs)
    ids := []string{
        "a581d205-1969-4350-acbe-a2a13eb871a6", // Replace with actual Skyflow ID
        "5ff887c3-b334-4294-9acc-70e78ae5164a", // Replace with actual Skyflow ID
    }
    // Step 2: Create a GetRequest to retrieve records based on Skyflow IDs
    // The request specifies:
    // - `ids`: The list of Skyflow IDs to retrieve
    // - `table`: The table from which the records will be retrieved
    getRequest := common.GetRequest{
        Table: "table1", // Replace with the actual table name
        Ids: ids,
    }
    // Specify options for the request
    // - `returnTokens`: Set to true, meaning tokens will be included in the response	
    getOptions := common.GetOptions{
        ReturnTokens: true, // Tokens will be returned
    }

    // Prepare the context for the request
    ctx := context.TODO()

    // Initialize the Skyflow service
    // Replace <VAULT_ID> with your actual Skyflow vault ID
    service, serviceError := skyflowClient.Vault("<VAULT_ID>")
    if serviceError != nil {
        // Handle any errors that occur during the initialization process
        fmt.Println("Error occurred while initializing Skyflow service:", serviceError)
    }
    // Step 3: Send the request to the Skyflow vault and retrieve the records with tokens
    res, getErr := service.Get(ctx, getRequest, getOptions)
    if getErr != nil {
        // Step 4: Handle any errors that occur during the data retrieval process
        fmt.Println("Error occurred while retrieving records:", getErr)
    } else {
        // Step 5: Print the retrieved records from the response
        fmt.Println("Response:", res.Data)
    }
}

Sample response:

{
  "Data": [{
    "card_number": "3998-2139-0328-0697",
    "email": "c9a6c9555060@82c092e7.bd52",
    "name": "82c092e7-74c0-4e60-bd52-c9a6c9555060",
    "SkyflowId": "a581d205-1969-4350-acbe-a2a13eb871a6",
  }, {
    "card_number": "3562-0140-8820-7499",
    "email": "6174366e2bc6@59f82e89.93fc",
    "name": "59f82e89-138e-4f9b-93fc-6174366e2bc6",
    "SkyflowId": "5ff887c3-b334-4294-9acc-70e78ae5164a",
  }],
  "Errors": []
}

Get By column name and column values

Retrieve records by unique column values. Ideal for querying data without knowing Skyflow IDs, using alternate unique identifiers.

Tip

See the full example in the samples directory: get_column_values.go

package main

import (
  "context"
  "fmt"
  "github.com/skyflowapi/skyflow-go/v2/client"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
)
/**
 * This example demonstrates how to retrieve data from the Skyflow vault based on column values.
 *
 * 1. Initializes the Skyflow client with a given vault ID.
 * 2. Creates a request to retrieve records based on specific column values (e.g., email addresses).
 * 3. Prints the response to display the retrieved records after redacting sensitive data based on the specified redaction type.
 */

func main() {
  // Initialize Skyflow client
  // Step 1: Initialize a list of column values (email addresses in this case)
  columnValues := []string{"john.doe@gmail.com", "jane.doe@gmail.com"} // Replace with actual values

  // Step 2: Create a GetRequest and GetOptions to retrieve records based on column values
  // ColumnName and ColumnValues are set on GetOptions, not GetRequest
  request := common.GetRequest{
    Table: "table1",  // Replace with the actual table name
  }
  options := common.GetOptions{
    ColumnName:   "email",        // The column to filter by (must be unique in schema)
    ColumnValues: columnValues,   // The list of column values to match
    RedactionType: common.PLAIN_TEXT,
  }
  
  // Set up the Skyflow vault service
  service, serviceError := skyflowClient.Vault("<VAULT_ID>") // Replace <VAULT_ID> with the actual vault ID
  if serviceError != nil {
    fmt.Println(serviceError) // Print any errors that occur during service initialization
  }

  // Define the context for the API call
  ctx := context.TODO() // Using context to manage the API request lifecycle
  
  // Step 3: Send the Get request to the Skyflow vault and retrieve the records
  response, getErr := service.Get(ctx, request, options)
  if getErr != nil {
    // Step 4: Handle any errors that occur during the data retrieval process
    fmt.Println("Error occurred", getErr)
  } else {
    // Print the response to display the retrieved records
    fmt.Println("RESPONSE:", response.Data)
  }
}

Sample response:

{
  "Data": [{
    "card_number": "4555555555555553",
    "email": "john.doe@gmail.com",
    "name": "john doe",
    "SkyflowId": "a581d205-1969-4350-acbe-a2a13eb871a6",
  }, {
    "card_number": "4555555555555559",
    "email": "jane.doe@gmail.com",
    "name": "jane doe",
    "SkyflowId": "5ff887c3-b334-4294-9acc-70e78ae5164a",
  }],
  "Errors": []
}

GetOptions fields

Field Type Description
RedactionType RedactionType How to display sensitive data (PLAIN_TEXT, MASKED, REDACTED, DEFAULT).
ReturnTokens bool Return tokens instead of plain-text values.
ColumnName string Filter by this column (must be unique in schema). Use with ColumnValues.
ColumnValues []string Values to match in ColumnName. Cannot be combined with Ids.
Fields []string Return only these specific fields.
Offset string Pagination offset.
Limit string Pagination limit.
OrderBy OrderByEnum Sort order: ASCENDING, DESCENDING, or NONE.
DownloadUrl bool Return a pre-signed download URL for file-type columns.
CustomHeaders map[CustomHeaderKey]string Request-level custom headers for this call.

Redaction types

Redaction types determine how sensitive data is displayed when retrieved from the vault.

Available Redaction Types

  • DEFAULT: Applies the vault-configured default redaction setting.
  • REDACTED: Completely removes sensitive data from view.
  • MASKED: Partially obscures sensitive information.
  • PLAIN_TEXT: Displays the full, unmasked data.

Choosing the Right Redaction Type

  • Use REDACTED for scenarios requiring maximum data protection to prevent exposure of sensitive information.
  • Use MASKED to provide partial visibility of sensitive data for less critical use cases.
  • Use PLAIN_TEXT for internal, authorized access where full data visibility is necessary.

Update

To update data in your vault, use the Update method. The UpdateRequest struct creates an update request, where you specify parameters such as the table name, data (as a map of key-value pairs), tokens, ReturnTokens, and TokenMode. If ReturnTokens is set to true, Skyflow returns tokens for the updated records. If ReturnTokens is set to false, Skyflow returns IDs for the updated records.

Construct an update request

package main

import (
  "context"
  "fmt"
  "github.com/skyflowapi/skyflow-go/v2/client"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
)

/**
 * This example demonstrates how to update records in the Skyflow vault by providing new data and/or tokenized values, along with corresponding UpdateRequest schema.
 *
 */
func main() {
  // Initialize Skyflow client
  // Step 1: Prepare the data to update in the vault — include SkyflowId as a key in the map
  data := map[string]interface{}{
    "SkyflowId":        "<SKYFLOW_ID>",       // Skyflow ID for identifying the record to update
    "<COLUMN_NAME_1>":  "<COLUMN_VALUE_1>",   // Column name and new value
    "<COLUMN_NAME_2>":  "<COLUMN_VALUE_2>",   // Column name and new value
  }
  // Step 2: Optionally provide BYOT tokens for specific columns
  tokens := map[string]interface{}{
    "<COLUMN_NAME_2>": "<TOKEN_VALUE_2>",
  }
  // Define the context for the API call
  ctx := context.TODO() // Using context to manage the API request lifecycle
  
  // Step 3: Create an UpdateRequest to specify the update operation
  updateRequest := common.UpdateRequest{
    Table:  "<TABLE_NAME>",  // Replace with the actual table name
    Data:   data,            // The data to update; SkyflowId identifies the record
    Tokens: tokens,          // Optional: BYOT tokens for specific columns
  }
  updateOptions := common.UpdateOptions{
    ReturnTokens: true,             // Specify whether to return tokens in the response
    TokenMode:    common.DISABLE,   // Specify the tokenization mode (e.g., ENABLE or DISABLE)
  }
  // Set up the Skyflow vault service
  service, serviceErr := skyflowClient.Vault("<VAULT_ID>") // Replace <VAULT_ID> with the actual vault ID
  if serviceErr != nil {
    // Handle errors that occur during service initialization
    fmt.Println(serviceErr) // Print the error
  }
  
  // Step 4: Send the request to the Skyflow vault and update the record
  response, errUpdate := service.Update(ctx, updateRequest, updateOptions)
  if errUpdate != nil {
    // Handle errors that occur during the update operation
    fmt.Println("Error occurred", *errUpdate) // Print the error for debugging purposes
  } else {
    // Print the response to confirm the update result
    fmt.Println("response:", response)
  }
}

Tip

See the full example in the samples directory: update_record.go

package main

import (
  "context"
  "fmt"
  "github.com/skyflowapi/skyflow-go/v2/client"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
)

/**
 * This example demonstrates how to update a record in the Skyflow vault with specified data and tokens.
 *
 * 1. Initializes the Skyflow client with a given vault ID.
 * 2. Constructs an update request with data to modify and tokens to include.
 * 3. Sends the request to update the record in the vault.
 * 4. Prints the response to confirm the success or failure of the update operation.
 */

func main() {
  // Initialize Skyflow client
  // Step 1: Prepare the data to update in the vault — include SkyflowId as a key in the map
  data := map[string]interface{}{
    "SkyflowId":   "5b699e2c-4301-4f9f-bcff-0a8fd3057413",  // Skyflow ID identifies the record to update
    "name":        "john doe",                               // New value for the "name" column
    "card_number": "4111111111111115",                        // New value for the "card_number" column
  }
  // Step 2: Optionally provide BYOT tokens for specific columns
  tokens := map[string]interface{}{
    "name": "72b8ffe3-c8d3-4b4f-8052-38b2a7405b5a",
  }
  
  // Step 3: Create an UpdateRequest to define the update operation
  updateRequest := common.UpdateRequest{
    Table:  "table1",  // Replace with the actual table name
    Data:   data,      // The data to update; SkyflowId identifies the record
    Tokens: tokens,    // Optional: BYOT tokens for specific columns
  }
  // Define update options, including tokenization mode
  updateOptions := common.UpdateOptions{
    ReturnTokens: true,            // Specify whether to return tokens in the response
    TokenMode:    common.DISABLE,  // Specify tokenization mode (e.g., DISABLE means no tokenization)
  }

  
  //Set up the Skyflow vault service
  // Initialize the Skyflow client with the provided Vault ID
  service, serviceErr := skyflowClient.Vault("<VAULT_ID>") // Replace <VAULT_ID> with your actual Vault ID
  if serviceErr != nil {
    // Handle errors that occur during the service initialization
    fmt.Println(serviceErr) // Print the error for debugging purposes
  }
  // Step 4: Send the update request to the Skyflow vault
  response, errUpdate := service.Update(context.TODO(), updateRequest, updateOptions)
  if errUpdate != nil {
    // Handle errors that occur during the update operation
    fmt.Println("Error occurred", *errUpdate) // Print the error for debugging purposes
  } else {
    // Print the response to confirm the update result
    fmt.Println("response:", response)
  }
}

Sample response: When ReturnTokens is set to true

{
  "UpdatedField": {
    "SkyflowId": "5b699e2c-4301-4f9f-bcff-0a8fd3057413",
    "name": "72b8ffe3-c8d3-4b4f-8052-38b2a7405b5a",
    "card_number": "4315-7650-1359-9681"
  },
  "Errors": []
}

Sample response

  • When ReturnTokens is set to false
{
  "UpdatedField": {
    "SkyflowId": "5b699e2c-4301-4f9f-bcff-0a8fd3057413"
  },
  "Errors": []
}

Delete

To delete records using Skyflow IDs, use the Delete method. The DeleteRequest struct accepts a list of Skyflow IDs that you want to delete, as shown below:

Construct a delete request

package main

import (
  "context"
  "fmt"
  "github.com/skyflowapi/skyflow-go/v2/client"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
)

/**
 * This example demonstrates how to delete records from a Skyflow vault using specified Skyflow IDs, along with corresponding DeleteRequest schema.
 *
 */
func main() {
  // Initialize Skyflow client 
  // Step 1: Prepare a list of Skyflow IDs for the records to delete
  // The list stores the Skyflow IDs of the records that need to be deleted from the vault
  ids := []string{
    "<SKYFLOW_ID_1>", // Replace with actual Skyflow ID 1
    "<SKYFLOW_ID_2>", // Replace with actual Skyflow ID 2
    "<SKYFLOW_ID_3>", // Replace with actual Skyflow ID 3
  }
  // Define the context for the API call
  ctx := context.TODO() // Use context to manage the lifecycle of the API request

  // Step 2: Create a DeleteRequest to define the delete operation
  // The request specifies the table from which to delete the records and the IDs of the records to delete
  deleteRequest := common.DeleteRequest{
    Table: "<TABLE_NAME>", // Replace with the actual table name from which to delete records
    Ids:   ids,            // List of Skyflow IDs to delete
  }

  // Set up the Skyflow vault service
  service, serviceErr := skyflowClient.Vault("<VAULT_ID>") // Replace <VAULT_ID> with the actual vault ID
  if serviceErr != nil {
    // Handle errors during service initialization
    fmt.Println(serviceErr) // Print the error message

  }
  
  // Step 3: Send the delete request to the Skyflow vault
  deleteResponse, errDelete := service.Delete(ctx, deleteRequest) // Call to delete records from the vault
  if errDelete != nil {
    // Handle errors during the delete operation
    fmt.Println("Error occurred", *errDelete) // Print the error message for debugging
  } else {
    // Step 4: Print the response to confirm the delete result
    // The response confirms whether the delete operation was successful
    fmt.Println("response:", deleteResponse) // Print the delete response
  }
}

Tip

See the full example in the samples directory: delete.go

package main

import (
  "context"
  "fmt"
  "github.com/skyflowapi/skyflow-go/v2/client"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
)

/**
 * This example demonstrates how to delete records from a Skyflow vault using specified Skyflow IDs.
 *
 * 1. Initializes the Skyflow client with a given Vault ID.
 * 2. Constructs a delete request by specifying the IDs of the records to delete.
 * 3. Sends the delete request to the Skyflow vault to delete the specified records.
 * 4. Prints the response to confirm the success or failure of the delete operation.
 **/

func main() {
  // Step 1: Set up the Skyflow vault service
  service, serviceErr := skyflowClient.Vault("<VAULT_ID>") // Replace <VAULT_ID> with your actual vault ID
  if serviceErr != nil {
    // Handle any errors that occur during service initialization
    fmt.Println(serviceErr) // Print the error
  }

  // Prepare a list of Skyflow IDs for the records to delete
  // The list stores the Skyflow IDs of the records that need to be deleted from the vault
  ids := []string{
    "9cbf66df-6357-48f3-b77b-0f1acbb69280", // Replace with actual Skyflow ID 1
    "ea74bef4-f27e-46fe-b6a0-a28e91b4477b", // Replace with actual Skyflow ID 2
    "47700796-6d3b-4b54-9153-3973e281cafb", // Replace with actual Skyflow ID 3
  }

  // Step 2: Create a DeleteRequest to define the delete operation
  // The request specifies the table from which to delete the records and the IDs of the records to delete
  
  deleteRequest := common.DeleteRequest{
    Table: "<TABLE_NAME>", // Replace with the actual table name from which to delete
    Ids:   ids,            // List of Skyflow IDs to delete
  }

  // Step 3: Send the delete request to the Skyflow vault
  deleteResponse, errDelete := service.Delete(context.TODO(), deleteRequest)
  if errDelete != nil {
    // Handle errors that occur during the delete operation
    fmt.Println("Error occurred", *errDelete) // Print the error for debugging purposes
  } else {
    // Step 4: Print the response to confirm the delete result
    fmt.Println("response:", deleteResponse)
  }
}

Sample response:

{
  "DeletedIds": [
    "9cbf66df-6357-48f3-b77b-0f1acbb69280",
    "ea74bef4-f27e-46fe-b6a0-a28e91b4477b",
    "47700796-6d3b-4b54-9153-3973e281cafb"
  ]
}

Query

To retrieve data with SQL queries, use the Query method. The QueryRequest struct accepts a query parameter, as shown below.

Construct a query request

Refer to Query your data and Execute Query for guidelines and restrictions on supported SQL statements, operators, and keywords.

package main

import (
  "context"
  "fmt"
  "github.com/skyflowapi/skyflow-go/v2/client"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
)

/**
 * This example demonstrates how to execute a custom SQL query on a Skyflow vault, along with QueryRequest schema.
 *
 */
func main() {
  // Initialize Skyflow client
  // Step 1: Define the SQL query to execute on the Skyflow vault
  // Replace "<YOUR_SQL_QUERY>" with the actual SQL query you want to run
  query := "<YOUR_SQL_QUERY>" // Example: "SELECT * FROM demo WHERE SkyflowId='<ID>'"

  // Step 2: Create a QueryRequest with the specified SQL query
  queryRequest := common.QueryRequest{
    Query: query, // Pass the query string to the request
  }
  // Step 3: Initialize the Skyflow vault service
  service, serviceError := skyflowClient.Vault("<VAULT_ID>") // Replace <VAULT_ID> with the actual Vault ID
  if serviceError != nil {
    // Handle errors that occur during the service initialization
    fmt.Println(serviceError) // Print the error message

  }
  ctx := context.TODO() // Using context to manage the API request lifecycle

  // Step 4: Execute the query request on the specified Skyflow vault
  res, queryErr := service.Query(ctx, queryRequest) // Execute the query

  // Step 5: Handle the response or any errors from the query execution
  if queryErr != nil {
    // Handle any errors that occur during query execution
    fmt.Println("Error occurred: ", *queryErr) // Print the error message
  } else {
    // Print the response containing the query results
    fmt.Println("RESPONSE: ", res)
  }
}

Tip

See the full example in the samples directory: query_record.go

package main

import (
  "context"
  "fmt"
  "github.com/skyflowapi/skyflow-go/v2/client"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
)

/**
 * This example demonstrates how to execute a SQL query on a Skyflow vault to retrieve data.
 *
 * 1. Initializes the Skyflow client with the Vault ID.
 * 2. Constructs a query request with a specified SQL query.
 * 3. Executes the query against the Skyflow vault.
 * 4. Prints the response from the query execution.
 **/


func main() {
  // Initialize Skyflow client
  // Step 1: Define the SQL query to execute
  // Example query: Retrieve all records from the "demo" table with a specific SkyflowId
  query := "SELECT * FROM cards WHERE SkyflowId='3ea3861-x107-40w8-la98-106sp08ea83f'" // Replace with the actual Skyflow ID to filter the query 

  // Step 2: Create a QueryRequest with the SQL query
  queryRequest := common.QueryRequest{
    Query: query, // SQL query to execute
  }

  // Set up the Skyflow vault service
  service, serviceError := skyflowClient.Vault("9f27764a10f7946fe56b3258e117") // Replace with the actual vault ID
  if serviceError != nil {
    // Handle errors that occur during service initialization
    fmt.Println(serviceError) // Print the error

  }

  // Step 3: Execute the query request on the specified Skyflow vault and handle the response
  ctx := context.TODO() // Context for managing the lifecycle of the query request
  res, queryErr := service.Query(ctx, queryRequest) // Execute the query request

  if queryErr != nil {
    // Handle any errors that occur during query execution
    fmt.Println("Error occurred ", *queryErr) // Print the error for debugging purposes
  } else {
    // Step 5: Print the response from the query execution
    // The response contains the query results retrieved from the Skyflow vault
    fmt.Println("RESPONSE: ", res) // Print the query response to show the results
  }
}

Sample response:

{
  "Fields": [{
    "card_number": "XXXXXXXXXXXX1112",
    "name": "S***ar",
    "SkyflowId": "3ea3861-x107-40w8-la98-106sp08ea83f",
    "TokenizedData": []
  }],
  "Errors": []
}

Upload File

To upload a file, use the UploadFile method. The FileUploadRequest struct accepts the skyflow id and associated parameters, as shown below:

Construct an File upload request

package main

import (
  "context"
  "fmt"
  "github.com/skyflowapi/skyflow-go/v2/client"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
)

/**
 * This example demonstrates how to upload files in the Skyflow vault by providing skyflow id and file data, along with corresponding FileUploadRequest schema.
 *
 */
func main() {
  // Initialize Skyflow client

  // Set up the Skyflow vault service
  service, serviceErr := skyflowClient.Vault("<VAULT_ID>") // Replace <VAULT_ID> with the actual vault ID
  if serviceErr != nil {
    // Handle errors that occur during service initialization
    fmt.Println(serviceErr) // Print the error
  } else {
    ctx := context.TODO()
    // Step 2: Create File object for request
    filePath := "<FILE_PATH>" // File path for creating the file object
    fileObj, err := os.Open(filePath)
    if err != nil {
      fmt.Println("Error in reading file: ", err)
    } else {
      // Step 3: Create file request
      request := common.FileUploadRequest{
      	Table: "<TABLE_NAME>", // Replace with the actual table name into which file is to upload 
      	FileObject: *fileObj,   // Optional
          FilePath: "<FILE_PATH>" // Optional 
          Base64: "<BASE_64>" // Optional
      	ColumnName: "<COLUMN_NAME>", // Replace column name with your file column
      	SkyflowId:  "<SKYFLOW_ID>", // Replace skyflow id for file upload
          FileName: "<FILE_NAME>" // Optional, File name is required in case of base64
      }
        // Step 4: Send the file upload request to the Skyflow vault
      fileResponse, errFile := service.UploadFile(ctx, request)
        // Step 5: Prints the response to confirm the success or failure of the update operation.
      if errFile != nil {
          // Handle errors that occur during the upload operation
      	fmt.Println("ERROR: ", *errFile)
      } else {
          // Print the response to confirm the file upload result
      	fmt.Println("Response: ", fileResponse)
      }
			}
  }
}

Note:

  • We can pass only one from file path, file object and base64 in file upload request.
  • File name is required when base64 is passed in request.

Tip

See the full example in the samples directory: upload_file.go

package main

import (
  "context"
  "fmt"
  "github.com/skyflowapi/skyflow-go/v2/client"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
)

/**
 * This example demonstrates how to upload file in the Skyflow vault with specified data and tokens.
 *
 * 1. Initializes the Skyflow client with a given vault ID.
 * 2. Create File object for request
 * 3. Constructs an file upload request 
 * 4. Send the file upload request to the Skyflow vault
 * 5. Prints the response to confirm the success or failure of the file upload operation.
 */
func main() {
  // Initialize Skyflow client

  // Set up the Skyflow vault service
  service, serviceErr := skyflowClient.Vault("<VAULT_ID>") // Replace <VAULT_ID> with the actual vault ID
  if serviceErr != nil {
    // Handle errors that occur during service initialization
    fmt.Println(serviceErr) // Print the error
  } else {
    	ctx := context.TODO()
    	// Step 2: Create File object for request
			filePath := "Photo.png" // File path for creating the file object
			fileObj, err := os.Open(filePath)
			if err != nil {
      fmt.Println("Error in reading file: ", err)
			} else {
      // Step 3: Constructs an file upload request 
      request := common.FileUploadRequest{
      	Table: "table1", // Replace with the actual table name into which file is to upload 
      	FileObject: *fileObj,   // Optional
        FilePath: filePath // Optional 
        Base64: "<BASE_64>" // Optional
      	ColumnName: "file", // Replace column name with your file column
      	SkyflowId:  "5b699e2c-4301-4f9f-bcff-0a8fd3057413", // Replace skyflow id for file upload
        FileName: "<FILE_NAME>" // Optional, File name is required in case of base64
      }
        // Step 4: Send the file upload request to the Skyflow vault
      fileResponse, errFile := service.UploadFile(ctx, request)
        // Step 5: Prints the response to confirm the success or failure of the file upload operation.
      if errFile != nil {
          // Handle errors that occur during the upload operation
      	fmt.Println("ERROR: ", *errFile)
      } else {
          // Print the response to confirm the file upload result
      	fmt.Println("Response: ", fileResponse)
      }
			}
  }
}

Sample response:

{
  "SkyflowId": "5b699e2c-4301-4f9f-bcff-0a8fd3057413"
}

Custom Request Headers

The SDK supports passing custom HTTP headers at two levels: client level (applied to all requests) and request level (applied to a single API call).

Supported headers

Constant Header name Description
common.RequestIDHeader x-request-id Custom request identifier for tracing
common.SkyflowAccountID x-skyflow-account-id Skyflow account identifier
common.SkyflowAccountName x-skyflow-account-name Skyflow account name

Client-level custom headers

Use client.WithCustomHeaders when building the Skyflow client. These headers are sent with every request made through that client.

import (
  "github.com/skyflowapi/skyflow-go/v2/client"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
)

customHeaders := map[common.CustomHeaderKey]string{
    common.RequestIDHeader:    "<REQUEST_ID>",   // Replace with your request ID
    common.SkyflowAccountID:  "<ACCOUNT_ID>",   // Replace with your account ID
}

skyflowClient, err := client.NewSkyflow(
    client.WithVaults(vaultConfig),
    client.WithCredentials(skyflowCredentials),
    client.WithCustomHeaders(customHeaders),
)

Request-level custom headers

Pass CustomHeaders in the options struct for any individual operation. Request-level headers take precedence over client-level headers for that call.

The following vault options structs support CustomHeaders. Detect operations set request-level headers with an Interceptor instead: see Detect request headers.

Vault operations

Operation Options struct
Insert InsertOptions
Detokenize DetokenizeOptions
Get GetOptions
Update UpdateOptions
Delete DeleteOptions
Query QueryOptions
Tokenize TokenizeOptions
UploadFile FileUploadOptions

Example — passing a custom request ID on a single insert call:

import (
  "context"
  "fmt"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
)

customHeaders := map[common.CustomHeaderKey]string{
    common.RequestIDHeader: "<REQUEST_ID>", // Replace with your request ID
}

insertOptions := common.InsertOptions{
    ReturnTokens:  true,
    CustomHeaders: customHeaders,
}

service, serviceErr := skyflowClient.Vault("<VAULT_ID>")
if serviceErr != nil {
    fmt.Println("Error:", serviceErr)
}

response, err := service.Insert(context.TODO(), insertRequest, insertOptions)
if err != nil {
    fmt.Println("Error:", err)
} else {
    fmt.Println("Response:", response)
}

Detect

Skyflow Detect finds sensitive data in text and in files, including documents, spreadsheets, images and audio, and replaces it with tokens or placeholders. Vault tokens can be re-identified later. It also screens text with guardrails for toxicity and denied topics. Get a vault's detect service from the client; every method takes a context, a request and an options struct, and returns a response and a *SkyflowError.

Before you start, have these ready:

  • A vault ID and cluster ID. The vault ID is on the vault's details page in Skyflow Studio. The cluster ID is the first part of the vault URL: https://{clusterId}.vault.skyflowapis.com.
  • A role. The service account needs the Detect Invoker, Detect Manager or Vault Owner role on the vault. Detect Invoker can de-identify data and write vault tokens; Detect Manager can also create, update and delete Detect configurations. Re-identifying vault tokens works like detokenization: the caller also needs a policy that grants the Detokenization action on the destination, unless it is a Vault Owner.
  • A configuration, unless you pass one inline. A stored configuration is created in Studio or with the Management API, and its ID goes in ConfigurationId; the SDK doesn't create configurations. See De-identification.
  • A destination column, if you use DeidentificationTypeVaultToken. Vault tokens are stored in the "<TABLE_NAME>.<COLUMN_NAME>" named in the entity's Destination, for example persons.ssn. The table and column must already exist in the vault schema: Detect writes into them but doesn't create them.
service, err := skyflowClient.Detect("<VAULT_ID>") // a vault from the client config
if err != nil {
	fmt.Println(err.GetMessage())
	return
}
Method Request Options Response
DeidentifyString DeidentifyStringRequest DeidentifyStringOptions DeidentifyStringResponse
DeidentifyFile DeidentifyFileRequest DeidentifyFileOptions DeidentifyFileResponse
GetRun GetRunRequest GetRunOptions GetRunResponse
ReidentifyString ReidentifyStringRequest ReidentifyStringOptions ReidentifyStringResponse
ReidentifyFile ReidentifyFileRequest ReidentifyFileOptions ReidentifyFileResponse
CheckGuardrails CheckGuardrailsRequest CheckGuardrailsOptions CheckGuardrailsResponse

All types are in github.com/skyflowapi/skyflow-go/v2/utils/common. This section covers SkyVault vaults. For FlowVault vaults (token groups and redaction patterns), see Detect in the FlowVault README.

Important

These are the new Detect methods. They replace the earlier ones (DeidentifyText, ReidentifyText, GetDetectRun), which are removed. DeidentifyFile keeps its name but no longer waits for the result by default: without Poll it returns only RunId, with an empty Status and no Output. See Migrate from the earlier Detect methods.

Deidentify String

DeidentifyString replaces sensitive data in Text with tokens. Choose the configuration with ConfigurationId (a stored configuration, created in Studio or with the Management API) or Configuration (an inline one; see the Detect configuration reference). Both are optional and sent as given, as in the other Skyflow SDKs. With neither, the SDK sends only the vault ID and the run uses the vault's default Detect settings. Set only one: the API rejects a request with both (HTTP 400).

// With a stored configuration
response, err := service.DeidentifyString(ctx, common.DeidentifyStringRequest{
	Text:            "My name is John Doe, and my email is johndoe@acme.com.",
	ConfigurationId: "<CONFIGURATION_ID>",
}, common.DeidentifyStringOptions{})

// With an inline configuration. Optional numbers and flags are pointers (set them with common.Ptr): nil is left to the server.
response, err = service.DeidentifyString(ctx, common.DeidentifyStringRequest{
	Text: "My name is John Doe, and my email is johndoe@acme.com.",
	Configuration: &common.DetectConfiguration{
		Detect: &common.Detect{
			Entities: []common.Entity{
				{EntityType: common.EntityTypeName, DeidentificationType: common.DeidentificationTypeVaultToken, Destination: "<TABLE_NAME>.<COLUMN_NAME>"},
				{
					EntityType:           common.EntityTypeDOB,
					DeidentificationType: common.DeidentificationTypeEntityUniqueCounter,
					Transformation:       &common.Transformation{ShiftDates: &common.ShiftDates{MinDays: common.Ptr(10), MaxDays: common.Ptr(30)}},
				},
				{EntityType: common.EntityTypeAll, DeidentificationType: common.DeidentificationTypeEntityUniqueCounter},
			},
			Restrict:       []string{"[0-9]{3}-[0-9]{2}-[0-9]{4}"},              // always treat as sensitive
			Skip:           []string{"Skyflow"},                                 // never treat as sensitive
			CustomTypes:    []common.CustomType{{Label: "EMPLOYEE_ID", Match: []string{"EMP-[0-9]{6}"}}},
			ReturnEntities: common.ReturnEntitiesTypeExcludeSensitiveData,
		},
	},
}, common.DeidentifyStringOptions{})
if err != nil {
	fmt.Println(err.GetHttpCode(), err.GetMessage(), err.GetRequestId())
	return
}
fmt.Println(response.ProcessedText) // My name is [NAME_1], and my email is [EMAIL_ADDRESS_1].

Sample response:

{
  "processedText": "My name is [NAME_1], and my email is [EMAIL_ADDRESS_1].",
  "entities": [
    {
      "token": "NAME_1",
      "value": "",
      "location": { "startIndex": 11, "endIndex": 19, "startIndexProcessed": 11, "endIndexProcessed": 19 },
      "entityType": "NAME",
      "entityScores": { "NAME": 0.95 }
    }
  ],
  "metrics": { "size": 0.05, "wordCount": 11, "characterCount": 54 }
}

Value is set only when the configuration's ReturnEntities is ReturnEntitiesTypeAll. Location is a *common.EntityLocation: nil when the server sends no location.

Tip

See the full example in the samples directory: deidentify_string.go

Deidentify File

DeidentifyFile submits a file and returns its run ID. Supply the file as exactly one of:

Field Input
FilePath A local file. Sent as base64; the format is inferred from the extension. DataSource is ignored.
FileObject An open *os.File, sent the same way. The caller closes it.
DataSource + Value DeidentifySourceTypeBase64, DeidentifySourceTypeSkyflowID or DeidentifySourceTypePresignedURL.

Before calling the API, the SDK checks that exactly one is set, that a Value has a DataSource and isn't blank, and that a local file exists and is a regular file. A local file is checked before the Poll options, and one that exists but can't be read fails with "Failed to encode the file". It sends DataSource as given; the server rejects one the vault doesn't accept.

ConfigurationId and Configuration work as for Deidentify String.

Warning

DeidentifyFile doesn't wait for the result by default. It returns as soon as the file is submitted, with only RunId set: Status is empty and there is no Output. Get the result later with GetRun, or set Poll to wait for the run. The earlier DeidentifyFile always waited, so ported code can run without an error and still get no Output. Check Status before reading it.

Outputs are written to disk only when the input is a local file (FilePath or FileObject), the polled run reached SUCCESS and its outputs are base64. They are named processed-<name>.<ext>, processed-entities-<name>.json and processed-object-entities-<name>.json, where <name> is the input's name without its extension (a dotfile such as .env keeps its whole name). A file that can't be written fails the call with "Failed to write the processed output to ." and code "0"; the underlying error is Unwrap(). OutputDirectory requires Poll, is created if missing and defaults to the current directory (an empty or blank value means the current directory). Presigned-URL outputs are not fetched: read them from Output.

DeidentificationTypeVaultToken is supported only for txt, csv, json, jsonl, xml, docx, xlsx and pptx files.

// Submit and return: only RunId is set
submitted, err := service.DeidentifyFile(ctx, common.DeidentifyFileRequest{
	DataSource:      common.DeidentifySourceTypeSkyflowID,
	Value:           "<SKYFLOW_ID>",
	DataFormat:      common.DeidentifyFileDataFormatPDF, // optional
	ConfigurationId: "<CONFIGURATION_ID>",
}, common.DeidentifyFileOptions{})
fmt.Println(submitted.RunId)

// Submit a local file and wait up to 2 minutes
response, err := service.DeidentifyFile(ctx, common.DeidentifyFileRequest{
	FilePath:        "<PATH_TO_FILE>/patient-notes.pdf",
	ConfigurationId: "<CONFIGURATION_ID>",
}, common.DeidentifyFileOptions{
	Poll:            &common.PollOptions{WaitTime: common.Ptr(2 * time.Minute)},
	OutputDirectory: "<OUTPUT_DIRECTORY>",
})
if err != nil {
	fmt.Println(err.GetHttpCode(), err.GetMessage(), err.GetRequestId())
	return
}
switch response.Status {
case common.DetectRunStatusSuccess:
	fmt.Println("Outputs:", len(response.Output))
case common.DetectRunStatusInProgress, common.DetectRunStatusQueued: // the wait ran out
	fmt.Println("Still running, run ID:", response.RunId)
default: // FAILED or UNKNOWN
	fmt.Println("Run failed:", response.Message)
}
PollOptions Default Limit
WaitTime 60s 1s to 300s
MaxAttempts 23 1 to 23

A field left nil uses its default; a value that is set must be within the limit, so 0 is rejected (common.Ptr(2 * time.Minute) sets one).

Polling backs off 1s, 2s, 4s … up to 32s between lookups, and stops at the first of WaitTime, MaxAttempts or a final status (SUCCESS, FAILED, UNKNOWN). WaitTime counts the pauses between lookups, not the time each lookup takes, so a call can run a little longer than WaitTime. With this backoff at most 7 lookups fit in 60s and 15 in 300s, so MaxAttempts only stops polling earlier when it is set below that.

Sample response (polled, successful):

{
  "runId": "89699e2c-4301-4f9f-bcff-0a8fd3057489",
  "status": "SUCCESS",
  "outputType": "BASE64",
  "output": [
    { "processedFile": "TXkgU1NOIGlzIFtTU0==", "processedFileType": "REDACTED_FILE", "processedFileExtension": "PDF" },
    { "processedFile": "0X2xhYmVsIjoiQ1JFRElUX0NB==", "processedFileType": "ENTITIES", "processedFileExtension": "JSON" }
  ],
  "metrics": { "size": 12.4, "wordCount": 210, "characterCount": 1180, "pages": 2 },
  "message": ""
}

Tip

See the full example in the samples directory: deidentify_file.go

Get Run

GetRun returns the current state of a DeidentifyFile run. Output, Metrics and OutputType are set once the run succeeds; each output is base64 or a presigned URL, per OutputType. OutputType is a DeidentifySourceType; it is nil for a value the SDK doesn't know. Metrics and each of its counts are pointers, nil when the server leaves them out.

run, err := service.GetRun(ctx, common.GetRunRequest{RunId: "<RUN_ID>"}, common.GetRunOptions{})
if err != nil {
	fmt.Println(err.GetHttpCode(), err.GetMessage(), err.GetRequestId())
	return
}
if run.Status == common.DetectRunStatusSuccess {
	for _, output := range run.Output {
		fmt.Println(output.ProcessedFileType, output.ProcessedFileExtension)
	}
}

Sample response (successful run):

{
  "runId": "89699e2c-4301-4f9f-bcff-0a8fd3057489",
  "status": "SUCCESS",
  "outputType": "BASE64",
  "output": [
    { "processedFile": "TXkgU1NOIGlzIFtTU0==", "processedFileType": "REDACTED_FILE", "processedFileExtension": "PDF" }
  ],
  "metrics": { "size": 12.4, "wordCount": 210, "characterCount": 1180, "pages": 2 },
  "message": ""
}

A run still in progress has "status": "IN_PROGRESS" and no output. A failed run has "status": "FAILED" and the reason in message.

Tip

See the full example in the samples directory: get_run.go

Reidentify String

ReidentifyString replaces the tokens in Text. Re-identification looks the tokens up in the vault, so it applies only to values de-identified with DeidentificationTypeVaultToken; ENTITY_UNIQUE_COUNTER, ENTITY_ONLY and MASK placeholders are not stored and cannot be re-identified.

A vault token in the text looks like [NAME_<token>]: the entity-type prefix, then the token for the value stored in the entity's Destination column ("<TABLE_NAME>.<COLUMN_NAME>"). Placeholders such as [NAME_1] from ENTITY_UNIQUE_COUNTER look similar but come back unchanged. A token de-identified with IncludePrefixNo has no prefix and can't be re-identified either.

Without RedactionLevel, every token gets its original value. RedactionLevel is a []common.RedactionRule of common.RedactionLevel values; each selects tokens by EntityName and shows them through a RedactionType: common.PLAIN_TEXT (original value), common.MASKED or common.REDACTED (keeps the token).

// De-identify into vault tokens first: only these can be re-identified
deidentified, err := service.DeidentifyString(ctx, common.DeidentifyStringRequest{
	Text: "My name is John Doe, and my email is johndoe@acme.com.",
	Configuration: &common.DetectConfiguration{
		Detect: &common.Detect{
			Entities: []common.Entity{
				{EntityType: common.EntityTypeName, DeidentificationType: common.DeidentificationTypeVaultToken, Destination: "<TABLE_NAME>.<COLUMN_NAME>"},
				{EntityType: common.EntityTypeEmailAddress, DeidentificationType: common.DeidentificationTypeVaultToken, Destination: "<TABLE_NAME>.<COLUMN_NAME>"},
			},
		},
	},
}, common.DeidentifyStringOptions{})
if err != nil {
	fmt.Println(err.GetHttpCode(), err.GetMessage(), err.GetRequestId())
	return
}
fmt.Println(deidentified.ProcessedText) // My name is [NAME_<token>], and my email is [EMAIL_ADDRESS_<token>].

response, err := service.ReidentifyString(ctx, common.ReidentifyStringRequest{
	Text: deidentified.ProcessedText,
	RedactionLevel: []common.RedactionRule{
		common.RedactionLevel{EntityName: common.EntityTypeName, RedactionType: common.PLAIN_TEXT},
		common.RedactionLevel{EntityName: common.EntityTypeEmailAddress, RedactionType: common.MASKED},
	},
}, common.ReidentifyStringOptions{})
if err != nil {
	fmt.Println(err.GetHttpCode(), err.GetMessage(), err.GetRequestId())
	return
}
fmt.Println(response.ProcessedText) // My name is John Doe, and my email is j******e@acme.com.

Sample response:

{
  "processedText": "My name is John Doe, and my email is j******e@acme.com.",
  "metrics": { "size": 0.05, "wordCount": 11, "characterCount": 54 }
}

Tip

See the full example in the samples directory: reidentify_string.go

Reidentify File

ReidentifyFile is synchronous: there is no run to poll. DataSource and Value are required: ReidentifySourceTypeBase64 with base64 content, or ReidentifySourceTypePresignedURL with a URL (a Skyflow ID is not accepted). There is no FilePath / FileObject: encode a local file into Value. DataFormat is optional: a ReidentifyFileDataFormat* constant (CSV, DOCX, JSON, JSONL, PPTX, TXT, XLSX, XML), the formats re-identification works with. Each output is a common.ReidentifyFileOutput, whose ProcessedFileExtension is the same type: empty for any other format. RedactionLevel works as in Reidentify String. The response's OutputType is a ReidentifySourceType, or nil for a value the SDK doesn't know.

The SDK writes nothing to disk: the re-identified output is in response.Output for you to handle.

content, readErr := os.ReadFile("<PATH_TO_FILE>/processed-notes.txt")
if readErr != nil {
	fmt.Println(readErr)
	return
}
response, err := service.ReidentifyFile(ctx, common.ReidentifyFileRequest{
	DataSource: common.ReidentifySourceTypeBase64,
	Value:      base64.StdEncoding.EncodeToString(content),
	RedactionLevel: []common.RedactionRule{
		common.RedactionLevel{EntityName: common.EntityTypeName, RedactionType: common.PLAIN_TEXT},
	},
}, common.ReidentifyFileOptions{})
if err != nil {
	fmt.Println(err.GetHttpCode(), err.GetMessage(), err.GetRequestId())
	return
}
for i, output := range response.Output {
	if response.OutputType != common.ReidentifySourceTypeBase64 {
		// A presigned URL: anyone holding it can download the data, so don't log it.
		fmt.Println("Output", i, "of type", output.ProcessedFileType, "is at a presigned URL")
		continue
	}
	decoded, decodeErr := base64.StdEncoding.DecodeString(output.ProcessedFile)
	if decodeErr != nil {
		fmt.Println(decodeErr)
		return
	}
	// The type and extension come from the server: keep only safe characters (namePart in
	// the sample below allows a-z, 0-9 and _), so the name can't leave this directory.
	name := fmt.Sprintf("reidentified-notes-%d-%s.%s", i,
		namePart(string(output.ProcessedFileType), "output"), namePart(string(output.ProcessedFileExtension), "bin"))
	if writeErr := os.WriteFile(name, decoded, 0o600); writeErr != nil {
		fmt.Println(writeErr)
		return
	}
}

Sample response:

{
  "status": "SUCCESS",
  "outputType": "BASE64",
  "output": [
    { "processedFile": "TXkgbmFtZSBpcyBKb2huIERvZS4=", "processedFileType": "REIDENTIFIED_FILE", "processedFileExtension": "TXT" }
  ],
  "metrics": { "size": 0.03, "wordCount": 5, "characterCount": 20 }
}

Tip

See the full example in the samples directory: reidentify_file.go

Check Guardrails

CheckGuardrails screens text for toxicity and denied topics. CheckToxicity is a *bool: toxicity is checked only when it is true. Nil leaves the field out of the request, and the server then doesn't check toxicity.

response, err := service.CheckGuardrails(ctx, common.CheckGuardrailsRequest{
	Text:          "<USER_PROMPT>",
	CheckToxicity: common.Ptr(true),
	DenyTopics:    []string{"politics", "medical advice"},
}, common.CheckGuardrailsOptions{})
if err != nil {
	fmt.Println(err.GetHttpCode(), err.GetMessage(), err.GetRequestId())
	return
}
if response.Validation == common.GuardrailsValidationFailed {
	// Toxic and DeniedTopic are *bool: nil when the API leaves them out.
	fmt.Println("Blocked. Toxic:", response.Toxic != nil && *response.Toxic, "Denied topic:", response.DeniedTopic != nil && *response.DeniedTopic)
}

Sample response:

{ "text": "<USER_PROMPT>", "validation": "FAILED", "toxic": false, "deniedTopic": true }

Tip

See the full example in the samples directory: check_guardrails.go

Detect configuration reference

An inline DetectConfiguration (the Configuration field) has these parts. Optional numbers and flags are pointers: nil leaves them to the server default, and common.Ptr(v) sets them. The SDK fills in the vault ID.

DetectConfiguration field Type Meaning
Name, Description string Optional labels.
Detect *Detect What is detected and how it's de-identified.
FileMapping []FileMapping Maps a source file location to where its outputs go: Source, Destination, OutputFileNameSuffix, EntitiesDestination, ObjectEntitiesDestination.
Media *Media Per-media options. File calls only.
Detect field Type Meaning
Entities []Entity One rule per entity type (below). EntityTypeAll matches every type without its own rule.
ObjectEntities []ObjectEntity Objects in images and video. EntityType: ObjectEntityTypeFace, ObjectEntityTypeLicensePlate, ObjectEntityTypeLogo, ObjectEntityTypeSignature, ObjectEntityTypeAll. DeidentificationType: ObjectDeidentificationTypeRedact or ObjectDeidentificationTypeUnredact. File calls only.
Restrict []string Regexes always treated as sensitive.
Skip []string Regexes never treated as sensitive.
CustomTypes []CustomType Custom entities: a Label (reported as the entity type), Match regexes, and the same DeidentificationType, Destination, IncludePrefix and PrefixOverride fields as Entity.
ReturnEntities ReturnEntitiesType What Entities in the response carries: ReturnEntitiesTypeAll (with values), ReturnEntitiesTypeExcludeSensitiveData (without values) or ReturnEntitiesTypeNone.
Entity field Meaning
EntityType An EntityType* constant, for example EntityTypeName, EntityTypeSSN or EntityTypeEmailAddress. See v2/utils/common/detect.go for the full list.
DeidentificationType DeidentificationTypeVaultToken (stored in the vault and reversible), DeidentificationTypeEntityUniqueCounter ([NAME_1]), DeidentificationTypeEntityOnly ([NAME]) or DeidentificationTypeMask.
Destination The vault column the value is stored in, as "<TABLE_NAME>.<COLUMN_NAME>" (for example persons.name). Required for DeidentificationTypeVaultToken.
Transformation ShiftDates{MinDays, MaxDays} shifts dates by a random number of days in that range, instead of replacing them.
IncludePrefix IncludePrefixYes / IncludePrefixNo: whether a vault token carries the entity-type prefix, as in [NAME_<token>]. Applies only to DeidentificationTypeVaultToken; the server default is yes. IncludePrefixNo returns the raw vault token, and the value can't be re-identified later.
PrefixOverride A custom prefix instead of the entity type, for example NAAM gives [NAAM_<token>]. Not valid with IncludePrefixNo.
Media field Options
Audio OutputProcessedAudio *bool; OutputTranscription (OutputTranscriptionType*: none, transcription, medical, diarized, medical diarized); Bleep with StartPadding / StopPadding (seconds, 0–20; server defaults 0.5 and 0.2), Frequency (Hz) and Gain.
Document.Pdf ProcessingMode (PdfProcessingModeOCR, PdfProcessingModeTextLayer, PdfProcessingModeNone), Density, MaxResolution.
Image OutputProcessedImage *bool, OutputOcrText *bool, MaskingMethod (MaskingMethodBlur, MaskingMethodBlackbox, MaskingMethodNone).

The supported file formats are the DeidentifyFileDataFormat* constants: pdf, txt, csv, json, jsonl, xml, doc, docx, xls, xlsx, ppt, pptx, jpg, jpeg, png, bmp, gif, tif, tiff, dcm, mp3, wav and zip.

Detect request headers

Client-level headers set with WithCustomHeaders are sent with every Detect call. To add a header to a single call, set Interceptor in its options:

options := common.DeidentifyStringOptions{
	Interceptor: func(rc *common.RequestContext) {
		rc.AddHeader(common.RequestIdHeader, "<REQUEST_ID>")
	},
}

Migrate from the earlier Detect methods

client.Detect(vaultID) now returns the new Detect methods. The earlier ones (DeidentifyText, ReidentifyText, GetDetectRun) and their types are removed, and DeidentifyFile no longer waits by default. See the migration guide for the upgrade command, the method mapping and before-and-after code.

Connections

Skyflow Connections is a gateway service leveraging tokenization to securely send and receive data between your systems and first- or third-party services. The connections module is used to invoke both INBOUND and/or OUTBOUND connections.

  • Inbound Connections: Act as intermediaries between your client and server, tokenizing sensitive data before it reaches your backend, ensuring downstream services handle only tokenized data.
  • Outbound Connections: Enable secure extraction of data from the vault and transfer it to third-party services via your backend server.

Invoke Connection

To invoke a connection, use the Invoke method of the Skyflow client.

Construct an invoke connection request

package vaultapi

import (
  "context"
  "fmt"
  "github.com/skyflowapi/skyflow-go/v2/utils/logger"
  . "github.com/skyflowapi/skyflow-go/v2/client"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
)
/**
 * This example demonstrates how to invoke an external connection using the Skyflow SDK, along with corresponding InvokeConnectionRequest schema.
 *
 */


func main() {
  // Initialize Skyflow client 
  // Step 1: Define the request body parameters
  // These are the values you want to send in the request body
  ctx := context.TODO() // Define the context of the request
  body := map[string]interface{}{ // Set your data in the body of the request
    "<KEY>": "<VALUE>", // Example BODY
  }
  // Step 2: Define the request headers
  // Add any required headers that need to be sent with the request
  headers := map[string]string{ 
    "<HEADER_NAME_1>": "<HEADER_VALUE_1>", 
    "<HEADER_NAME_2>": "<HEADER_VALUE_2>", 
  }
  // Step 3: Define the path parameters
  // Path parameters are part of the URL and typically used in RESTful APIs
  pathParams := map[string]string{ 
    "<YOUR_PATH_PARAM_KEY_1>": "<YOUR_PATH_PARAM_VALUE_1>", 
  }
  // Step 4: Define the query parameters
  // Query parameters are included in the URL after a '?' and are used to filter or modify the response
  queryParams := map[string]interface{}{ 
    "<YOUR_QUERY_PARAM_KEY_1>": "<YOUR_QUERY_PARAM_VALUE_1>",
    "<YOUR_QUERY_PARAM_KEY_2>": "<YOUR_QUERY_PARAM_VALUE_2>",
  }
  // Step 5: Build the InvokeConnectionRequest
  // Construct the request by specifying method, headers, body, query parameters, and path parameters
  req := InvokeConnectionRequest{
    Method:      POST,        // The HTTP method to use for the request (POST in this case)
    Headers:     headers,     // The headers to include in the request
    Body:        body,        // Attach the request body
    QueryParams: queryParams,  // The query parameters to append to the URL
    PathParams:  pathParams,  // The path parameters for the URL
  }
  // Replace "<CONNECTION_ID>" with the actual connection ID you are using
  service, conError := client1.Connection("<CONNECTION_ID1>") // Replace with actual connection ID
  if conError != nil {
    // Handle errors when establishing the connection
    fmt.Println("Error:", conError) // Print the connection error if it occurs
  } else {
    // Step 6: Invoke the connection using the request
    // Send the request to the external connection and receive the response
    res, invokeError := service.Invoke(ctx, req) // Invoke the connection with the provided request
    if invokeError != nil {
      // Handle any errors that occur during the connection invocation
      fmt.Println("Error occurred ", *invokeError) // Print the error if the invocation fails
    } else {
      // Step 7: Print the response from the invoked connection
      // The response contains the result of the request sent to the external system
      fmt.Println("RESPONSE", res) // Print the successful response
    }
  }
}

method supports the following methods:

  • GET
  • POST
  • PUT
  • PATCH
  • DELETE

PathParams, QueryParams, RequestHeader, RequestBody are the objects represented as map, that will be sent through the connection integration url.

Tip

See the full example in the samples directory: invoke_connection.go See docs.skyflow.com for more details on integrations with Connections, Functions, and Pipelines.

import (
"context"
"fmt"
"github.com/skyflowapi/skyflow-go/v2/utils/logger"

. "github.com/skyflowapi/skyflow-go/v2/client"
. "github.com/skyflowapi/skyflow-go/v2/utils/common"
)
/**
 * This example demonstrates how to invoke an external connection using the Skyflow SDK.
 * It configures a connection, sets up the request, and sends a POST request to the external service.
 *
 * 1. Initialize Skyflow client with connection details.
 * 2. Define the request body, headers, and method.
 * 3. Execute the connection request.
 * 4. Print the response from the invoked connection.
 */

func main() {
    // Initialize Skyflow client 
    // Step 1: Set up credentials and connection configuration
    // Load credentials from a JSON file (you need to provide the correct path)
    credentials := Credentials{Path: "../cred.json"}

    // Define the connection configuration (URL and credentials)
    connConfig1 := ConnectionConfig{
    	ConnectionId: "<CONNECTION_ID1>", // Replace with actual connection ID
        ConnectionUrl: "https://connection.url.com", // Replace with actual connection URL
        Credentials: credentials, // Set credentials for the connection
    }
    // Add connection configurations to an array
    var arr []ConnectionConfig
    arr = append(arr, connConfig1)

    // Initialize the Skyflow client with the connection configuration
    skyflowClient, clientError := NewSkyflow(
                    WithConnections(arr...),       // Add the connection configurations to the client
                    WithLogLevel(logger.DEBUG),    // Set log level to DEBUG for detailed logs
                    )
    if clientError != nil {
        // Handle any errors that occur during Skyflow client initialization
        fmt.Println("Error:", clientError)
    } else {
        // Replace "<CONNECTION_ID1>" with the actual connection ID
        service, conError := skyflowClient.Connection("<CONNECTION_ID1>")
        if conError != nil {
        // Handle errors that occur during the connection setup
            fmt.Println("Error:", conError)
        } else {
            // Step 2: Define the request body and headers
            // Map for request body parameters
            ctx := context.TODO() // Define the context for the API call
            body := map[string]interface{}{ // Set your request data
                    "card_number": "4337-1696-5866-0865", // Example card number
                    "ssn": "524-41-4248",                // Example SSN
			}
        // Map for request headers
        headers := map[string]string{ // Set the request headers
            "Content-Type": "application/json", // Specify the content type for the request
        }
        // Step 3: Build the InvokeConnectionRequest with required parameters
        // Set HTTP method to POST, include the request body and headers
        req := InvokeConnectionRequest{
            Method:      POST,    // Set the HTTP method to POST
            Headers:     headers, // Add request headers
            Body:        body,    // Add the body with request data
        }

        // Step 4: Invoke the connection and capture the response
        res, invokeError := service.Invoke(ctx, req)
        if invokeError != nil {
            // Handle any errors that occur during the connection invocation
            fmt.Println("Error occurred ", *invokeError)
        } else {
            // Step 8: Print the response from the connection invocation
            fmt.Println("RESPONSE", res)
        }
        }
    }
}

Sample response:

{
  "data": {
    "card_number": "4337-1696-5866-0865",
    "ssn": "524-41-4248"
  },
  "metadata": {
    "requestId": "4a3453b5-7aa4-4373-98d7-cf102b1f6f97"
  }
}

Client management

After the Skyflow client is initialized, you can add, update, retrieve, and remove vault and connection configurations at runtime without recreating the client.

Vault management

Method Description
AddVaultConfig(config VaultConfig) Add a new vault after initialization
RemoveVaultConfig(vaultId string) Remove a vault by ID
UpdateVaultConfig(config VaultConfig) Update an existing vault configuration
GetVaultConfig(vaultId string) Retrieve a vault configuration by ID
import (
  "fmt"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
)

// Add a new vault
newVault := common.VaultConfig{
  VaultId:   "<NEW_VAULT_ID>",
  ClusterId: "<NEW_CLUSTER_ID>",
  Env:       common.PROD,
  Credentials: common.Credentials{Token: "<BEARER_TOKEN>"},
}
if err := skyflowClient.AddVaultConfig(newVault); err != nil {
  fmt.Println("Error adding vault:", err)
}

// Retrieve vault configuration
vaultCfg, err := skyflowClient.GetVaultConfig("<VAULT_ID>")
if err != nil {
  fmt.Println("Error getting vault config:", err)
} else {
  fmt.Println("Vault config:", vaultCfg)
}

// Update an existing vault configuration
updatedVault := common.VaultConfig{
  VaultId:   "<VAULT_ID>",
  ClusterId: "<NEW_CLUSTER_ID>",
  Env:       common.PROD,
}
if err := skyflowClient.UpdateVaultConfig(updatedVault); err != nil {
  fmt.Println("Error updating vault:", err)
}

// Remove a vault
if err := skyflowClient.RemoveVaultConfig("<VAULT_ID>"); err != nil {
  fmt.Println("Error removing vault:", err)
}

Connection management

Method Description
AddConnectionConfig(config ConnectionConfig) Add a new connection after initialization
RemoveConnectionConfig(connId string) Remove a connection by ID
UpdateConnectionConfig(config ConnectionConfig) Update an existing connection configuration
GetConnectionConfig(connId string) Retrieve a connection configuration by ID

Credential management

Method Description
AddSkyflowCredentials(config Credentials) Add client-level credentials
UpdateSkyflowCredentials(credentials Credentials) Update client-level credentials
GetSkyflowCredentials() Get current client-level credentials

Log level management

Method Description
UpdateLogLevel(logLevel LogLevel) Update the log level at runtime
GetLoglevel() Get the current log level
import "github.com/skyflowapi/skyflow-go/v2/utils/logger"

// Change log level at runtime
skyflowClient.UpdateLogLevel(logger.INFO)

// Get current log level
level := skyflowClient.GetLoglevel()
fmt.Println("Current log level:", *level)

Authentication & authorization

Types of credentials

The SDK accepts one of several credential types. Only one type can be used at a time.

  1. API key — A unique identifier used to authenticate and authorize requests to an API. Use for long-term service authentication.

    credentials := common.Credentials{
        ApiKey: "<YOUR_API_KEY>",
    }
  2. Bearer token — A temporary access token used to authenticate API requests. Use for optimal security.

    credentials := common.Credentials{
        Token: "<YOUR_BEARER_TOKEN>",
    }
  3. Service account credentials file path — The file path pointing to a JSON file containing credentials for a service account. Use when credentials are managed externally or stored in secure file systems.

    credentials := common.Credentials{
        Path: "<PATH_TO_CREDENTIALS_JSON_FILE>",
    }
  4. Service account credentials string — A JSON-formatted string containing service account credentials. Use when integrating with secret management systems or when credentials are passed programmatically.

    credentials := common.Credentials{
        CredentialsString: "<CREDENTIALS_JSON_AS_STRING>",
    }
  5. Environment variable — If no credentials are explicitly provided, the SDK automatically looks for the SKYFLOW_CREDENTIALS environment variable. Use to avoid hardcoding credentials in source code.

Note

Only one type of credential can be used at a time. If multiple credentials are provided, the individual vault-level credentials take precedence over common credentials, and common credentials take precedence over the environment variable.

Generate bearer tokens for authentication & authorization

Generate and manage bearer tokens to authenticate API calls. This section covers options for scoping to certain roles, passing context, and signing data tokens.

  • Generate a bearer token: Enable the creation of bearer tokens using service account credentials. These tokens, valid for 60 minutes, provide secure access to Vault services and management APIs based on the service account's permissions.
  • Generate a bearer token with context: Support embedding context values into bearer tokens, enabling dynamic access control and the ability to track end-user identity.
  • Generate a scoped bearer token: Facilitate the creation of bearer tokens with role-specific access, ensuring permissions are limited to the operations allowed by the designated role.
  • Generate signed data tokens: Add an extra layer of security by digitally signing data tokens with the service account's private key.

Generate a bearer token

The Service Account go module is designed to generate service account tokens using a service account credentials file, which is provided when a service account is created. The tokens generated by this module are valid for 60 minutes and can be used to make API calls to Vault services and management APIs, depending on the permissions assigned to the service account.

The GenerateBearerToken(filepath) utility provides functionality for generating bearer tokens using a credentials JSON file. Alternatively, you can pass the credentials as a string to achieve the same result.

Tip

See the full example in the samples directory: service_account_token.go

import (
"fmt"
saUtil "github.com/skyflowapi/skyflow-go/v2/serviceaccount"
"github.com/skyflowapi/skyflow-go/v2/utils/common"
"github.com/skyflowapi/skyflow-go/v2/utils/logger"
)
/**
 * Example program to generate a Bearer Token using Skyflow's BearerToken utility.
 * The token can be generated in two ways:
 * 1. Using the file path to a credentials.json file.
 * 2. Using the JSON content of the credentials file as a string.
 */
func BearerTokenGenerationExample() {
    // Variable to store the generated token
    var token string

    // Example 1: Generate Bearer Token using a credentials.json file
    // Specify the full file path to the credentials.json file
    var filePath = "<YOUR_CREDENTIALS_FILE_PATH>"

    // Check if the token is either not initialized or has expired
    if saUtil.IsExpired(token) {
        // Create a BearerToken using the credentials file
        res, err := saUtil.GenerateBearerToken(filePath, common.BearerTokenOptions{
                LogLevel: logger.DEBUG,
                })
        if err != nil {
            fmt.Println("errors", *err)
        } else {
            token = res.AccessToken
        }
    }

    // Print the generated Bearer Token to the console
    fmt.Println("Generated Bearer Token (from file): " + token)

    // Example 2: Generate Bearer Token using the credentials JSON as a string
    // Provide the credentials JSON content as a string
    var fileContents = "<YOUR_CREDENTIALS_FILE_CONTENTS_AS_STRING>"

    // Check if the token is either not initialized or has expired
    if saUtil.IsExpired(token) {
    // Create a BearerToken using the credentials string
        res, err := saUtil.GenerateBearerTokenFromCreds(fileContents, common.BearerTokenOptions{
            LogLevel: logger.DEBUG,
            })
        if err != nil {
            fmt.Println("Errors", *err)
        } else {
            fmt.Println("Token", res.AccessToken)
        }
        token = res.AccessToken
    }
    // Print the generated Bearer Token to the console
    fmt.Println("Generated Bearer Token: " + token)
}

Generate bearer tokens with context

Context-Aware Authorization embeds context values into a bearer token during its generation so you can reference those values in your policies. This enables more flexible access controls, such as helping you track end-user identity when making API calls using service accounts, and facilitates using signed data tokens during detokenization.

A service account with the context_id identifier generates bearer tokens containing context information, represented as a JWT claim in a Skyflow-generated bearer token. Tokens generated from such service accounts include a context_identifier claim, are valid for 60 minutes, and can be used to make API calls to the Data and Management APIs, depending on the service account's permissions.

The Ctx field accepts either a string or a map[string]interface{}:

String context — use when your policy references a single context value:

res, err := serviceaccount.GenerateBearerToken(filePath, common.BearerTokenOptions{
    Ctx: "user_12345",
})

JSON object context — use when your policy needs multiple context values for conditional data access. Each key in the map maps to a Skyflow CEL policy variable under request.context.*:

ctxMap := map[string]interface{}{
    "role":       "admin",
    "department": "finance",
    "user_id":    "user_12345",
}
res, err := serviceaccount.GenerateBearerToken(filePath, common.BearerTokenOptions{
    Ctx: ctxMap,
})

With the map above, your Skyflow policies can reference request.context.role, request.context.department, and request.context.user_id to make conditional access decisions.

You can also set context on Credentials for automatic token generation:

// String context
creds := common.Credentials{
    Path:    "path/to/credentials.json",
    Context: "user_12345",
}

// Map context
creds := common.Credentials{
    Path: "path/to/credentials.json",
    Context: map[string]interface{}{
        "role":       "admin",
        "department": "finance",
    },
}

Context map keys must contain only alphanumeric characters and underscores ([a-zA-Z0-9_]). Invalid keys will return a SkyflowError.

Tip

See the full example in the samples directory: token_generation_with_context.go See Skyflow's context-aware authorization and conditional data access docs for policy variable syntax like request.context.*.

Generate scoped bearer tokens

A service account with multiple roles can generate bearer tokens with access limited to a specific role by specifying the appropriate roleID. It can be used to limit access to specific roles for services with multiple responsibilities, such as segregating access for billing vs. analytics. The generated bearer tokens are valid for 60 minutes and can only execute operations permitted by the permissions associated with the designated role.

Tip

See the full example in the samples directory: scoped_token_generation.go See docs.skyflow.com for more details on authentication, access control, and governance for Skyflow.

import (
"fmt"
saUtil "github.com/skyflowapi/skyflow-go/v2/serviceaccount"
"github.com/skyflowapi/skyflow-go/v2/utils/common"
"github.com/skyflowapi/skyflow-go/v2/utils/logger"
)

/**
 * Example program to generate a Scoped Token using Skyflow's BearerToken utility.
 * The token is generated by providing the file path to the credentials.json file
 * and specifying roles associated with the token.
 */
func ScopedTokenGenerationExample() {
    // Variable to store the generated scoped token
    var scopedToken interface{}

    // Example: Generate Scoped Token by specifying the credentials.json file path
    // Create a list of roles that the generated token will be scoped to
    var roles = []string{"<ROLE_ID_1>", "<ROLE_ID_2>", "<ROLE_ID_3>"}

    // Specify the full file path to the service account's credentials.json file
    var filePath = "<YOUR_CREDENTIALS_FILE_PATH>"

    // Create a BearerToken using the credentials file and associated roles
    res, err := saUtil.GenerateBearerToken(filePath, common.BearerTokenOptions{LogLevel: logger.DEBUG, RoleIds: roles}) // Set the roles that the token should be scoped to

    if err != nil {
        fmt.Println("Errors", *err)
	} else {
        // retrieve token
        fmt.Println("Token", res.AccessToken)
    }

    // Retrieve the generated scoped token
    scopedToken = res.AccessToken

    // Print the generated scoped token to the console
    fmt.Println(scopedToken);
}

Generate signed data tokens

Skyflow generates data tokens when sensitive data is inserted into the vault. These data tokens can be digitally signed with a service account's private key, adding an extra layer of protection. Signed tokens can only be detokenized by providing the signed data token along with a bearer token generated from the service account's credentials. The service account must have the necessary permissions and context to successfully detokenize the signed data tokens.

Tip

See the full example in the samples directory: signed_token_generation.go See docs.skyflow.com for more details on authentication, access control, and governance for Skyflow.

import (
"fmt"
saUtil "github.com/skyflowapi/skyflow-go/v2/serviceaccount"
"github.com/skyflowapi/skyflow-go/v2/utils/common"
"github.com/skyflowapi/skyflow-go/v2/utils/logger"
)

// Example program to generate Signed Data Tokens using Skyflow's SignedDataTokens utility.
// Signed Data Tokens can be generated in two ways:
// 1. By specifying the file path to the credentials.json file.
// 2. By providing the credentials as a JSON string.
func SignedTokenGenerationExample() {
    // Example 1: Generate Signed Data Tokens by specifying the credentials.json file path
    // File path to the service account's credentials.json file
    var filePath = "<YOUR_CREDENTIALS_FILE_PATH>";

    // Context value to associate with the token
    var context = "abc";

    var tokens []string
    tokens = append(tokens, "<TOKEN>") // List of data tokens to sign; replace with your actual data tokens

    // Build the SignedDataTokensOptions object using the file path and required configurations
    options := common.SignedDataTokensOptions{
        Ctx: context, // Set the context value
        DataTokens: tokens,  // Set the data tokens to be signed
        TimeToLive: 60, // Set the token's time-to-live (TTL) in seconds
        LogLevel: logger.ERROR,
    }
    // Generate and retrieve the signed data tokens
    res, err := saUtil.GenerateSignedDataTokens(filePath, options)
    if err != nil {
        fmt.Println("Error occurred ", err)
    } else {
        // retrieve the signed data tokens 
        fmt.Println("RESPONSE:", res)
    }

    // Example 2: Generate Signed Data Tokens by specifying credentials as a JSON string
    // Provide the credentials JSON content as a string
    var fileContents = "<YOUR_CREDENTIALS_FILE_CONTENTS_AS_STRING>";

    // Context value to associate with the token
    context = "abc";

    tokens = nil
    tokens = append(tokens, "<TOKEN>")

    // Create the SignedDataTokensOptions object using the required configurations
    options = common.SignedDataTokensOptions{
        DataTokens: tokens,  // Set the data tokens to be signed
        TimeToLive: 60, // in seconds
        LogLevel: logger.ERROR,
    }
    // Generate and retrieve the signed data tokens
    res, err = saUtil.GenerateSignedDataTokensFromCreds(fileContents, options)

    if err != nil {
        fmt.Println("Error occurred ", err)
    } else {
        // retrieve the signed data tokens 
        fmt.Println("RESPONSE: ", res)
    }
}

Response:

[
  {
    "Token":"5530-4316-0674-5748",
    "signedToken":"signed_token_eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJzLCpZjA"
  }
]

Notes:

  • The time to live (TTL) value should be specified in seconds.
  • By default, the TTL value is set to 60 seconds.

Bearer token expiry edge case

When you use bearer tokens for authentication and API requests in SDKs, there's the potential for a token to expire after the token is verified as valid but before the actual API call is made, causing the request to fail unexpectedly due to the token's expiration. An error from this edge case would look something like this:

message: Authentication failed. Bearer token is expired. Use a valid bearer token. See https://docs.skyflow.com/api-authentication/

If you encounter this kind of error, retry the request. During the retry, the SDK detects that the previous bearer token has expired and generates a new one for the current and subsequent requests.

Tip

See the full example in the samples directory: bearer_token_expiry_example.go See docs.skyflow.com for more details on authentication, access control, and governance for Skyflow.

package serviceaccount

import (
	"context"
	"fmt"
	"github.com/skyflowapi/skyflow-go/v2/client"
	"github.com/skyflowapi/skyflow-go/v2/utils/common"
	"github.com/skyflowapi/skyflow-go/v2/utils/error"
	"github.com/skyflowapi/skyflow-go/v2/utils/logger"
)
//   * This example demonstrates how to configure and use the Skyflow SDK
//   * to detokenize sensitive data stored in a Skyflow vault.
//   * It includes setting up credentials, configuring the vault, and
//   * making a detokenization request. The code also implements a retry
//   * mechanism to handle unauthorized access errors (HTTP 401).
func DetokenizeData(skyflowClient, vaultID) error.SkyflowError {
	service, serviceError := skyflowInstance.Vault(vaultID)
	if serviceError != nil {
		fmt.Println(serviceError)
		return serviceError
	} else {
		ctx := context.TODO()
		//  Creating a list of tokens to be detokenized
		detokenizeData := []common.DetokenizeData{
			{
				Token:         "<TOKEN1>",
				RedactionType: common.REDACTED,
			},
			{
				Token:         "<TOKEN2>",
				RedactionType: common.MASKED,
			},
		}
		//  Building a detokenization request
		req := common.DetokenizeRequest{DetokenizeData: detokenizeData}
		//  Sending the detokenization request and receiving the response
		res, errDetokenize := service.Detokenize(ctx, req, common.DetokenizeOptions{
			ContinueOnError: true,
		})
		if errDetokenize != nil {
			
			fmt.Println("Unexpected error occurred: ", errDetokenize)
			return errDetokenize
		} else {
			// Printing the detokenized response
			fmt.Println("Skyflow error occurred: ", res)
		}
	}
	return nil
}
func main(){
	// Setting up credentials for accessing the Skyflow vault
	//  Credentials string for authentication
	credentials := common.Credentials{
		CredentialsString: "<STRINGIFIED_JSON_VALUE>", 
	}

	// Configuring the Skyflow vault with necessary details
	privaryVaultConfig := common.VaultConfig{
		VaultId:     "<YOUR_VAULT_ID1>",
		ClusterId:   "<YOUR_CLUSTER_ID1>",
		Env:         common.DEV,
		Credentials: credentials,
	}
	// Create a new Skyflow client
	skyflowClient, err := client.NewSkyflow(
		client.WithVaults(privaryVaultConfig),
		client.WithCredentials(credentials),
		client.WithLogLevel(logger.DEBUG),
	)
	if err != nil {
		fmt.Println("Error creating Skyflow client:", err)
		return
	}
	//  Attempting to detokenize data using the Skyflow client
	err = DetokenizeData(skyflowClient, "<VAULT_ID>")
	if err != nil {
		fmt.Println("Error detokenizing data:", err)
		// Retry detokenization if the error is due to unauthorized access (HTTP 401)
		if err.GetHttpCode() == "401" {
			fmt.Println("Unauthorized access. Retrying...")
			err2 := DetokenizeData(skyflowClient, "<VAULT_ID>")
			if err2 != nil {
				fmt.Println("Error detokenizing data on retry:", err2)
			} else {
				fmt.Println("Detokenization successful on retry")
			}
		}
		return
	} else {
		fmt.Println("Detokenization successful")
	}
}

Logging

The Skyflow Go SDK provides useful logging using go's built-in logging library. By default, the SDK's logging level is set to LogLevel.ERROR. This can be changed using the UpdateLogLevel(logLevel) method as shown below.

Currently, the following five log levels are supported:

  • DEBUG:

    When LogLevel.DEBUG is passed, logs at all levels will be printed (DEBUG, INFO, WARN, ERROR).

  • INFO:

    When LogLevel.INFO is passed, INFO logs for every event that occurs during SDK flow execution will be printed, along with WARN and ERROR logs.

  • WARN:

    When LogLevel.WARN is passed, only WARN and ERROR logs will be printed.

  • ERROR:

    When LogLevel.ERROR is passed, only ERROR logs will be printed.

  • OFF: LogLevel.OFF can be used to turn off all logging from the Skyflow Go SDK.

Note: The ranking of logging levels is as follows: DEBUG < INFO < WARN < ERROR < OFF.

Example: Setting LogLevel to INFO

package main

import (
  "fmt"
  "github.com/skyflowapi/skyflow-go/v2/client"
  "github.com/skyflowapi/skyflow-go/v2/utils/common"
  "github.com/skyflowapi/skyflow-go/v2/utils/logger"
)

/**
 * This example demonstrates how to configure the Skyflow client with custom log levels
 * and authentication credentials (either token, credentials string, or other methods).
 * It also shows how to configure a vault connection using specific parameters.
 *
 * 1. Set up credentials with a Bearer token or credentials string.
 * 2. Define the Vault configuration.
 * 3. Build the Skyflow client with the chosen configuration and set log level.
 * 4. Example of changing the log level from ERROR (default) to INFO.
 */
func main() {
  // Step 1: Set up credentials - either pass token or use credentials string
  // In this case, we are using a Bearer token for authentication.
  credentials := common.Credentials{
    Token: "<BEARER_TOKEN>",        // Replace with the actual Bearer token
  }
  // Step 2: Define the Vault configuration
  // Configure the vault with necessary details like vault ID, cluster ID, and environment
  config := common.VaultConfig{
    VaultId:   "<VAULT_ID>",            // Replace with the actual Vault ID (first vault)
    ClusterId: "<CLUSTER_ID>",          // Replace with the actual Cluster ID (from vault URL)
    Env:       common.DEV,               // Set the environment (default is DEV, can also use PROD)
    Credentials: credentials,
  }
  credentialString := "<CREDENTIAL_AS_JSON_STRING>"
  skyflowCredentials := common.Credentials{
    CredentialsString: credentialString,
  }
  // Step 2: Define the Vault configuration
  // Create an array of Vault configurations to be used for multiple Vaults.
  var arr []common.VaultConfig
  arr = append(arr, config) // Add Vault configurations to the array

  // Step 3: Build the Skyflow client with the chosen configuration and log level
  // Using the Vault configurations and setting the log level to DEBUG.
  skyflowClient, err := client.NewSkyflow(
    client.WithVaults(arr...),              // Add the Vault configurations from the array
    client.WithCredentials(skyflowCredentials), // Use Skyflow credentials if no token is passed
    client.WithLogLevel(logger.INFO),     // Set log level to INFO (default is ERROR)
  )

  // Step 4: Handle any errors that occur during client creation
  if err != nil {
    // Print the error if something went wrong during client initialization
    fmt.Println("Error occurred while creating Skyflow client:", err)
  } else {
    skyflowClient.UpdateLogLevel(logger.DEBUG)
  }

  // Step 5: Client is now ready to use with the specified log level and credentials
  fmt.Println("Skyflow client has been successfully configured with log level: DEBUG.")
}

Error handling

Catching SkyflowError instances

All SDK methods return *skyflowError.SkyflowError as the error type. Check for nil before accessing the error fields.

SkyflowError methods:

Method Return type Description
GetMessage() string Human-readable error message, prefixed with Message: .
GetHttpCode() string HTTP status code, for example "400", "401", "500". "499" when the call's context was cancelled or its deadline passed. "0" (with an empty GetHttpStatusCode()) when no usable HTTP response came back. Use this for comparisons.
GetHttpCodeInt() int GetHttpCode() as a number; 0 when there is no HTTP code.
GetHttpStatusCode() string HTTP status text, not the numeric code: the http_status from a Skyflow JSON error body (for example "PERMISSION_DENIED"), otherwise the response status line (for example "401 Unauthorized"). "Bad Request" for validation errors raised before any network call. Empty when GetHttpCode() is "0".
GetCode() string Deprecated — use GetHttpCode(). Returns the code prefixed with Code: , for example "Code: 401", so it can't be compared to a bare status code.
GetRequestId() string Request ID for tracing and support. Empty when there was no server response.
GetGrpcCode() string gRPC status code when applicable.
GetGrpcCodeInt() int GetGrpcCode() as a number; 0 when the server sent none.
GetDetails() []interface{} Structured error details array from the API response.
GetResponseBody() map[string]interface{} Decoded JSON error body of an API error; nil for validation, network and non-JSON errors.
import (
    "fmt"
    skyflowError "github.com/skyflowapi/skyflow-go/v2/utils/error"
)

res, err := service.Insert(ctx, insertRequest)
if err != nil {
    fmt.Println("HTTP code:", err.GetHttpCode())
    fmt.Println("HTTP status:", err.GetHttpStatusCode())
    fmt.Println("message:", err.GetMessage())
    fmt.Println("request ID:", err.GetRequestId())
    fmt.Println("details:", err.GetDetails())
}
_ = res

Detect run status

A *SkyflowError reports a Detect call that failed. A de-identify file run can also end without an error but with a status that needs handling. Check Status on the DeidentifyFile (polled) or GetRun response:

Status Meaning What to do
DetectRunStatusSuccess The run finished. Read Output. A polled local file's outputs are also written to OutputDirectory.
DetectRunStatusInProgress, DetectRunStatusQueued The poll wait ran out before the run finished. Keep RunId and call GetRun later.
DetectRunStatusFailed, DetectRunStatusUnknown The run failed. Message says why.
empty DeidentifyFile wasn't polled. Only RunId is set: call GetRun.

When a lookup or an output write fails during a polled DeidentifyFile, the call returns both the error and the response, so check response.RunId before giving up on the run.

Common Detect errors

These come back from the server as a *SkyflowError. GetMessage() has the server's reason; quote GetRequestId() if you contact support.

Cause Status Fix
Both ConfigurationId and Configuration are set. The SDK sends both, and the API rejects the pair. 400 Set one.
An entity or custom type uses DeidentificationTypeVaultToken without a Destination, or with a table or column that doesn't exist. Detect doesn't create them. 400 Set Destination to an existing "<TABLE_NAME>.<COLUMN_NAME>" (names are case-sensitive).
DeidentificationTypeVaultToken in a file whose format doesn't support it. Only txt, csv, json, jsonl, xml, docx, xlsx and pptx do. 400 Use another de-identification type for that file, or convert it.
PrefixOverride set together with IncludePrefixNo. 400 Drop one of them.
A missing role, or re-identifying vault tokens without permission to detokenize. Detect needs the Detect Invoker, Detect Manager or Vault Owner role; re-identification also needs a policy granting the Detokenization action on the destination table and columns, unless the caller is a Vault Owner. 403 Grant the role or policy.

The SDK rejects some mistakes itself, before any request, with a 400 *SkyflowError and no request ID. Examples: no file source in DeidentifyFile, OutputDirectory without Poll, and a Poll limit out of range.

Errors without a server response also have no request ID. GetHttpCode() is "0" (with an empty GetHttpStatusCode()) when no usable HTTP response came back: a network failure, a call that ran past its timeout, or a response body that couldn't be read. It is also "0" when there was no HTTP exchange at all, for example a local file that exists but can't be read ("Failed to encode the file…") or an output file that can't be written. It is "499" only when the caller's context was cancelled or its deadline passed. Unwrap() returns the underlying error in these cases, so errors.Is / errors.As work. A missing local file is reported before the Poll options are checked.

For an API error, GetHttpCode() is always the response's HTTP status. When the body isn't a Skyflow JSON error, the message is, in order: an error string in the body, a top-level message, the body itself (only its first 512 bytes are kept), or "Error with status code <N>" for an empty body. An error-from-client response header is added to GetDetails() as errorFromClient.

Bearer token expiration edge cases

When using bearer tokens for authentication, a token may expire after validation but before the actual API call completes. This causes the request to fail unexpectedly. An error from this edge case looks like this:

message: Authentication failed. Bearer token is expired. Use a valid bearer token. See https://docs.skyflow.com/api-authentication/

If you encounter this kind of error, retry the request. During the retry, the SDK detects that the previous bearer token has expired and generates a new one for the current and subsequent requests.

Security

Reporting a Vulnerability

If you discover a potential security issue in this project, please reach out to us at security@skyflow.com. Please refrain from creating public GitHub issues or pull requests, as malicious actors could potentially view them.

About

Skyflow SDK for the Go programming language.

Topics

Resources

Contributing

Security policy

Stars

20 stars

Watchers

14 watching

Forks

Releases

Packages

Used by

Contributors

Languages