🔄 Data Flow & APIs - OPEN API Integration
This document provides comprehensive information about the MyPit OPEN API endpoints available for external platform integration. These endpoints enable third-party systems to integrate with MyPit's badge management, holder management, and badge issuance capabilities.
Production API endpoints and Docs
https://mypit-api.daosolution.io/
📋 Complete API Reference Summary
| Endpoint | Method | Purpose | Authentication |
|---|---|---|---|
/hello | GET | Health check | Required |
/createBadgeTemplate | POST | Create badge template | Required |
/getAllBadgeTemplatesByOwnerId | POST | List badge templates | Required |
/getASingleBadgeTemplate | POST | Get specific template | Required |
/updateBadgeTemplate | POST | Update template | Required |
/deleteBadgeTemplate | POST | Delete template | Required |
/createHolder | POST | Create badge holder | Required |
/updateHolder | POST | Update holder info | Required |
/deleteHolder | POST | Delete holder | Required |
/getHolderById | POST | Get specific holder | Required |
/getHolders | POST | List holders | Required |
/issueBadge | POST | Issue badges | Required |
/getIssuedBadges | POST | List issued badges | Required |
🌐 OPEN API Architecture
Authentication Requirements
All OPEN API endpoints require authentication via HTTP headers:
typescript
interface APIAuthHeaders {
clientId: string; // Your API client ID
secretKey: string; // Your API secret key
}
// Example usage
const headers = {
'Content-Type': 'application/json',
'clientId': 'your-client-id',
'secretKey': 'your-secret-key'
};API Base URL
Base URL: https://your-mypit-domain.comAvailable OPEN API Endpoints
System Health Check
typescript
// GET /hello
// Simple health check endpoint to verify API connectivity
interface HelloResponse {
message: string; // "Hello, from MyPit!"
}
// No request body required for GET request
// Authentication headers still requiredBadge Template Management Endpoints
typescript
// POST /createBadgeTemplate
interface BadgeTemplateCreationRequest {
userId: string; // ID of the user creating the template
imageUrl: string; // URL of the badge image
typeOfBadge: "mobility" | "achievement" | "healthcare" | "finance";
name: string; // Badge template name
validityPeriod: number; // Validity period in days
description: string; // Badge description
criteria: string; // Badge criteria
price: number; // Badge price
}
interface BadgeTemplateCreationResponse {
_id: string; // Created template ID
// Additional template details returned
}
// POST /getAllBadgeTemplatesByOwnerId
interface BadgeTemplateListRequest {
userId: string; // Owner's user ID
paginationOpts: {
numItems: number; // Number of items per page
cursor?: string; // Pagination cursor
};
}
interface BadgeTemplateListResponse {
page: BadgeTemplate[]; // Array of badge templates
hasMore: boolean; // Whether more pages exist
cursor?: string; // Next page cursor
}
// POST /getASingleBadgeTemplate
interface SingleBadgeTemplateRequest {
userId: string; // User ID
templateId: string; // Badge template ID
}
interface SingleBadgeTemplateResponse {
// Complete badge template object
_id: string;
name: string;
type: "mobility" | "achievement" | "healthcare" | "finance";
description: string;
criteria: string;
validityPeriod: number;
imageUrl?: string;
backgroundColor: string;
textColor: string;
price: number;
isActive: boolean;
ownerId: string;
createdAt: number;
updatedAt: number;
}
// POST /updateBadgeTemplate
interface BadgeTemplateUpdateRequest {
userId: string; // Owner's user ID
templateId: string; // Template ID to update
data: {
name: string;
type: "mobility" | "achievement" | "healthcare" | "finance";
description: string;
criteria: string;
validityPeriod: number;
imageUrl?: string;
backgroundColor: string;
textColor: string;
price: number;
updatedAt: number;
};
}
interface BadgeTemplateUpdateResponse {
_id: string; // Updated template ID
}
// POST /deleteBadgeTemplate
interface BadgeTemplateDeletionRequest {
userId: string; // Owner's user ID
templateId: string; // Template ID to delete
}
interface BadgeTemplateDeletionResponse {
_id: string; // Deleted template ID
}Holder Management Endpoints
typescript
// POST /createHolder
interface HolderCreationRequest {
issuerDid: string; // Issuer's DID
issuerId: string; // Issuer's user ID
data: {
name: string; // Holder's name
email: string; // Holder's email
phone: string; // Holder's phone number
ownerId: string; // Owner ID (same as issuerId)
memo?: string; // Optional memo
holderDid: string; // Holder's DID
holderId: string; // Holder's ID
};
}
interface HolderCreationResponse {
_id: string; // Created holder ID
// Additional holder details
}
// POST /updateHolder
interface HolderUpdateRequest {
holderID: string; // Holder ID to update
issuerId: string; // Issuer's user ID
data: {
name: string; // Updated name
email: string; // Updated email
phone: string; // Updated phone
};
}
interface HolderUpdateResponse {
_id: string; // Updated holder ID
}
// POST /deleteHolder
interface HolderDeletionRequest {
holderID: string; // Holder ID to delete
issuerId: string; // Issuer's user ID
}
interface HolderDeletionResponse {
success: boolean; // Deletion status
}
// POST /getHolderById
interface SingleHolderRequest {
userId: string; // User ID
holderId: string; // Holder ID
}
interface SingleHolderResponse {
_id: string;
name: string;
email: string;
phone: string;
ownerId: string;
holderDid: string;
issuerDid: string;
memo?: string;
// Additional holder fields
}
// POST /getHolders
interface HolderListRequest {
userId: string; // User ID
paginationOpts: {
numItems: number; // Number of items per page
cursor?: string; // Pagination cursor
};
}
interface HolderListResponse {
page: Holder[]; // Array of holders
hasMore: boolean; // Whether more pages exist
cursor?: string; // Next page cursor
}Badge Issuance & Management Endpoints
typescript
// POST /issueBadge
interface BadgeIssuanceRequest {
userId: string; // Issuer's user ID
validityPeriod: number; // Badge validity period in days
templateId: string; // Badge template ID
badgeData: any; // Additional badge data
recipientIds: string[]; // Array of recipient holder IDs
type: "mobility" | "achievement" | "healthcare" | "finance";
}
interface BadgeIssuanceResponse {
// Array of issued badge IDs or confirmation
issuedBadges: string[];
status: 'success' | 'partial' | 'failed';
details?: {
successful: string[];
failed: {
recipientId: string;
error: string;
}[];
};
}
// POST /getIssuedBadges
interface IssuedBadgeListRequest {
userId: string; // Issuer's user ID
paginationOpts: {
numItems: number; // Number of items per page
cursor?: string; // Pagination cursor
};
}
interface IssuedBadgeListResponse {
page: IssuedBadge[]; // Array of issued badges
hasMore: boolean; // Whether more pages exist
cursor?: string; // Next page cursor
}
interface IssuedBadge {
_id: string; // Badge ID
templateId: string; // Template ID used
recipientId: string; // Recipient holder ID
issuerId: string; // Issuer user ID
issuedAt: number; // Issuance timestamp
expiresAt: number; // Expiration timestamp
status: string; // Badge status
type: "mobility" | "achievement" | "healthcare" | "finance";
// Additional badge details
}🔧 Error Handling
All OPEN API endpoints return standardized error responses:
typescript
interface ErrorResponse {
error: string; // Error message description
status?: number; // HTTP status code
}
// Common error responses:
// 400 - Missing clientId or secretKey
// 401 - Invalid clientId or secretKey
// 403 - Insufficient permissions
// 404 - Resource not found
// 500 - Internal server error📋 Badge Type Definitions
typescript
type BadgeType = "mobility" | "achievement" | "healthcare" | "finance";
// Badge types supported:
// - mobility: Transportation and mobility-related badges
// - achievement: Academic and personal achievement badges
// - healthcare: Health and wellness-related badges
// - finance: Financial literacy and achievement badges🔄 OPEN API Data Flow Patterns
1. Badge Template Creation Flow
2. Holder Management Flow
3. Badge Issuance Flow
4. Badge Data Retrieval Flow
🔌 OPEN API Integration Examples
JavaScript/Node.js Integration
javascript
// MyPit OPEN API Client Example
class MyPitAPIClient {
constructor(clientId, secretKey, baseUrl = 'https://your-mypit-domain.com') {
this.clientId = clientId;
this.secretKey = secretKey;
this.baseUrl = baseUrl;
}
async makeRequest(endpoint, method = 'POST', data = null) {
const headers = {
'Content-Type': 'application/json',
'clientId': this.clientId,
'secretKey': this.secretKey
};
const config = {
method,
headers,
};
if (data && method !== 'GET') {
config.body = JSON.stringify(data);
}
const response = await fetch(`${this.baseUrl}${endpoint}`, config);
if (!response.ok) {
const error = await response.json();
throw new Error(`API Error: ${error.error}`);
}
return response.json();
}
// Health check
async healthCheck() {
return this.makeRequest('/hello', 'GET');
}
// Badge template operations
async createBadgeTemplate(templateData) {
return this.makeRequest('/createBadgeTemplate', 'POST', templateData);
}
async getBadgeTemplates(userId, paginationOpts) {
return this.makeRequest('/getAllBadgeTemplatesByOwnerId', 'POST', {
userId,
paginationOpts
});
}
// Holder operations
async createHolder(holderData) {
return this.makeRequest('/createHolder', 'POST', holderData);
}
async getHolders(userId, paginationOpts) {
return this.makeRequest('/getHolders', 'POST', {
userId,
paginationOpts
});
}
// Badge issuance
async issueBadge(badgeData) {
return this.makeRequest('/issueBadge', 'POST', badgeData);
}
async getIssuedBadges(userId, paginationOpts) {
return this.makeRequest('/getIssuedBadges', 'POST', {
userId,
paginationOpts
});
}
}
// Usage example
const client = new MyPitAPIClient('your-client-id', 'your-secret-key');
// Create a badge template
const template = await client.createBadgeTemplate({
userId: 'user123',
imageUrl: 'https://example.com/badge.png',
typeOfBadge: 'achievement',
name: 'Course Completion',
validityPeriod: 365,
description: 'Awarded for completing the course',
criteria: 'Complete all modules and pass final exam',
price: 0
});
// Issue a badge to holders
const issuanceResult = await client.issueBadge({
userId: 'user123',
validityPeriod: 365,
templateId: template._id,
badgeData: { courseId: 'course456' },
recipientIds: ['holder789', 'holder101'],
type: 'achievement'
});Python Integration
python
import requests
import json
class MyPitAPIClient:
def __init__(self, client_id, secret_key, base_url='https://your-mypit-domain.com'):
self.client_id = client_id
self.secret_key = secret_key
self.base_url = base_url
self.session = requests.Session()
self.session.headers.update({
'Content-Type': 'application/json',
'clientId': client_id,
'secretKey': secret_key
})
def make_request(self, endpoint, method='POST', data=None):
url = f"{self.base_url}{endpoint}"
if method == 'GET':
response = self.session.get(url)
else:
response = self.session.post(url, json=data)
if not response.ok:
error_data = response.json()
raise Exception(f"API Error: {error_data.get('error', 'Unknown error')}")
return response.json()
def health_check(self):
return self.make_request('/hello', 'GET')
def create_badge_template(self, template_data):
return self.make_request('/createBadgeTemplate', 'POST', template_data)
def create_holder(self, holder_data):
return self.make_request('/createHolder', 'POST', holder_data)
def issue_badge(self, badge_data):
return self.make_request('/issueBadge', 'POST', badge_data)
# Usage example
client = MyPitAPIClient('your-client-id', 'your-secret-key')
# Health check
health = client.health_check()
print(f"API Status: {health['message']}")
# Create holder
holder = client.create_holder({
'issuerDid': 'did:ethr:0x123...',
'issuerId': 'user123',
'data': {
'name': 'John Doe',
'email': 'john@example.com',
'phone': '+1234567890',
'ownerId': 'user123',
'holderDid': 'did:ethr:0x456...',
'holderId': 'holder789'
}
})📊 API Best Practices
Rate Limiting & Throttling
javascript
// Implement client-side rate limiting
class RateLimitedClient extends MyPitAPIClient {
constructor(clientId, secretKey, baseUrl, requestsPerMinute = 60) {
super(clientId, secretKey, baseUrl);
this.requestQueue = [];
this.requestsPerMinute = requestsPerMinute;
this.intervalMs = 60000 / requestsPerMinute;
this.lastRequestTime = 0;
}
async makeRequest(endpoint, method = 'POST', data = null) {
// Rate limiting logic
const now = Date.now();
const timeSinceLastRequest = now - this.lastRequestTime;
if (timeSinceLastRequest < this.intervalMs) {
await new Promise(resolve =>
setTimeout(resolve, this.intervalMs - timeSinceLastRequest)
);
}
this.lastRequestTime = Date.now();
return super.makeRequest(endpoint, method, data);
}
}Error Handling & Retry Logic
javascript
// Robust error handling with exponential backoff
async function makeRequestWithRetry(client, endpoint, method, data, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await client.makeRequest(endpoint, method, data);
} catch (error) {
if (attempt === maxRetries) {
throw error;
}
// Exponential backoff: 1s, 2s, 4s
const delay = Math.pow(2, attempt) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
console.log(`Attempt ${attempt} failed, retrying in ${delay}ms...`);
}
}
}Batch Operations
javascript
// Efficient batch processing for multiple badge issuances
async function batchIssueBadges(client, userId, templateId, recipientIds, batchSize = 10) {
const results = [];
const errors = [];
// Process in batches to avoid overwhelming the API
for (let i = 0; i < recipientIds.length; i += batchSize) {
const batch = recipientIds.slice(i, i + batchSize);
try {
const result = await client.issueBadge({
userId,
templateId,
recipientIds: batch,
validityPeriod: 365,
type: 'achievement',
badgeData: {}
});
results.push(...result.issuedBadges);
} catch (error) {
errors.push({
batch,
error: error.message
});
}
// Brief pause between batches
await new Promise(resolve => setTimeout(resolve, 100));
}
return { results, errors };
}🔧 API Testing & Monitoring
Testing Your Integration
javascript
// Complete integration test example
async function testMyPitIntegration() {
const client = new MyPitAPIClient('test-client-id', 'test-secret-key');
try {
// 1. Health check
console.log('Testing API connectivity...');
const health = await client.healthCheck();
console.log('✅ API is healthy:', health.message);
// 2. Create a badge template
console.log('Creating badge template...');
const template = await client.createBadgeTemplate({
userId: 'test-user-123',
imageUrl: 'https://example.com/test-badge.png',
typeOfBadge: 'achievement',
name: 'Integration Test Badge',
validityPeriod: 30,
description: 'Test badge for API integration',
criteria: 'Complete integration test',
price: 0
});
console.log('✅ Template created:', template._id);
// 3. Create a holder
console.log('Creating holder...');
const holder = await client.createHolder({
issuerDid: 'did:ethr:0x123test',
issuerId: 'test-user-123',
data: {
name: 'Test Holder',
email: 'test.holder@example.com',
phone: '+1234567890',
ownerId: 'test-user-123',
holderDid: 'did:ethr:0x456test',
holderId: 'test-holder-456'
}
});
console.log('✅ Holder created:', holder._id);
// 4. Issue a badge
console.log('Issuing badge...');
const issuance = await client.issueBadge({
userId: 'test-user-123',
validityPeriod: 30,
templateId: template._id,
badgeData: { testData: 'integration-test' },
recipientIds: [holder._id],
type: 'achievement'
});
console.log('✅ Badge issued:', issuance);
// 5. Retrieve issued badges
console.log('Retrieving issued badges...');
const badges = await client.getIssuedBadges('test-user-123', {
numItems: 10,
cursor: null
});
console.log('✅ Badges retrieved:', badges.page.length, 'badges found');
console.log('🎉 All tests passed! Integration is working correctly.');
} catch (error) {
console.error('❌ Test failed:', error.message);
throw error;
}
}
// Run the test
testMyPitIntegration();Webhook Integration (Future Enhancement)
javascript
// Example webhook handler for real-time notifications
app.post('/webhook/mypit-notifications', (req, res) => {
const { event, data } = req.body;
switch (event) {
case 'badge.issued':
console.log('Badge issued:', data.badgeId);
// Handle badge issuance notification
break;
case 'holder.created':
console.log('Holder created:', data.holderId);
// Handle new holder notification
break;
case 'template.created':
console.log('Template created:', data.templateId);
// Handle template creation notification
break;
default:
console.log('Unknown event:', event);
}
res.status(200).json({ received: true });
});This comprehensive OPEN API documentation provides everything needed for external platforms to integrate with MyPit's badge management system. All endpoints require proper authentication and follow consistent request/response patterns for reliable integration.