Query User Data from an API
This blueprint provides a guide to securely share Personal Identifiable Information (PII) with Clients querying your Server API, without having to store sensitive data on your own database.
We will use Terraform to provision Basis Theory resources and https://echo.basistheory.com to represent the API. If you are not using Terraform, you can call Basis Theory APIs directly.
Creating the Inbound Proxy
In order to listen to API requests, we will create a Proxy that sits between the Client and your Server. We will assume these requests don't contain any sensitive information, so we will pass them through to the Server, which will respond with tokenized data. The Proxy will then transform the Server response to detokenize it and respond to the Client with the plaintext data.
Create a Management Application
Management Applications are used to manage Basis Theory Tenants settings and services. We will create a new Application and pass its key to the Terraform provider. If you want to make direct API calls for these purposes, you can use that application key to authenticate your requests.
Create a Management Application with the permissions Terraform needs to manage the Proxy: proxy:create, proxy:read, proxy:update, and proxy:delete. If you use cURL, you only need proxy:create and proxy:read to create the Proxy and check its state.
Install Basis Theory Terraform Provider
Add the Basis Theory Terraform provider to your configuration. It supports execution roles for Proxy code transforms.
terraform {
required_providers {
basistheory = {
source = "Basis-Theory/basistheory"
version = ">= 5.3.0"
}
}
}
variable "management_api_key" {}
provider "basistheory" {
api_key = var.management_api_key
}
Paste the API key to your terraform.tfvars file:
management_api_key = "<API_KEY>"
Initialize Terraform:
terraform init
Add Terraform Resources
Now that we have Terraform set up, let's add the required resources to start proxying requests to our Server.
Execution Role
The Proxy's response transform needs to read tokens in /pii/high/ and return their plaintext values. Both creation examples grant token:read with the reveal transform in a runtime execution role scoped to that container. On each invocation, Basis Theory passes a short-lived API key with this access to the code in event.applicationOptions.
Proxy Resource
Next, we will create a Proxy capable of passing Client requests to a certain destination URL (Server), listen to the response and detokenize part of its body, and respond with the transformed content back to the Client.
Create a detokenize.js file with the following code. The transform calls the Get a Token API with the execution role's API key:
const { BasisTheoryClient } = require("@basis-theory/node-sdk");
module.exports = async function (event) {
const { res, applicationOptions } = event;
const { body, headers } = res;
const destinationStatus = Object.entries(headers).find(
([name]) => name.toLowerCase() === "bt-proxy-destination-status"
)?.[1];
if (Number(destinationStatus) >= 300) {
return { res };
}
const client = new BasisTheoryClient({
apiKey: applicationOptions.apiKey,
baseUrl: applicationOptions.baseUrl,
});
try {
const token = await client.tokens.get(body.json.ssn);
return { res: { body: { ssn: token.data }, headers } };
} catch (error) {
if (error.statusCode === 400 || error.statusCode === 404) {
return { res: { statusCode: 400, body: { error: "Invalid SSN token ID" }, headers } };
}
throw error;
}
};
Add the Proxy resource to your Terraform configuration, or call the Create a Proxy API with cURL:
- Terraform
- cURL
resource "basistheory_proxy" "inbound_proxy" {
name = "Inbound Proxy"
destination_url = "https://echo.basistheory.com/anything"
require_auth = false
response_transforms {
type = "code"
code = file("./detokenize.js")
options {
runtime {
image = "node24"
dependencies = {
"@basis-theory/node-sdk" = "6.3.0"
}
execution_role {
rule {
description = "Read PII Tokens"
priority = 1
container = "/pii/high/"
transform = "reveal"
permissions = ["token:read"]
}
}
}
}
}
}
output "inbound_proxy_key" {
value = basistheory_proxy.inbound_proxy.key
description = "Inbound Proxy Key"
sensitive = true
}
The following command uses jq to load detokenize.js into the request body.
curl 'https://api.basistheory.com/proxies' \
-X 'POST' \
-H 'BT-API-KEY: <API_KEY>' \
-H 'Content-Type: application/json' \
--data "$(jq -n --rawfile code detokenize.js '{
"name": "Inbound Proxy",
"destination_url": "https://echo.basistheory.com/anything",
"response_transforms": [{
"type": "code",
"code": $code,
"options": {
"runtime": {
"image": "node24",
"dependencies": { "@basis-theory/node-sdk": "6.3.0" },
"execution_role": {
"rules": [{
"description": "Read PII Tokens",
"priority": 1,
"container": "/pii/high/",
"transform": "reveal",
"permissions": ["token:read"]
}]
}
}
}
}],
"require_auth": false
}')"
Use only synthetic data with the Echo Server. With require_auth set to false, a client that knows the Proxy key can invoke it without Basis Theory credentials. When you replace the Echo Server with your own API, authenticate each caller and authorize access to the requested data before returning tokens.
If you are using Terraform, apply the configuration:
terraform apply
For Terraform, save the inbound_proxy_key output after terraform apply completes. For cURL, save the key from the create response and use the id with the Get a Proxy API to wait until the Proxy's state is active.
Using the Inbound Proxy
Our scenario is a typical Inbound Detokenization setup. This means that by the time the Client queries the Server for User Data, it should exist already in the form of tokens. In the following steps, we will create a Social Security Number token and use the Proxy to retrieve its value.
Create a Token
There are many ways of collecting data with Basis Theory. Since our goal is to share data using the Proxy, we will take the easy route to create new tokens.
Public Application
To securely create PII tokens, you'll need a Public Application using our template Collect PII Data. Click here to create one.
This will create a application with the following Access Controls:
- Permissions:
token:create,token:update - Containers:
/pii/ - Transform:
mask
Tokenization
Call the Create Token token endpoint, using the key from the previous step:
curl "https://api.basistheory.com/tokens" \
-X "POST" \
-H "BT-API-KEY: <API_KEY>" \
-H "Content-Type: application/json" \
-d '{
"type": "social_security_number",
"data": "123456789"
}'
You should see a JSON response similar to:
{
"id": "f4867f40-a772-44d4-937a-1bb8c6dd322b",
"type": "social_security_number",
"tenant_id": "88b4fab9-eb9c-494f-a8fa-9e4847eac788",
"data": "XXXXX6789",
"created_by": "8b8fbf07-2f1e-4b45-bf0f-f2e651b112e0",
"created_at": "2022-12-15T13:09:25.9869097+00:00",
"fingerprint": "JE2WHCSeKCZUF5WMVavMZSvqQ61xf2zhCpYMieLoz9AD",
"fingerprint_expression": "{{ data | remove: '-' }}",
"mask": "{{ data | reveal_last: 4 }}",
"search_indexes": [
"{{ data }}",
"{{ data | replace: '-' }}",
"{{ data | last4 }}"
],
"containers": [
"/pii/high/"
]
}
Copy the id to use in the next step.
Invoking the Proxy
Now it is time to finally test the Proxy with our recently created token. We will use the token id as part of our request payload, so it is echoed back from our destination Server and detokenized at the Proxy response transform code.
Use the saved Proxy key to invoke the active Proxy. Replace inbound_proxy_key with your Proxy key and use the token id you copied in the previous step:
curl 'https://api.basistheory.com/proxy?bt-proxy-key=inbound_proxy_key' \
-X 'POST' \
-H 'Content-Type: application/json' \
--data '{
"ssn": "f4867f40-a772-44d4-937a-1bb8c6dd322b"
}'
You should see a JSON response like:
{
"ssn": "123456789"
}
What is Happening?
Basis Theory forwards the request to the Echo Server. The Proxy's response transform reads the token id from event.res.body.json.ssn, uses the execution role to retrieve the token, and returns its plaintext data in the ssn field.
This allows you to share sensitive PII data to any Client, without touching the data and, therefore, keeping your systems out of PII regulation scope.
Conclusion
Following this Blueprint enables you to meet regulatory requirements for storing and sharing sensitive PII by using Tokenization. This approach reliefs the burden of having to implement your own data encryption to protect customers privacy.
Have feedback or questions? Reach out to us at support@basistheory.com.