FastPII Docs
FastPII Connect

TypeScript SDK

TypeScript SDK reference for FastPII Connect with detection, protection, validation, batch operations, health, session management, and Gateway access.

TypeScript SDK

Complete API reference for the FastPIIClient TypeScript class, response types, and error handling.

Installation

npm install fastpii-connect
# or
pnpm add fastpii-connect
# or
yarn add fastpii-connect

Requires Node.js 18+.

FastPIIClient

import { FastPIIClient } from "fastpii-connect";

const client = new FastPIIClient({
  apiKey: "fpk_your_api_key",
  baseUrl: "https://api.fastpii.com", // default
  timeout: 30,        // request timeout in seconds
  maxRetries: 2,      // retries for 408, 429, 502, 503, 504 errors
});

Constructor parameters

ParameterTypeDefaultDescription
apiKeystringFASTPII_API_KEY env varYour FastPII API key (starts with fpk_)
baseUrlstring"https://api.fastpii.com"API base URL (or FASTPII_BASE_URL env var)
timeoutnumber30Request timeout in seconds
maxRetriesnumber2Number of retries for transient errors

The client sends the API key as an X-API-Key header on every request. It automatically retries on status codes 408, 429, 502, 503, and 504 with exponential backoff and jitter.

All methods are async and return Promises.

Methods

detect

Detect sensitive data entities in text. Calls POST /api/v1/detect.

const result = await client.detect("My rodné číslo is 900101/1234", {
  country: "cz",            // optional: ISO country code
  language: "cs",           // optional: language hint
  privacy_preset: "balanced", // optional: "conservative", "balanced", "aggressive"
});

for (const entity of result.entities) {
  console.log(`Found ${entity.type}: ${entity.original}`);
}
ParameterTypeRequiredDescription
textstringYesText to scan (1–50,000 characters)
options.countrystringNoISO 3166-1 alpha-2 country code. Auto-detected if omitted.
options.languagestringNoLanguage hint for detection
options.privacy_presetstringNo"conservative", "balanced", or "aggressive"

Returns a DetectResponse. See Detection API for the full response structure.

protect

Protect sensitive data in text using the specified mode. Calls POST /api/v1/protect.

const result = await client.protect("My rodné číslo is 900101/1234", {
  mode: "replace",         // "replace", "mask", "hash", "tokenize"
  country: "cz",           // optional
  language: "cs",          // optional
  privacy_preset: "aggressive", // optional
});

console.log(result.protected_text);
ParameterTypeRequiredDefaultDescription
textstringYes-Text to protect (1–50,000 characters)
options.modestringNo"replace"Protection mode: replace, mask, hash, tokenize
options.countrystringNoNoneISO country code
options.languagestringNoNoneLanguage hint
options.privacy_presetstringNoNonePrivacy preset

Returns a ProtectResponse. See Protection API for the full response structure.

validate

Validate a specific identifier. Calls POST /api/v1/validate.

const result = await client.validate("900101/1234", {
  entity_type: "rodne_cislo",
  country: "cz",  // optional
});

console.log(`Valid: ${result.valid}, Confidence: ${result.confidence}`);
ParameterTypeRequiredDescription
valuestringYesValue to validate
options.entity_typestringYesEntity type (e.g., "rodne_cislo", "pesel", "steuer_id")
options.countrystringNoISO country code

Returns a ValidateResponse.

listDetectors

List available detectors. Calls GET /api/v1/detectors.

const detectors = await client.listDetectors({ country: "CZ" });
for (const d of detectors.detectors) {
  console.log(`${d.name} (${d.region}): ${d.description}`);
}
ParameterTypeRequiredDescription
options.countrystringNoFilter by ISO country code

Returns a DetectorsResponse.

detectBatch

Detect sensitive data in multiple texts. Calls POST /api/v1/detect/batch.

const result = await client.detectBatch(
  ["Text one", "Text two", "Text three"],
  { country: "cz" }
);

console.log(`Total entities: ${result.total_entities}`);
ParameterTypeRequiredDescription
textsstring[]YesTexts to scan (1–50, each max 50,000 chars)
options.countrystringNoISO country code
options.languagestringNoLanguage hint
options.privacy_presetstringNoPrivacy preset

Returns a DetectBatchResponse. See batch detection for details.

protectBatch

Protect sensitive data in multiple texts. Calls POST /api/v1/protect/batch.

const result = await client.protectBatch(
  ["Text one", "Text two"],
  { mode: "mask", country: "cz" }
);

console.log(`Total entities: ${result.total_entities}`);
ParameterTypeRequiredDescription
textsstring[]YesTexts to protect (1–50, each max 50,000 chars)
options.modestringNoProtection mode (default "replace")
options.countrystringNoISO country code
options.languagestringNoLanguage hint
options.privacy_presetstringNoPrivacy preset

Returns a ProtectBatchResponse. See batch protection for details.

health

Check the API health status. Calls GET /api/v1/health.

const health = await client.health();
console.log(`Status: ${health.status}, Version: ${health.version}`);

Returns a HealthResponse with status, version, and environment fields.

Session management

Create a session that tracks detected countries across calls.

const session = new Session(client);

const result1 = await session.detect("My rodné číslo is 900101/1234");
console.log(session.countries);      // ["CZ"]

const result2 = await session.detect("My PESEL is 90010112345");
console.log(session.countries);      // ["CZ", "PL"]
console.log(session.messageCount);  // 2

Gateway

Access the AI Gateway for OpenAI-compatible chat completions:

const client = new FastPIIClient({ apiKey: "fpk_your_api_key" });

