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-connectFastPIIClient
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
| Parameter | Type | Default | Description |
|---|---|---|---|
| api_key | string | required (or FASTPII_API_KEY env var) | Your FastPII API key (starts with fpk_) |
| base_url | string | "https://api.fastpii.com" | API base URL (or FASTPII_BASE_URL env var) |
| timeout | int | 30 | Request timeout in seconds |
| max_retries | int | 2 | Number 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
| Variable | Description |
|---|---|
FASTPII_API_KEY | API key (used if api_key parameter not provided) |
FASTPII_BASE_URL | Base 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"
)| Parameter | Type | Required | Description |
|---|---|---|---|
| text | string | Yes | Text to scan (1–50,000 characters) |
| country | string | No | ISO 3166-1 alpha-2 country code. Auto-detected if omitted. |
| language | string | No | Language hint for detection |
| privacy_preset | string | No | "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
)| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| text | string | Yes | - | Text to protect (1–50,000 characters) |
| mode | string | No | "replace" | Protection mode: replace, mask, hash, tokenize |
| country | string | No | None | ISO country code |
| language | string | No | None | Language hint |
| privacy_preset | string | No | None | Privacy 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
)| Parameter | Type | Required | Description |
|---|---|---|---|
| value | string | Yes | Value to validate |
| entity_type | string | Yes | Entity type (e.g., "rodne_cislo", "pesel", "steuer_id") |
| country | string | No | ISO 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}")| Parameter | Type | Required | Description |
|---|---|---|---|
| country | string or None | No | Filter 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}")| Parameter | Type | Required | Description |
|---|---|---|---|
| texts | list[string] | Yes | Texts to scan (1–50, each max 50,000 chars) |
| country | string | No | ISO country code |
| language | string | No | Language hint |
| privacy_preset | string | No | Privacy 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}")| Parameter | Type | Required | Description |
|---|---|---|---|
| texts | list[string] | Yes | Texts to protect (1–50, each max 50,000 chars) |
| mode | string | No | Protection mode (default "replace") |
| country | string | No | ISO country code |
| language | string | No | Language hint |
| privacy_preset | string | No | Privacy 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) # 2gateway 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
| Field | Type | Description |
|---|---|---|
| text | string | Original input text |
| entities | list[DetectedEntity] | Detected entities |
| countries_detected | list[CountryDetection] | Countries detected by Intelligence Engine |
| privacy_preset | string or None | Privacy preset used |
| processing_time_ms | float | Processing time in milliseconds |
| api_version | string | API version (default "v1") |
ProtectResponse
| Field | Type | Description |
|---|---|---|
| original_text | string | Original text before protection |
| protected_text | string | Text after protection was applied |
| entities | list[ProtectedEntity] | Protected entities |
| countries_detected | list[CountryDetection] | Countries detected by Intelligence Engine |
| protection_mode | string | Protection mode used |
| processing_time_ms | float | Processing time in milliseconds |
| api_version | string | API version (default "v1") |
ValidateResponse
| Field | Type | Description |
|---|---|---|
| value | string | The value that was validated |
| entity_type | string | Entity type validated against |
| country | string or None | Country code used |
| valid | boolean | Whether the value is valid |
| confidence | float | Validation confidence (0–1) |
| metadata | dict or None | Additional validation metadata |
DetectedEntity
| Field | Type | Description |
|---|---|---|
| type | string | Entity type (e.g., rodne_cislo, email) |
| original | string | The original text that was detected |
| country | string or None | Country code if entity is country-specific |
| confidence | float | Detection confidence (0–1) |
| validated | boolean | Whether the entity passed checksum validation |
| start | integer | Start position in original text |
| end | integer | End position in original text |
| metadata | dict or None | Additional entity metadata |
ProtectedEntity
| Field | Type | Description |
|---|---|---|
| type | string | Entity type |
| original | string | The original text that was detected |
| protected | string | The protected or replaced text |
| country | string or None | Country code |
| confidence | float | Detection confidence (0–1) |
| validated | boolean | Whether the entity passed checksum validation |
| start | integer | Start position in original text |
| end | integer | End position in original text |
| metadata | dict or None | Additional entity metadata |
DetectBatchResponse
| Field | Type | Description |
|---|---|---|
| results | list[DetectResponse] | Detection results for each text |
| total_entities | integer | Total entities found across all texts |
| total_processing_time_ms | float | Total processing time in milliseconds |
ProtectBatchResponse
| Field | Type | Description |
|---|---|---|
| results | list[ProtectResponse] | Protection results for each text |
| total_entities | integer | Total entities found across all texts |
| total_processing_time_ms | float | Total processing time in milliseconds |
DetectorInfo
| Field | Type | Description |
|---|---|---|
| name | string | Detector identifier (e.g., "rodne_cislo") |
| description | string | Human-readable description |
| region | string | Country code this detector belongs to |
| category | string | Category: personal, business, medical, or government |
CountryDetection
| Field | Type | Description |
|---|---|---|
| code | string | ISO 3166-1 alpha-2 country code |
| confidence | float | Detection confidence (0–1) |
HealthResponse
| Field | Type | Description |
|---|---|---|
| status | string | Service status (e.g., "healthy") |
| version | string or None | API version |
| environment | string or None | Deployment environment |
Error handling
All errors inherit from FastPIIError which has message and status_code attributes.
| Error | Status | When | Key attribute |
|---|---|---|---|
AuthenticationError | 401 | Invalid or missing API key | — |
PermissionError | 403 | Permission denied | — |
QuotaExceededError | 403 | Monthly quota exceeded | — |
PolicyViolationError | 403 | Request violates policy | — |
ValidationError | 400/422 | Invalid request | message, status_code |
NotFoundError | 404 | Resource not found | — |
RateLimitError | 429 | Rate limit exceeded | retry_after (seconds) |
ServerError | 500+ | Internal server error | — |
ConnectionError | None | Network failure | message |
TimeoutError | None | Request timeout | message |
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.
FastPII Connect Overview
Client SDKs for the FastPII AI Data Security Platform — detect and protect sensitive data before it reaches AI systems.
TypeScript SDK
TypeScript SDK reference for FastPII Connect with detection, protection, validation, batch operations, health, session management, and Gateway access.