FastPII Docs
FastPII Connect

Client Reference

Python client API reference for FastPII Connect with detection, protection, validation, batch operations, health, session management, and Gateway access.

Client Reference

Complete API reference for the FastPIIClient and AsyncFastPII Python classes, response types, and error handling.

Installation

pip install fastpii-connect

FastPIIClient

from fastpii_connect import FastPIIClient

client = FastPIIClient(
    api_key="fpk_your_api_key",
    base_url="https://api.fastpii.com",  # default
    timeout=30,          # request timeout in seconds
    max_retries=2,      # retries for 408, 429, 502, 503, 504 errors
)

Parameters

ParameterTypeDefaultDescription
api_keystringrequired (or FASTPII_API_KEY env var)Your FastPII API key (starts with fpk_)
base_urlstring"https://api.fastpii.com"API base URL (or FASTPII_BASE_URL env var)
timeoutint30Request timeout in seconds
max_retriesint2Number 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.

Environment variables

VariableDescription
FASTPII_API_KEYAPI key (used if api_key parameter not provided)
FASTPII_BASE_URLBase URL override (used if base_url parameter not provided)

AsyncFastPII

The async client has the same interface as FastPIIClient but uses httpx.AsyncClient and async/await:

from fastpii_connect import AsyncFastPII

async with AsyncFastPII(api_key="fpk_your_api_key") as client:
    result = await client.detect("My rodné číslo is 900101/1234")
    print(result.entities)

All methods are identical to FastPIIClient but return coroutines. The async client also supports the Gateway:

async with AsyncFastPII(api_key="fpk_your_api_key") as client:
    response = await client.gateway.chat.completions(
        model="gpt-4o",
        messages=[{"role": "user", "content": "Hello!"}],
    )

Methods

detect

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

result = client.detect(
    text="My rodné číslo is 900101/1234",
    country="cz",           # optional: ISO country code
    language="cs",          # optional: language hint
    privacy_preset="balanced",  # optional: "conservative", "balanced", "aggressive"
)
ParameterTypeRequiredDescription
textstringYesText to scan (1–50,000 characters)
countrystringNoISO 3166-1 alpha-2 country code. Auto-detected if omitted.
languagestringNoLanguage hint for detection
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.

result = client.protect(
    text="My rodné číslo is 900101/1234",
    mode="replace",         # "replace", "mask", "hash", "tokenize"
    country="cz",           # optional
    language="cs",          # optional
    privacy_preset="aggressive",  # optional
)
ParameterTypeRequiredDefaultDescription
textstringYes-Text to protect (1–50,000 characters)
modestringNo"replace"Protection mode: replace, mask, hash, tokenize
countrystringNoNoneISO country code
languagestringNoNoneLanguage hint
privacy_presetstringNoNonePrivacy preset

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

validate

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

result = client.validate(
    value="900101/1234",
    entity_type="rodne_cislo",
    country="cz",   # optional
)
ParameterTypeRequiredDescription
valuestringYesValue to validate
entity_typestringYesEntity type (e.g., "rodne_cislo", "pesel", "steuer_id")
countrystringNoISO country code

Returns a ValidateResponse.

list_detectors

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

detectors = client.list_detectors(country="CZ")  # optional country filter
for d in detectors.detectors:
    print(f"{d.name} ({d.region}): {d.description}")
ParameterTypeRequiredDescription
countrystring or NoneNoFilter by ISO country code

Returns a DetectorsResponse.

detect_batch

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

result = client.detect_batch(
    texts=["Text one", "Text two", "Text three"],
    country="cz",  # optional
)
print(f"Total entities: {result.total_entities}")
ParameterTypeRequiredDescription
textslist[string]YesTexts to scan (1–50, each max 50,000 chars)
countrystringNoISO country code
languagestringNoLanguage hint
privacy_presetstringNoPrivacy preset

Returns a DetectBatchResponse. See batch detection for details.

protect_batch

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

result = client.protect_batch(
    texts=["Text one", "Text two"],
    mode="mask",    # optional, default "replace"
    country="cz",   # optional
)
print(f"Total entities: {result.total_entities}")
ParameterTypeRequiredDescription
textslist[string]YesTexts to protect (1–50, each max 50,000 chars)
modestringNoProtection mode (default "replace")
countrystringNoISO country code
languagestringNoLanguage hint
privacy_presetstringNoPrivacy preset

Returns a ProtectBatchResponse. See batch protection for details.