// Non-streaming
const response = await client.gateway.chat.completions({
  model: "gpt-4o",
  messages: [{ role: "user", content: "Hello!" }],
});

console.log(response.choices[0].message.content);

// Streaming
for await (const event of client.gateway.chat.stream({
  model: "gpt-4o",
  messages: [{ role: "user", content: "Hello!" }],
})) {
  if ("content" in event) {
    process.stdout.write(event.content);
  }
}

See the Gateway reference for full Gateway documentation.

Response types

DetectResponse

FieldTypeDescription
textstringOriginal input text
entitiesDetectedEntity[]Detected entities
countries_detectedCountryDetection[]Countries detected by Intelligence Engine
privacy_presetstring | nullPrivacy preset used
processing_time_msnumberProcessing time in milliseconds
api_versionstringAPI version (default "v1")

ProtectResponse

FieldTypeDescription
original_textstringOriginal text before protection
protected_textstringText after protection was applied
entitiesProtectedEntity[]Protected entities
countries_detectedCountryDetection[]Countries detected by Intelligence Engine
protection_modestringProtection mode used
processing_time_msnumberProcessing time in milliseconds
api_versionstringAPI version (default "v1")

ValidateResponse

FieldTypeDescription
valuestringThe value that was validated
entity_typestringEntity type validated against
countrystring | nullCountry code used
validbooleanWhether the value is valid
confidencenumberValidation confidence (0–1)
metadataRecord<string, unknown> | nullAdditional validation metadata

DetectedEntity

FieldTypeDescription
typestringEntity type (e.g., rodne_cislo, email)
originalstringThe original text that was detected
countrystring | nullCountry code if entity is country-specific
confidencenumberDetection confidence (0–1)
validatedbooleanWhether the entity passed checksum validation
startnumberStart position in original text
endnumberEnd position in original text
metadataRecord<string, unknown> | nullAdditional entity metadata

ProtectedEntity

FieldTypeDescription
typestringEntity type
originalstringThe original text that was detected
protectedstringThe protected or replaced text
countrystring | nullCountry code
confidencenumberDetection confidence (0–1)
validatedbooleanWhether the entity passed checksum validation
startnumberStart position in original text
endnumberEnd position in original text
metadataRecord<string, unknown> | nullAdditional entity metadata

DetectBatchResponse

FieldTypeDescription
resultsDetectResponse[]Detection results for each text
total_entitiesnumberTotal entities found across all texts
total_processing_time_msnumberTotal processing time in milliseconds

ProtectBatchResponse

FieldTypeDescription
resultsProtectResponse[]Protection results for each text
total_entitiesnumberTotal entities found across all texts
total_processing_time_msnumberTotal processing time in milliseconds

DetectorInfo

FieldTypeDescription
namestringDetector identifier (e.g., "rodne_cislo")
descriptionstringHuman-readable description
regionstringCountry code this detector belongs to
categorystringCategory: personal, business, medical, or government

CountryDetection

FieldTypeDescription
codestringISO 3166-1 alpha-2 country code
confidencenumberDetection confidence (0–1)

HealthResponse

FieldTypeDescription
statusstringService status (e.g., "healthy")
versionstring | nullAPI version
environmentstring | nullDeployment environment

Error handling

All errors inherit from FastPIIError which has message, statusCode, and errorType properties.

import {
  FastPIIError,
  AuthenticationError,
  RateLimitError,
  QuotaExceededError,
  ValidationError,
  ServerError,
  ConnectionError,
  TimeoutError,
} from "fastpii-connect";

try {
  const result = await client.detect("text");
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.log("Invalid API key");
  } else if (error instanceof RateLimitError) {
    console.log(`Rate limited. Retry after ${error.retryAfter} seconds`);
  } else if (error instanceof QuotaExceededError) {
    console.log("Monthly quota exceeded");
  } else if (error instanceof ValidationError) {
    console.log(`Request error: ${error.message} (status ${error.statusCode})`);
  } else if (error instanceof ServerError) {
    console.log("Server error");
  } else if (error instanceof ConnectionError) {
    console.log(`Connection failed: ${error.message}`);
  } else if (error instanceof FastPIIError) {
    console.log(`FastPII error: ${error.message}`);
  }
}
ErrorStatusWhenKey property
AuthenticationError401Invalid or missing API key
PermissionError403Permission denied
QuotaExceededError403Monthly quota exceeded
PolicyViolationError403Request violates policy
ValidationError400/422Invalid requestmessage, statusCode
NotFoundError404Resource not found
RateLimitError429Rate limit exceededretryAfter (seconds)
ServerError500+Internal server error
ConnectionErrorNoneNetwork failuremessage
TimeoutErrorNoneRequest timeoutmessage

Connect automatically retries on status codes 408, 429, 502, 503, and 504 up to maxRetries times with exponential backoff and jitter. See the error handling reference for Gateway-specific errors.

Validation helpers

The TypeScript SDK includes client-side validation that throws before making a network request:

import {
  validatePrivacyPreset,
  validateProtectMode,
  validateTextLength,
  validateBatchTexts,
} from "fastpii-connect";

validatePrivacyPreset("balanced");  // OK
validatePrivacyPreset("extreme");    // throws Error

validateProtectMode("replace");      // OK
validateProtectMode("delete");       // throws Error

validateTextLength("hello");         // OK
validateTextLength("");               // throws Error
validateTextLength("x".repeat(50001)); // throws Error

validateBatchTexts(["a", "b"]);      // OK
validateBatchTexts([]);              // throws Error
validateBatchTexts(new Array(51).fill("x")); // throws Error

On this page