(415) 300-0180
pip install givehub-sdk
poetry add givehub-sdk
import asyncio
from givehub import GiveHubSDK
async def main():
# Initialize the SDK
= GiveHubSDK({
givehub 'base_url': 'https://api.thegivehub.com',
'version': 'v1',
'api_key': 'your-api-key'
})
# Use the SDK
try:
= await givehub.campaigns.list()
campaigns print('Active campaigns:', campaigns)
except GiveHubException as e:
print('Error:', str(e))
if __name__ == "__main__":
asyncio.run(main())
try:
= await givehub.auth.login('user@example.com', 'password123')
result print(f"Logged in as: {result['user']['username']}")
except GiveHubException as e:
print(f"Login failed: {str(e)}")
try:
= {
user_data 'email': 'newuser@example.com',
'password': 'secure123',
'firstName': 'John',
'lastName': 'Doe'
}= await givehub.auth.register(user_data)
result print(f"Registration successful. User ID: {result['userId']}")
except GiveHubException as e:
print(f"Registration failed: {str(e)}")
try:
await givehub.auth.verify_email('user@example.com', '123456')
print("Email verified successfully")
except GiveHubException as e:
print(f"Verification failed: {str(e)}")
try:
= await givehub.campaigns.create({
campaign 'title': 'Clean Water Project',
'description': 'Providing clean water access',
'targetAmount': 50000,
'category': 'water',
'milestones': [{
'description': 'Phase 1: Survey',
'amount': 10000
}]
})print(f"Campaign created with ID: {campaign['id']}")
except GiveHubException as e:
print(f"Failed to create campaign: {str(e)}")
try:
= await givehub.campaigns.get('campaign-id')
campaign print(f"Campaign title: {campaign['title']}")
except GiveHubException as e:
print(f"Failed to get campaign: {str(e)}")
try:
= await givehub.campaigns.list(
campaigns ='water',
category='active',
status=1,
page=10
limit
)for campaign in campaigns['data']:
print(campaign['title'])
except GiveHubException as e:
print(f"Failed to list campaigns: {str(e)}")
try:
= await givehub.campaigns.upload_media(
result 'campaign-id',
'/path/to/image.jpg'
)print("Media uploaded successfully")
except GiveHubException as e:
print(f"Upload failed: {str(e)}")
try:
= await givehub.donations.create({
donation 'campaignId': 'campaign-id',
'amount': {
'value': 100,
'currency': 'USD'
},'type': 'one-time'
})print("Donation processed successfully")
except GiveHubException as e:
print(f"Donation failed: {str(e)}")
try:
= await givehub.donations.create_recurring({
recurring 'campaignId': 'campaign-id',
'amount': {
'value': 50,
'currency': 'USD'
},'frequency': 'monthly'
})print("Recurring donation set up successfully")
except GiveHubException as e:
print(f"Failed to set up recurring donation: {str(e)}")
try:
= await givehub.impact.create_metrics('campaign-id', {
metrics 'metrics': [{
'name': 'People Helped',
'value': 500,
'unit': 'individuals'
}, {'name': 'Water Access',
'value': 1000,
'unit': 'liters/day'
}]
})print("Impact metrics created successfully")
except GiveHubException as e:
print(f"Failed to create metrics: {str(e)}")
async with givehub.notifications as notifications:
# Register handlers
@notifications.on('donation_received')
async def handle_donation(notification):
print(f"New donation: {notification['amount']}")
@notifications.on('milestone_completed')
async def handle_milestone(notification):
print(f"Milestone completed: {notification['milestone']}")
# Keep connection alive
await asyncio.sleep(3600) # 1 hour
try:
# Connect to notifications
await givehub.notifications.connect()
# Register handlers
async def handle_donation(notification):
print(f"New donation: {notification['amount']}")
'donation_received', handle_donation)
givehub.notifications.on(
# Keep connection alive
await asyncio.sleep(3600) # 1 hour
finally:
# Clean up
await givehub.notifications.disconnect()
class CampaignManager:
def __init__(self, givehub: GiveHubSDK):
self.givehub = givehub
async def create_campaign_with_milestones(self, data: dict, milestones: list):
try:
# Create campaign
= await self.givehub.campaigns.create({
campaign 'title': data['title'],
'description': data['description'],
'targetAmount': data['targetAmount'],
'category': data['category'],
'milestones': milestones
})
# Upload media if provided
if 'mediaPath' in data:
await self.givehub.campaigns.upload_media(
'id'],
campaign['mediaPath']
data[
)
return campaign
except GiveHubException as e:
f"Campaign creation failed: {str(e)}")
logging.error(raise
class ImpactTracker:
def __init__(self, givehub: GiveHubSDK):
self.givehub = givehub
async def track_progress(self, campaign_id: str, metrics: list):
try:
# Update metrics
= await self.givehub.impact.update_metrics(
result
campaign_id,'metrics': metrics}
{
)
# Create update
await self._create_impact_update(campaign_id, metrics)
return result
except GiveHubException as e:
f"Impact tracking failed: {str(e)}")
logging.error(raise
async def _create_impact_update(self, campaign_id: str, metrics: list):
= "Impact Update:\n\n"
content for metric in metrics:
+= f"- {metric['name']}: {metric['value']} {metric['unit']}\n"
content
return await self.givehub.updates.create({
'campaignId': campaign_id,
'title': 'Impact Metrics Updated',
'content': content,
'type': 'impact'
})
The SDK provides comprehensive type hints for better IDE support:
from givehub.types import (
Campaign,
Donation,
ImpactMetric,
Update,
Notification
)
async def process_campaign(campaign: Campaign) -> None:
pass
async def handle_donation(donation: Donation) -> None:
pass
The SDK raises GiveHubException
for all errors:
try:
= await givehub.campaigns.create(campaign_data)
result except GiveHubException as e:
if e.status_code == 401:
# Handle authentication error
pass
elif e.status_code == 400:
# Handle validation error
pass
else:
# Handle other errors
pass
f"API Error: {str(e)}") logging.error(
= {
config 'base_url': 'https://api.thegivehub.com', # API base URL
'version': 'v1', # API version
'api_key': 'your-api-key', # Your API key
'timeout': 30, # Request timeout in seconds
'verify_ssl': True, # Verify SSL certificates
'debug': False # Enable debug mode
}
Enable debug mode to see detailed logs:
import logging
=logging.DEBUG)
logging.basicConfig(level
= GiveHubSDK({
givehub 'debug': True,
# other config...
})