This directory contains example scripts demonstrating how to use the BlackRoad Python SDK.
Before running these examples:
-
Install the SDK:
cd .. pip install -e .
-
Start the BlackRoad backend:
cd ../../../backend uvicorn app.main:app --reload -
Set environment variables (optional):
export BLACKROAD_BASE_URL="http://localhost:8000"
Basic usage example covering all major features
python quickstart.pyThis example demonstrates:
- User registration and authentication
- Wallet management
- Blockchain statistics
- Transaction history
- Block mining
- Agent operations (if available)
What you'll learn:
- How to initialize the client
- How to authenticate users
- How to interact with the blockchain
- How to mine blocks
- Basic error handling
Advanced blockchain operations
python blockchain_example.pyThis example demonstrates:
- Detailed wallet information
- Blockchain analytics
- Block explorer functionality
- Transaction monitoring
- Concurrent blockchain operations (async)
- Mining blocks
What you'll learn:
- Working with blockchain data
- Pagination for blocks and transactions
- Synchronous vs asynchronous operations
- Performance optimization with async
- Blockchain statistics analysis
Agent management and execution
python agents_example.pyThis example demonstrates:
- Listing available agents
- Filtering agents by category
- Getting agent details
- Executing agents with parameters
- Monitoring execution status
- Concurrent agent execution (async)
What you'll learn:
- How to discover available agents
- How to execute agents with custom parameters
- How to monitor agent execution
- Error handling for agent operations
- Async patterns for multiple agents
from blackroad import BlackRoadClient
# Initialize client
client = BlackRoadClient(base_url="http://localhost:8000")
try:
# Login
token = client.auth.login(username="user", password="pass")
client.set_token(token.access_token)
# Perform operations
wallet = client.blockchain.get_wallet()
print(f"Balance: {wallet.balance}")
finally:
# Always close the client
client.close()import asyncio
from blackroad import AsyncBlackRoadClient
async def main():
async with AsyncBlackRoadClient(base_url="http://localhost:8000") as client:
# Login
token = await client.auth.login(username="user", password="pass")
client.set_token(token.access_token)
# Perform operations concurrently
wallet, stats = await asyncio.gather(
client.blockchain.get_wallet(),
client.blockchain.get_stats()
)
print(f"Balance: {wallet.balance}")
print(f"Total blocks: {stats.total_blocks}")
asyncio.run(main())from blackroad import BlackRoadClient
# Automatic cleanup with context manager
with BlackRoadClient(base_url="http://localhost:8000") as client:
token = client.auth.login(username="user", password="pass")
client.set_token(token.access_token)
wallet = client.blockchain.get_wallet()
print(f"Balance: {wallet.balance}")
# Client is automatically closedAll examples include error handling. Common patterns:
from blackroad import (
AuthenticationError,
NotFoundError,
ValidationError,
BlockchainError,
)
try:
# Perform operation
result = client.some_operation()
except AuthenticationError as e:
print(f"Authentication failed: {e}")
except NotFoundError as e:
print(f"Resource not found: {e}")
except ValidationError as e:
print(f"Invalid data: {e}")
except BlockchainError as e:
print(f"Blockchain error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")When creating your own scripts, follow this structure:
#!/usr/bin/env python3
"""
Your Script Name
================
Description of what the script does.
"""
import os
import sys
# Add parent directory to path if running from examples/
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from blackroad import BlackRoadClient
def main():
"""Main function."""
client = BlackRoadClient(
base_url=os.getenv("BLACKROAD_BASE_URL", "http://localhost:8000")
)
try:
# Your code here
pass
finally:
client.close()
if __name__ == "__main__":
main()- Always use environment variables for URLs and credentials
- Use context managers to ensure proper cleanup
- Handle exceptions appropriately for production code
- Use async for better performance when making multiple requests
- Check the backend is running before running examples
- Start with quickstart.py to understand the basics
NetworkError: Connection refused
Solution: Start the backend server first:
cd ../../../backend
uvicorn app.main:app --reloadAuthenticationError: Username or email already registered
Solution: The examples try to create a user. If it already exists, they'll log in instead.
ModuleNotFoundError: No module named 'blackroad'
Solution: Install the SDK:
cd ..
pip install -e .After exploring these examples:
- Read the main README for detailed API documentation
- Check out the tests/ directory for more usage patterns
- Build your own application using the SDK
- Contribute your own examples!
Happy coding! 🛣️