Metadata-Version: 2.4
Name: humanos-sdk
Version: 1.0.8
Summary: Official Humanos API SDK for Python with automatic request signing and webhook verification
Author-email: Humanos <support@humanos.id>
Maintainer-email: Humanos <support@humanos.id>
License: MIT
Project-URL: Homepage, https://humanos.id
Project-URL: Documentation, https://docs.humanos.id
Project-URL: Repository, https://github.com/humanos-io/humanos-sdk
Project-URL: Bug Tracker, https://github.com/humanos-io/humanos-sdk/issues
Project-URL: Changelog, https://github.com/humanos-io/humanos-sdk/blob/main/python/CHANGELOG.md
Keywords: humanos,api,sdk,verifiable-credentials,did,identity,kyc,authentication,credentials
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Internet :: WWW/HTTP
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.25.0
Requires-Dist: cryptography>=3.4.0
Requires-Dist: urllib3>=1.25.3
Requires-Dist: python-dateutil>=2.8.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: typing-extensions>=4.0.0
Provides-Extra: flask
Requires-Dist: flask>=2.0.0; extra == "flask"
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.68.0; extra == "fastapi"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.20.0; extra == "dev"
Requires-Dist: python-dotenv>=1.0.0; extra == "dev"
Dynamic: license-file

# Humanos SDK for Python

Official Python SDK for the Humanos API. This SDK provides automatic request signing, webhook verification, and comprehensive API access for credential management.

[![PyPI version](https://badge.fury.io/py/humanos-sdk.svg)](https://pypi.org/project/humanos-sdk/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)

## Features

- 🔐 **Automatic Request Signing** - All API requests are automatically signed with HMAC-SHA256
- ✅ **Webhook Verification** - Built-in utilities for verifying webhook signatures
- 📝 **Type Hints** - Full type hint support for better IDE autocomplete
- 🎯 **Simple API** - Clean, intuitive interface for all Humanos endpoints
- 🌐 **Framework Integration** - Built-in support for Flask and FastAPI
- 🔄 **Auto-generated** - Always up-to-date with the latest API specifications

## Installation

```bash
pip install humanos-sdk
```

For webhook handling with Flask or FastAPI:

```bash
pip install humanos-sdk[flask]
# or
pip install humanos-sdk[fastapi]
```

For development:

```bash
pip install humanos-sdk[dev]
```

## Quick Start

```python
from humanos_sdk import HumanosClient, HumanosClientConfig
import os

client = HumanosClient(HumanosClientConfig(
    base_path="https://api.humanos.id",
    api_key=os.environ["HUMANOS_API_KEY"],
    signature_secret=os.environ["HUMANOS_SIGNATURE_SECRET"],
))

# Get resources
resources = client.resources.get_resources()
print(resources.data)

# Create a credential request
from humanos_sdk_generated.models import GenerateRequestDto

request = client.requests.generate(GenerateRequestDto(
    contacts=["user@example.com"],
    security_level="CONTACT",
    resources_ids=["resource-id"]
))
```

## API Reference

### Client Initialization

```python
from humanos_sdk import HumanosClient, HumanosClientConfig

client = HumanosClient(HumanosClientConfig(
    base_path="https://api.humanos.id",  # API base URL
    api_key="your-api-key",              # Your API key
    signature_secret="your-secret",       # Your signature secret
    verify_ssl=True                       # SSL verification (default: True)
))
```

### Available APIs

#### Resources API

```python
# Get all resources
response = client.resources.get_resources_with_http_info(
    page_index=0,
    page_size=20,
    active=True,
    search="search term",
    types="DOCUMENT"
)

# Get resource groups
groups = client.resources.get_groups_with_http_info(
    page_index=0,
    page_size=20,
    active=True,
    search="search term",
    types="CONSENT"
)

# Download a credential
file_data = client.resources.download(credential_id)
```

#### Requests API

```python
from humanos_sdk_generated.models import GenerateRequestDto

# Get all requests
requests = client.requests.get_requests_with_http_info(
    page_index=0,
    page_size=20,
    active=True,
    search="search term"
)

# Get request details
detail = client.requests.get_request_detail_with_http_info(request_id)

# Generate a new credential request
new_request = client.requests.generate_with_http_info(
    GenerateRequestDto(
        contacts=["email@example.com"],
        security_level="CONTACT",
        resources_ids=["resource-id"]
    )
)

# Cancel a request
client.requests.cancel_request_with_http_info(request_id)

# Resend OTP
client.requests.resend_otp_with_http_info(subject_otp_id)
```

#### Users API

```python
from humanos_sdk_generated.models import CreateSubjectDto, IdentityDto

# Create users
users = client.users.create_with_http_info([
    CreateSubjectDto(
        contact="user@example.com",
        internal_id="your-internal-id",  # optional
        identity=IdentityDto(            # optional KYC data
            full_name="John Doe",
            birth="1990-01-01",
            doc_id="123456789",
            country_alpha3="USA"
        )
    )
])
```

#### Health API

```python
# Health check
health = client.health.health_check_with_http_info()
```

### Webhook Verification

#### Flask Integration

```python
from flask import Flask, request, jsonify
from humanos_sdk.webhooks import verify_webhook_signature
import os

app = Flask(__name__)

@app.route('/webhooks/humanos', methods=['POST'])
def handle_webhook():
    signature = request.headers.get('X-Signature')
    timestamp = request.headers.get('X-Timestamp')
    body = request.get_json()

    is_valid = verify_webhook_signature(
        body=body,
        signature=signature,
        timestamp=int(timestamp),
        signature_secret=os.environ["HUMANOS_SIGNATURE_SECRET"],
        tolerance_ms=300000  # 5 minutes
    )

    if not is_valid:
        return jsonify({'error': 'Invalid signature'}), 401

    # Process webhook
    print('Received webhook:', body)
    return jsonify({'success': True})
```

#### FastAPI Integration

```python
from fastapi import FastAPI, Request, HTTPException
from humanos_sdk.webhooks import verify_webhook_signature
import os

app = FastAPI()

@app.post('/webhooks/humanos')
async def handle_webhook(request: Request):
    signature = request.headers.get('x-signature')
    timestamp = request.headers.get('x-timestamp')
    body = await request.json()

    is_valid = verify_webhook_signature(
        body=body,
        signature=signature,
        timestamp=int(timestamp),
        signature_secret=os.environ["HUMANOS_SIGNATURE_SECRET"],
        tolerance_ms=300000
    )

    if not is_valid:
        raise HTTPException(status_code=401, detail='Invalid signature')

    # Process webhook
    print('Received webhook:', body)
    return {'success': True}
```

## Error Handling

The SDK raises exceptions for failed requests. Use try-except blocks:

```python
from humanos_sdk_generated.exceptions import ApiException

try:
    resources = client.resources.get_resources()
except ApiException as e:
    print(f"API Error: {e.status} - {e.reason}")
    print(f"Body: {e.body}")
except Exception as e:
    print(f"Error: {str(e)}")
```

## Development

### Running Tests

```bash
cd python/tests
pytest -v
```

### Building

```bash
python -m build
```

## Documentation

- [Official Documentation](https://docs.humanos.id)
- [API Reference](https://docs.humanos.id/api-reference)
- [Humanos Homepage](https://humanos.id)

## Support

- **Email**: support@humanos.id
- **Issues**: [GitHub Issues](https://github.com/humanos-io/humanos-sdk/issues)

## License

MIT License - see [LICENSE](../LICENSE) file for details.

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.