health

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

health = client.health()
print(f"Status: {health.status}, Version: {health.version}")

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

create_session

Create a session that tracks detected countries across calls.

session = client.create_session()
result1 = session.detect("My rodné číslo is 900101/1234")
print(session.countries)       # ["CZ"]

result2 = session.detect("My PESEL is 90010112345")
print(session.countries)       # ["CZ", "PL"]
print(session.message_count)  # 2

gateway property

Access the AI Gateway for OpenAI-compatible chat completions:

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

# Streaming
for event in client.gateway.chat.stream(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Hello!"}],
):
    if hasattr(event, "content"):
        print(event.content, end="")

See the Gateway reference for full Gateway documentation.

close

Close the underlying HTTP client. Called automatically when using the context manager.

client.close()

Response types

DetectResponse

FieldTypeDescription
textstringOriginal input text
entitieslist[DetectedEntity]Detected entities
countries_detectedlist[CountryDetection]Countries detected by Intelligence Engine
privacy_presetstring or NonePrivacy preset used
processing_time_msfloatProcessing time in milliseconds
api_versionstringAPI version (default "v1")

ProtectResponse

FieldTypeDescription
original_textstringOriginal text before protection
protected_textstringText after protection was applied
entitieslist[ProtectedEntity]Protected entities
countries_detectedlist[CountryDetection]Countries detected by Intelligence Engine
protection_modestringProtection mode used
processing_time_msfloatProcessing time in milliseconds
api_versionstringAPI version (default "v1")

ValidateResponse

FieldTypeDescription
valuestringThe value that was validated
entity_typestringEntity type validated against
countrystring or NoneCountry code used
validbooleanWhether the value is valid
confidencefloatValidation confidence (0–1)
metadatadict or NoneAdditional validation metadata

DetectedEntity

FieldTypeDescription
typestringEntity type (e.g., rodne_cislo, email)
originalstringThe original text that was detected
countrystring or NoneCountry code if entity is country-specific
confidencefloatDetection confidence (0–1)
validatedbooleanWhether the entity passed checksum validation
startintegerStart position in original text
endintegerEnd position in original text
metadatadict or NoneAdditional entity metadata

ProtectedEntity

FieldTypeDescription
typestringEntity type
originalstringThe original text that was detected
protectedstringThe protected or replaced text
countrystring or NoneCountry code
confidencefloatDetection confidence (0–1)
validatedbooleanWhether the entity passed checksum validation
startintegerStart position in original text
endintegerEnd position in original text
metadatadict or NoneAdditional entity metadata

DetectBatchResponse

FieldTypeDescription
resultslist[DetectResponse]Detection results for each text
total_entitiesintegerTotal entities found across all texts
total_processing_time_msfloatTotal processing time in milliseconds

ProtectBatchResponse

FieldTypeDescription
resultslist[ProtectResponse]Protection results for each text
total_entitiesintegerTotal entities found across all texts
total_processing_time_msfloatTotal 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
confidencefloatDetection confidence (0–1)

HealthResponse

FieldTypeDescription
statusstringService status (e.g., "healthy")
versionstring or NoneAPI version
environmentstring or NoneDeployment environment

Error handling

All errors inherit from FastPIIError which has message and status_code attributes.

ErrorStatusWhenKey attribute
AuthenticationError401Invalid or missing API key
PermissionError403Permission denied
QuotaExceededError403Monthly quota exceeded
PolicyViolationError403Request violates policy
ValidationError400/422Invalid requestmessage, status_code
NotFoundError404Resource not found
RateLimitError429Rate limit exceededretry_after (seconds)
ServerError500+Internal server error
ConnectionErrorNoneNetwork failuremessage
TimeoutErrorNoneRequest timeoutmessage
from fastpii_connect.errors import (
    FastPIIError,
    AuthenticationError,
    RateLimitError,
    QuotaExceededError,
    ValidationError,
    ServerError,
    ConnectionError,
    TimeoutError,
)

try:
    result = client.detect("text")
except AuthenticationError:
    print("Invalid API key")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after} seconds")
except QuotaExceededError:
    print("Monthly quota exceeded")
except ValidationError as e:
    print(f"Request error: {e.message} (status {e.status_code})")
except ServerError:
    print("Server error")
except ConnectionError as e:
    print(f"Connection failed: {e.message}")
except FastPIIError as e:
    print(f"FastPII error: {e.message}")

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

On this page