x402tools


Namex402tools JSON
Version 1.0.0 PyPI version JSON
download
home_pagehttps://github.com/JaspSoe/stakefy-usage-envelope
SummaryPython SDK for x402 Usage-Based Billing API
upload_time2025-11-05 21:39:54
maintainerNone
docs_urlNone
authorStakefy
requires_python>=3.8
licenseMIT
keywords billing api usage tracking envelope metering
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # x402tools - Python SDK

Python SDK for the x402 Usage-Based Billing API. Track API usage, manage envelopes, and implement usage-based billing in your Python applications.

## Installation
```bash
pip install x402tools
```

## Quick Start
```python
from x402tools import X402Client

# Initialize the client with your API key
client = X402Client(api_key="your_api_key_here")

# Record usage
usage = client.record_usage(
    envelope_id="your_envelope_id",
    amount=100,
    metadata={"user_id": "123", "action": "api_call"}
)

print(f"Recorded {usage.amount} units of usage")
```

## Features

- ✅ **Envelope Management** - Create and manage usage limit envelopes
- ✅ **Usage Tracking** - Record and retrieve usage data
- ✅ **API Key Management** - Manage authentication keys
- ✅ **Type Hints** - Full type annotation support
- ✅ **Error Handling** - Comprehensive exception classes
- ✅ **Easy Integration** - Simple, intuitive API

## Usage Examples

### Create an Envelope
```python
from x402tools import X402Client

client = X402Client(api_key="your_api_key")

# Create a monthly envelope with 10,000 usage limit
envelope = client.create_envelope(
    name="API Calls",
    limit=10000,
    period="MONTHLY",
    reset_day=1  # Reset on the 1st of each month
)

print(f"Created envelope: {envelope.name} (ID: {envelope.id})")
```

### Record Usage
```python
# Record usage for an envelope
usage = client.record_usage(
    envelope_id=envelope.id,
    amount=50,
    metadata={
        "endpoint": "/api/users",
        "method": "GET",
        "user_id": "user_123"
    }
)

print(f"Usage recorded at {usage.timestamp}")
```

### Get All Envelopes
```python
# Retrieve all envelopes
envelopes = client.get_envelopes()

for env in envelopes:
    print(f"{env.name}: {env.limit} ({env.period})")
```

### Get Usage Statistics
```python
# Get usage stats
stats = client.get_usage_stats()

print(f"Total Usage: {stats.total_usage}")
print(f"Active Envelopes: {stats.active_envelopes}")
```

### Get Usage History
```python
# Get all usage records
all_usage = client.get_usage()

# Get usage for a specific envelope
envelope_usage = client.get_usage(envelope_id="your_envelope_id")

for record in envelope_usage:
    print(f"{record.timestamp}: {record.amount} units")
```

### Update an Envelope
```python
# Update envelope limit
updated = client.update_envelope(
    envelope_id=envelope.id,
    limit=20000
)

print(f"Updated limit to {updated.limit}")
```

### Delete an Envelope
```python
# Delete an envelope
client.delete_envelope(envelope_id=envelope.id)
print("Envelope deleted")
```

### Manage API Keys
```python
# Create a new API key
api_key = client.create_api_key(name="Production Key")
print(f"New API key: {api_key.key}")

# List all API keys
keys = client.get_api_keys()
for key in keys:
    print(f"{key.name}: {key.key}")

# Delete an API key
client.delete_api_key(key_id=api_key.id)
```

## Error Handling
```python
from x402tools import X402Client, AuthenticationError, APIError, RateLimitError

client = X402Client(api_key="your_api_key")

try:
    usage = client.record_usage(
        envelope_id="invalid_id",
        amount=100
    )
except AuthenticationError:
    print("Invalid API key")
except RateLimitError:
    print("Rate limit exceeded, please try again later")
except APIError as e:
    print(f"API Error: {e}")
```

## API Reference

### X402Client

**Constructor:**
```python
X402Client(api_key: str, base_url: str = "https://stakefy-usage-envelope-production.up.railway.app")
```

**Envelope Methods:**
- `get_envelopes() -> List[Envelope]`
- `get_envelope(envelope_id: str) -> Envelope`
- `create_envelope(name: str, limit: int, period: PeriodType, reset_day: Optional[int] = None) -> Envelope`
- `update_envelope(envelope_id: str, **kwargs) -> Envelope`
- `delete_envelope(envelope_id: str) -> None`

**Usage Methods:**
- `record_usage(envelope_id: str, amount: int, metadata: Optional[Dict] = None) -> Usage`
- `get_usage(envelope_id: Optional[str] = None) -> List[Usage]`
- `get_usage_stats() -> UsageStats`

**API Key Methods:**
- `get_api_keys() -> List[ApiKey]`
- `create_api_key(name: str) -> ApiKey`
- `delete_api_key(key_id: str) -> None`

## Data Types

