Python SDK
The official TAG IT Python SDK for server-side applications and data pipelines.
Installation
Install the TAG IT Python SDK using pip:
pip install tagit-sdk
Or add it to your requirements.txt:
tagit-sdk>=1.0.0
Then install dependencies:
pip install -r requirements.txt
The SDK requires Python 3.8 or higher. For async support, Python 3.9+ is recommended.
Initialization
Initialize the TAG IT client with your API credentials:
Synchronous Client
from tagit import TagIt
# Initialize the synchronous client
client = TagIt(
api_key="tagit_live_abc123xyz789",
api_secret="sk_live_your_secret_key_here",
network="mainnet" # or "testnet" for development
)
# Verify a product
result = client.products.verify("NFC-TAG-001-ABC")
print(f"Verified: {result.verified}")
Async Client
from tagit import AsyncTagIt
import asyncio
# Initialize the async client
client = AsyncTagIt(
api_key="tagit_live_abc123xyz789",
api_secret="sk_live_your_secret_key_here",
network="mainnet"
)
async def main():
result = await client.products.verify("NFC-TAG-001-ABC")
print(f"Verified: {result.verified}")
await client.close()
asyncio.run(main())
Never hardcode API credentials. Use environment variables or a secrets manager in production.
import os
from tagit import TagIt
client = TagIt(
api_key=os.environ["TAGIT_API_KEY"],
api_secret=os.environ["TAGIT_API_SECRET"],
network=os.environ.get("TAGIT_NETWORK", "mainnet")
)
Products Module
The Products module provides methods for registering, verifying, and retrieving product information.
client.products.register()
Register a new product on the TAG IT Network:
# Register a new product
product = client.products.register(
tag_id="NFC-TAG-002-XYZ",
metadata={
"product_name": "Designer Handbag",
"brand": "Luxury Brand Co",
"serial_number": "SN-2024-005678",
"manufacture_date": "2024-03-15",
"origin": "Italy",
"materials": ["leather", "gold hardware"],
"retail_price": 2500.00
},
owner_address="0x742d35Cc6634C0532925a3b844Bc9e7595f5c9E8"
)
print(f"Product registered with ID: {product.tag_id}")
print(f"Transaction hash: {product.tx_hash}")
print(f"Token ID: {product.token_id}")
client.products.verify()
Verify a product's authenticity:
# Verify product authenticity
result = client.products.verify("NFC-TAG-001-ABC")
if result.verified:
print(f"Product is authentic!")
print(f"Product: {result.metadata['product_name']}")
print(f"Brand: {result.metadata['brand']}")
print(f"Current owner: {result.current_owner}")
print(f"Transfer count: {len(result.transfer_history)}")
else:
print("Product verification failed - may be counterfeit")
# Verify with additional options
result = client.products.verify(
tag_id="NFC-TAG-001-ABC",
include_history=True,
include_blockchain_data=True
)
client.products.get()
Retrieve detailed product information:
# Get product details
product = client.products.get("NFC-TAG-001-ABC")
print(f"Tag ID: {product.tag_id}")
print(f"Name: {product.metadata['product_name']}")
print(f"Brand: {product.metadata['brand']}")
print(f"Serial: {product.metadata['serial_number']}")
print(f"Owner: {product.current_owner}")
print(f"Registered: {product.created_at}")
print(f"Last updated: {product.updated_at}")
# Access blockchain data
print(f"Network: {product.blockchain['network']}")
print(f"Contract: {product.blockchain['contract_address']}")
print(f"Token ID: {product.blockchain['token_id']}")
Transfers Module
The Transfers module handles ownership transfer operations.
client.transfers.initiate()
Initiate an ownership transfer:
# Initiate a transfer
transfer = client.transfers.initiate(
tag_id="NFC-TAG-001-ABC",
from_address="0x742d35Cc6634C0532925a3b844Bc9e7595f5c9E8",
to_address="0x8ba1f109551bD432803012645Ac136ddd64DBA72",
transfer_type="sale", # "sale", "gift", or "return"
metadata={
"sale_price": 2200.00,
"currency": "USD",
"notes": "Secondary market sale"
}
)
print(f"Transfer ID: {transfer.transfer_id}")
print(f"Status: {transfer.status}")
print(f"Expires at: {transfer.expires_at}")
print(f"Confirmation required from: {transfer.to_address}")
client.transfers.confirm()
Confirm a pending transfer:
# Confirm the transfer (called by the recipient)
confirmed = client.transfers.confirm(
transfer_id="TXF-2024-001234",
signature="0x..." # Wallet signature for verification
)
print(f"Transfer confirmed: {confirmed.confirmed}")
print(f"New owner: {confirmed.new_owner}")
print(f"Transaction hash: {confirmed.tx_hash}")
print(f"Block number: {confirmed.block_number}")
# Check transfer status
status = client.transfers.get_status("TXF-2024-001234")
print(f"Current status: {status.status}") # pending, confirmed, cancelled, expired
Async Support
The SDK provides full async support for high-performance applications:
import asyncio
from tagit import AsyncTagIt
async def process_batch_verification(tag_ids: list[str]):
"""Verify multiple products concurrently."""
client = AsyncTagIt(
api_key=os.environ["TAGIT_API_KEY"],
api_secret=os.environ["TAGIT_API_SECRET"]
)
try:
# Create verification tasks
tasks = [client.products.verify(tag_id) for tag_id in tag_ids]
# Execute concurrently
results = await asyncio.gather(*tasks, return_exceptions=True)
for tag_id, result in zip(tag_ids, results):
if isinstance(result, Exception):
print(f"{tag_id}: Error - {result}")
elif result.verified:
print(f"{tag_id}: Verified - {result.metadata['product_name']}")
else:
print(f"{tag_id}: Not verified")
return results
finally:
await client.close()
# Run the batch verification
tag_ids = ["NFC-TAG-001", "NFC-TAG-002", "NFC-TAG-003"]
asyncio.run(process_batch_verification(tag_ids))
Context Manager Support
async def verify_with_context():
"""Use async context manager for automatic cleanup."""
async with AsyncTagIt(
api_key=os.environ["TAGIT_API_KEY"],
api_secret=os.environ["TAGIT_API_SECRET"]
) as client:
result = await client.products.verify("NFC-TAG-001-ABC")
return result
# The client is automatically closed after the block
Django Integration
Integrate TAG IT SDK with Django applications:
Settings Configuration
# settings.py
TAGIT_CONFIG = {
"API_KEY": os.environ["TAGIT_API_KEY"],
"API_SECRET": os.environ["TAGIT_API_SECRET"],
"NETWORK": os.environ.get("TAGIT_NETWORK", "mainnet"),
"TIMEOUT": 30,
"RETRY_ATTEMPTS": 3,
}
INSTALLED_APPS = [
# ...
"tagit.django",
]
MIDDLEWARE = [
# ...
"tagit.django.middleware.TagItMiddleware",
]
Middleware
# tagit/django/middleware.py
from django.conf import settings
from tagit import TagIt
class TagItMiddleware:
def __init__(self, get_response):
self.get_response = get_response
self.client = TagIt(**settings.TAGIT_CONFIG)
def __call__(self, request):
# Attach client to request
request.tagit = self.client
response = self.get_response(request)
return response
Using in Views
# views.py
from django.http import JsonResponse
from django.views import View
class ProductVerifyView(View):
def get(self, request, tag_id):
result = request.tagit.products.verify(tag_id)
return JsonResponse({
"verified": result.verified,
"product": result.metadata if result.verified else None,
"owner": result.current_owner if result.verified else None,
})
class ProductRegisterView(View):
def post(self, request):
data = request.POST
product = request.tagit.products.register(
tag_id=data["tag_id"],
metadata={
"product_name": data["name"],
"brand": data["brand"],
"serial_number": data["serial"],
},
owner_address=data["owner_address"]
)
return JsonResponse({
"success": True,
"tag_id": product.tag_id,
"tx_hash": product.tx_hash,
})
Error Handling
The SDK provides specific exception classes for different error scenarios:
from tagit import TagIt
from tagit.exceptions import (
TagItError,
AuthenticationError,
ValidationError,
NotFoundError,
RateLimitError,
NetworkError,
BlockchainError,
)
client = TagIt(
api_key=os.environ["TAGIT_API_KEY"],
api_secret=os.environ["TAGIT_API_SECRET"]
)
try:
result = client.products.verify("NFC-TAG-001-ABC")
except AuthenticationError as e:
# Invalid or expired API credentials
print(f"Authentication failed: {e.message}")
print(f"Error code: {e.code}")
except ValidationError as e:
# Invalid input parameters
print(f"Validation error: {e.message}")
print(f"Field: {e.field}")
print(f"Details: {e.details}")
except NotFoundError as e:
# Product or resource not found
print(f"Not found: {e.message}")
print(f"Resource type: {e.resource_type}")
print(f"Resource ID: {e.resource_id}")
except RateLimitError as e:
# API rate limit exceeded
print(f"Rate limit exceeded: {e.message}")
print(f"Retry after: {e.retry_after} seconds")
except NetworkError as e:
# Network connectivity issues
print(f"Network error: {e.message}")
print(f"Retryable: {e.retryable}")
except BlockchainError as e:
# Blockchain transaction failed
print(f"Blockchain error: {e.message}")
print(f"Transaction hash: {e.tx_hash}")
print(f"Reason: {e.reason}")
except TagItError as e:
# Base exception for all TAG IT errors
print(f"TAG IT error: {e.message}")
print(f"Error code: {e.code}")
Always implement proper error handling in production. Use specific exception types to provide meaningful error messages to your users and log errors for debugging.