Skip to main content

Guardian SDK for Python

Project description

Guardian Python SDK

PyPI version

The official Python SDK for the Guardian API, providing a convenient and production-ready interface for real-time threat detection.

This SDK includes:

  • A simple and intuitive API
  • Robust error handling and automatic retries
  • High-performance connection pooling
  • Structured logging for observability
  • Comprehensive configuration options

Installation

Install the SDK using pip:

pip install guardian-sdk

Quick Start

Here's a basic example of how to analyze a piece of text:

import os
from guardian_sdk import Guardian, GuardianAPIError

# Initialize the client. API key can be passed directly or set via
# the GUARDIAN_API_KEY environment variable.
client = Guardian(api_key=os.getenv("GUARDIAN_API_KEY"))

text_to_analyze = "URGENT: Your account is locked. Click http://secure-login-portal.com to fix."

try:
    result = client.analyze(text=text_to_analyze)
    print(f"Risk Score: {result['risk_score']}")
    for threat in result['threats_detected']:
        print(f"- Detected Threat: {threat['category']} (Confidence: {threat['confidence_score']})")
except GuardianAPIError as e:
    print(f"API Error: {e.message} (Status: {e.status_code})")
finally:
    client.close() # Gracefully close connections

Configuration

The client can be configured via the GuardianConfig class or by passing keyword arguments to the Guardian constructor.

from guardian_sdk import Guardian, GuardianConfig
from httpx import Limits

# Advanced configuration
config = GuardianConfig(
    api_key="YOUR_API_KEY",
    base_url="https://api.your-guardian-instance.com",
    timeout_seconds=30.0,
    max_retries=5,
    debug=True, # Enable verbose logging
    limits=Limits(max_connections=200, max_keepalive_connections=40)
)

client = Guardian(config=config)
Parameter Type Default Description
api_key str os.getenv("GUARDIAN_API_KEY") Your Guardian API key.
base_url str "http://localhost:8000" The base URL of the Guardian API.
timeout_seconds float 15.0 Timeout for network requests.
max_retries int 3 Maximum number of retries for transient errors (e.g., 5xx, timeouts).
debug bool False If True, enables verbose structured logging to the console.
limits httpx.Limits Limits(max_connections=100, ...) Configuration for connection pooling.

Error Handling

The SDK raises specific exceptions for different types of errors, all inheriting from GuardianError.

  • GuardianValidationError: Invalid input provided to the SDK (e.g., missing API key, empty text).
  • GuardianAPIError: A generic error from the API (e.g., 400 Bad Request, 500 Internal Server Error).
  • GuardianRateLimitError: A 429 Too Many Requests error. The retry_after attribute contains the recommended wait time in seconds.
  • GuardianTimeoutError: The request failed after exhausting all retries due to network timeouts or transient server issues.

Example:

from guardian_sdk import Guardian, GuardianError, GuardianRateLimitError
import time

client = Guardian(api_key="YOUR_API_KEY")

try:
    client.analyze("some text")
except GuardianRateLimitError as e:
    print(f"Rate limited. Waiting for {e.retry_after} seconds.")
    time.sleep(e.retry_after)
except GuardianError as e:
    print(f"An unexpected Guardian error occurred: {e}")

Best Practices

Use as a Context Manager

For proper resource management, it is recommended to use the client as a context manager. This ensures that network connections are closed gracefully.

with Guardian(api_key="YOUR_API_KEY") as client:
    result = client.analyze("some text")
    print(result)

Singleton Instance

For most applications (e.g., a web server), you should create a single Guardian client instance and reuse it for all requests. This is crucial for connection pooling to work effectively.

# In your application's initialization code (e.g., main.py)

from guardian_sdk import Guardian

guardian_client = Guardian(api_key="YOUR_API_KEY")

# In your request handlers:
def handle_request(text):
    return guardian_client.analyze(text)

Logging

The SDK uses the structlog library for structured logging. To see detailed logs, including request/response information, enable debug mode:

client = Guardian(api_key="YOUR_API_KEY", debug=True)

This will output detailed JSON-formatted logs to the console, which can be invaluable for debugging.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

guardian_securitysdk-0.2.1.tar.gz (6.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

guardian_securitysdk-0.2.1-py3-none-any.whl (6.2 kB view details)

Uploaded Python 3

File details

Details for the file guardian_securitysdk-0.2.1.tar.gz.

File metadata

  • Download URL: guardian_securitysdk-0.2.1.tar.gz
  • Upload date:
  • Size: 6.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for guardian_securitysdk-0.2.1.tar.gz
Algorithm Hash digest
SHA256 bbc8b3846411b7bb2eb2389ca33a48e522239857940d4dade387ee12fda86395
MD5 2f0c4218ebe489ee5cb9ca719bf52eaf
BLAKE2b-256 79d585311b493a8359238d7cbc693c8aa7be80f78e3a6ea3b153e975b6b05271

See more details on using hashes here.

File details

Details for the file guardian_securitysdk-0.2.1-py3-none-any.whl.

File metadata

File hashes

Hashes for guardian_securitysdk-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 bd0223718104d2bd5ca2b6740602b5cf206020081f556544a7d2474e1db2ae74
MD5 224b0f558fde6ad4a6a80011da1e84b3
BLAKE2b-256 67742b5ddfed6c9ca1737c0862700eeacc2c335a529d870a9230fb8b6c4c519a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page