### Envelope
```python
@dataclass
class Envelope:
    id: str
    name: str
    limit: int
    period: Literal["DAILY", "WEEKLY", "MONTHLY", "YEARLY"]
    organization_id: str
    created_at: datetime
    updated_at: datetime
    reset_day: Optional[int] = None
```

### Usage
```python
@dataclass
class Usage:
    id: str
    envelope_id: str
    amount: int
    timestamp: datetime
    metadata: Optional[Dict[str, Any]] = None
```

## Requirements

- Python 3.8+
- requests >= 2.31.0

## License

MIT License

## Support

For issues and questions:
- GitHub Issues: https://github.com/JaspSoe/stakefy-usage-envelope/issues
- Email: support@stakefy.com

## Links

- Homepage: https://stakefy.com
- Documentation: https://github.com/JaspSoe/stakefy-usage-envelope
- PyPI: https://pypi.org/project/x402tools/

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/JaspSoe/stakefy-usage-envelope",
    "name": "x402tools",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "billing, api, usage, tracking, envelope, metering",
    "author": "Stakefy",
    "author_email": "Stakefy <support@stakefy.com>",
    "download_url": "https://files.pythonhosted.org/packages/20/cb/c3241b8c1f5f0034d136e80ac6f9d2fe4dab280c3bb817f16cc6a6141862/x402tools-1.0.0.tar.gz",
    "platform": null,
    "description": "# x402tools - Python SDK\n\nPython SDK for the x402 Usage-Based Billing API. Track API usage, manage envelopes, and implement usage-based billing in your Python applications.\n\n## Installation\n```bash\npip install x402tools\n```\n\n## Quick Start\n```python\nfrom x402tools import X402Client\n\n# Initialize the client with your API key\nclient = X402Client(api_key=\"your_api_key_here\")\n\n# Record usage\nusage = client.record_usage(\n    envelope_id=\"your_envelope_id\",\n    amount=100,\n    metadata={\"user_id\": \"123\", \"action\": \"api_call\"}\n)\n\nprint(f\"Recorded {usage.amount} units of usage\")\n```\n\n## Features\n\n- \u2705 **Envelope Management** - Create and manage usage limit envelopes\n- \u2705 **Usage Tracking** - Record and retrieve usage data\n- \u2705 **API Key Management** - Manage authentication keys\n- \u2705 **Type Hints** - Full type annotation support\n- \u2705 **Error Handling** - Comprehensive exception classes\n- \u2705 **Easy Integration** - Simple, intuitive API\n\n## Usage Examples\n\n### Create an Envelope\n```python\nfrom x402tools import X402Client\n\nclient = X402Client(api_key=\"your_api_key\")\n\n# Create a monthly envelope with 10,000 usage limit\nenvelope = client.create_envelope(\n    name=\"API Calls\",\n    limit=10000,\n    period=\"MONTHLY\",\n    reset_day=1  # Reset on the 1st of each month\n)\n\nprint(f\"Created envelope: {envelope.name} (ID: {envelope.id})\")\n```\n\n### Record Usage\n```python\n# Record usage for an envelope\nusage = client.record_usage(\n    envelope_id=envelope.id,\n    amount=50,\n    metadata={\n        \"endpoint\": \"/api/users\",\n        \"method\": \"GET\",\n        \"user_id\": \"user_123\"\n    }\n)\n\nprint(f\"Usage recorded at {usage.timestamp}\")\n```\n\n### Get All Envelopes\n```python\n# Retrieve all envelopes\nenvelopes = client.get_envelopes()\n\nfor env in envelopes:\n    print(f\"{env.name}: {env.limit} ({env.period})\")\n```\n\n### Get Usage Statistics\n```python\n# Get usage stats\nstats = client.get_usage_stats()\n\nprint(f\"Total Usage: {stats.total_usage}\")\nprint(f\"Active Envelopes: {stats.active_envelopes}\")\n```\n\n### Get Usage History\n```python\n# Get all usage records\nall_usage = client.get_usage()\n\n# Get usage for a specific envelope\nenvelope_usage = client.get_usage(envelope_id=\"your_envelope_id\")\n\nfor record in envelope_usage:\n    print(f\"{record.timestamp}: {record.amount} units\")\n```\n\n### Update an Envelope\n```python\n# Update envelope limit\nupdated = client.update_envelope(\n    envelope_id=envelope.id,\n    limit=20000\n)\n\nprint(f\"Updated limit to {updated.limit}\")\n```\n\n### Delete an Envelope\n```python\n# Delete an envelope\nclient.delete_envelope(envelope_id=envelope.id)\nprint(\"Envelope deleted\")\n```\n\n### Manage API Keys\n```python\n# Create a new API key\napi_key = client.create_api_key(name=\"Production Key\")\nprint(f\"New API key: {api_key.key}\")\n\n# List all API keys\nkeys = client.get_api_keys()\nfor key in keys:\n    print(f\"{key.name}: {key.key}\")\n\n# Delete an API key\nclient.delete_api_key(key_id=api_key.id)\n```\n\n## Error Handling\n```python\nfrom x402tools import X402Client, AuthenticationError, APIError, RateLimitError\n\nclient = X402Client(api_key=\"your_api_key\")\n\ntry:\n    usage = client.record_usage(\n        envelope_id=\"invalid_id\",\n        amount=100\n    )\nexcept AuthenticationError:\n    print(\"Invalid API key\")\nexcept RateLimitError:\n    print(\"Rate limit exceeded, please try again later\")\nexcept APIError as e:\n    print(f\"API Error: {e}\")\n```\n\n## API Reference\n\n### X402Client\n\n**Constructor:**\n```python\nX402Client(api_key: str, base_url: str = \"https://stakefy-usage-envelope-production.up.railway.app\")\n```\n\n**Envelope Methods:**\n- `get_envelopes() -> List[Envelope]`\n- `get_envelope(envelope_id: str) -> Envelope`\n- `create_envelope(name: str, limit: int, period: PeriodType, reset_day: Optional[int] = None) -> Envelope`\n- `update_envelope(envelope_id: str, **kwargs) -> Envelope`\n- `delete_envelope(envelope_id: str) -> None`\n\n**Usage Methods:**\n- `record_usage(envelope_id: str, amount: int, metadata: Optional[Dict] = None) -> Usage`\n- `get_usage(envelope_id: Optional[str] = None) -> List[Usage]`\n- `get_usage_stats() -> UsageStats`\n\n**API Key Methods:**\n- `get_api_keys() -> List[ApiKey]`\n- `create_api_key(name: str) -> ApiKey`\n- `delete_api_key(key_id: str) -> None`\n\n## Data Types\n\n### Envelope\n```python\n@dataclass\nclass Envelope:\n    id: str\n    name: str\n    limit: int\n    period: Literal[\"DAILY\", \"WEEKLY\", \"MONTHLY\", \"YEARLY\"]\n    organization_id: str\n    created_at: datetime\n    updated_at: datetime\n    reset_day: Optional[int] = None\n```\n\n### Usage\n```python\n@dataclass\nclass Usage:\n    id: str\n    envelope_id: str\n    amount: int\n    timestamp: datetime\n    metadata: Optional[Dict[str, Any]] = None\n```\n\n## Requirements\n\n- Python 3.8+\n- requests >= 2.31.0\n\n## License\n\nMIT License\n\n## Support\n\nFor issues and questions:\n- GitHub Issues: https://github.com/JaspSoe/stakefy-usage-envelope/issues\n- Email: support@stakefy.com\n\n## Links\n\n- Homepage: https://stakefy.com\n- Documentation: https://github.com/JaspSoe/stakefy-usage-envelope\n- PyPI: https://pypi.org/project/x402tools/\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Python SDK for x402 Usage-Based Billing API",
    "version": "1.0.0",
    "project_urls": {
        "Documentation": "https://github.com/JaspSoe/stakefy-usage-envelope",
        "Homepage": "https://github.com/JaspSoe/stakefy-usage-envelope",
        "Repository": "https://github.com/JaspSoe/stakefy-usage-envelope"
    },
    "split_keywords": [
        "billing",
        " api",
        " usage",
        " tracking",
        " envelope",
        " metering"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "818c20689688fc09bb1b4e77d0d966df5b71020f95d8d48f66bfbfc6688f8f0b",
                "md5": "ab44ac6625a908392461295615d41de6",
                "sha256": "c48c170baa2ec1da109e3b2cf4700d20b200881473cccbaa9c2c3fc8fffafbf2"
            },
            "downloads": -1,
            "filename": "x402tools-1.0.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "ab44ac6625a908392461295615d41de6",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 6968,
            "upload_time": "2025-11-05T21:39:53",
            "upload_time_iso_8601": "2025-11-05T21:39:53.380696Z",
            "url": "https://files.pythonhosted.org/packages/81/8c/20689688fc09bb1b4e77d0d966df5b71020f95d8d48f66bfbfc6688f8f0b/x402tools-1.0.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "20cbc3241b8c1f5f0034d136e80ac6f9d2fe4dab280c3bb817f16cc6a6141862",
                "md5": "48baf10b3393e3fc59f4e5769cff82e3",
                "sha256": "8830f8805586136763e981e299a0267e83be1a993dc62749aca3e19e2a2c000e"
            },
            "downloads": -1,
            "filename": "x402tools-1.0.0.tar.gz",
            "has_sig": false,
            "md5_digest": "48baf10b3393e3fc59f4e5769cff82e3",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 7932,
            "upload_time": "2025-11-05T21:39:54",
            "upload_time_iso_8601": "2025-11-05T21:39:54.617369Z",
            "url": "https://files.pythonhosted.org/packages/20/cb/c3241b8c1f5f0034d136e80ac6f9d2fe4dab280c3bb817f16cc6a6141862/x402tools-1.0.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-11-05 21:39:54",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "JaspSoe",
    "github_project": "stakefy-usage-envelope",
    "github_not_found": true,
    "lcname": "x402tools"
}
        
Elapsed time: 2.30009s