Skip to main content

API Examples

Practical code examples for integrating with the tagd-ai API.

JavaScript/Node.js

Setup

const TAGD_API_KEY = process.env.TAGD_API_KEY;
const BASE_URL = 'https://api.tagd-ai.com/v1';

async function tagdFetch(endpoint, options = {}) {
const response = await fetch(`${BASE_URL}${endpoint}`, {
...options,
headers: {
'Authorization': `Bearer ${TAGD_API_KEY}`,
'Content-Type': 'application/json',
...options.headers,
},
});
return response.json();
}

Create a Tag

async function createTag(title, content) {
const result = await tagdFetch('/tags', {
method: 'POST',
body: JSON.stringify({
title,
content: [
{ type: 'text', content }
],
permissions: {
read: 'public',
write: 'owner'
}
})
});

console.log('Created tag:', result.data.short_id);
return result.data;
}

// Usage
createTag('Product Info', 'Model X-500 specifications');

List All Tags

async function listTags(limit = 20) {
const result = await tagdFetch(`/tags?limit=${limit}&sort=updated&order=desc`);
return result.data;
}

// With pagination
async function* getAllTags() {
let offset = 0;
const limit = 100;

while (true) {
const result = await tagdFetch(`/tags?limit=${limit}&offset=${offset}`);
yield* result.data;

if (!result.pagination.has_more) break;
offset += limit;
}
}

// Usage
for await (const tag of getAllTags()) {
console.log(tag.title);
}

Upload a File

async function uploadFile(tagId, filePath, fileName) {
const formData = new FormData();
const file = await fs.readFile(filePath);
formData.append('file', new Blob([file]), fileName);
formData.append('name', fileName);

const response = await fetch(`${BASE_URL}/tags/${tagId}/files`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${TAGD_API_KEY}`,
},
body: formData
});

return response.json();
}

Set Up Webhook

async function createWebhook(url, events) {
const result = await tagdFetch('/webhooks', {
method: 'POST',
body: JSON.stringify({
name: 'My Webhook',
url,
events,
secret: 'my-webhook-secret'
})
});

return result.data;
}

// Usage
createWebhook('https://api.example.com/tagd-hook', [
'tag.created',
'tag.updated',
'qr.scanned'
]);

Python

Setup

import os
import requests

TAGD_API_KEY = os.environ.get('TAGD_API_KEY')
BASE_URL = 'https://api.tagd-ai.com/v1'

def tagd_request(endpoint, method='GET', data=None):
headers = {
'Authorization': f'Bearer {TAGD_API_KEY}',
'Content-Type': 'application/json'
}

url = f'{BASE_URL}{endpoint}'
response = requests.request(method, url, headers=headers, json=data)
return response.json()

Create a Tag

def create_tag(title, content):
return tagd_request('/tags', method='POST', data={
'title': title,
'content': [
{'type': 'text', 'content': content}
],
'permissions': {
'read': 'public',
'write': 'owner'
}
})

# Usage
result = create_tag('Equipment Tag', 'Serial: SN-12345')
print(f"Created: {result['data']['short_id']}")

Bulk Create Tags

def create_bulk_tags(tags_data):
return tagd_request('/tags/batch', method='POST', data={
'tags': tags_data
})

# Usage
tags = [
{'title': f'Asset-{i:03d}', 'content': [{'type': 'text', 'content': f'Asset #{i}'}]}
for i in range(1, 51)
]
result = create_bulk_tags(tags)
print(f"Created {result['data']['created']} tags")

Get Analytics

def get_tag_analytics(tag_id, start_date, end_date):
params = f'?start_date={start_date}&end_date={end_date}'
return tagd_request(f'/tags/{tag_id}/analytics{params}')

# Usage
analytics = get_tag_analytics('abc123', '2024-01-01', '2024-01-31')
print(f"Total views: {analytics['data']['summary']['total_views']}")

cURL Examples

Create Tag

curl -X POST https://api.tagd-ai.com/v1/tags \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"title": "My Tag",
"content": [{"type": "text", "content": "Hello World"}]
}'

Update Tag

curl -X PUT https://api.tagd-ai.com/v1/tags/abc123 \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"title": "Updated Title"
}'

Download QR Code

curl "https://api.tagd-ai.com/v1/tags/abc123/qr?format=svg&size=1024" \
-H "Authorization: Bearer YOUR_API_KEY" \
-o qr-code.svg

Upload File

curl -X POST https://api.tagd-ai.com/v1/tags/abc123/files \
-H "Authorization: Bearer YOUR_API_KEY" \
-F "[email protected]" \
-F "name=User Manual"

Webhook Handling

Express.js Handler

const express = require('express');
const crypto = require('crypto');

const app = express();
app.use(express.json());

const WEBHOOK_SECRET = process.env.TAGD_WEBHOOK_SECRET;

function verifySignature(payload, signature) {
const expected = crypto
.createHmac('sha256', WEBHOOK_SECRET)
.update(JSON.stringify(payload))
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(`sha256=${expected}`)
);
}

app.post('/webhook', (req, res) => {
const signature = req.headers['x-tagd-signature'];

if (!verifySignature(req.body, signature)) {
return res.status(401).send('Invalid signature');
}

const { event, data } = req.body;

switch (event) {
case 'tag.created':
console.log('New tag:', data.tag.title);
break;
case 'qr.scanned':
console.log('QR scanned:', data.tag_id);
break;
default:
console.log('Event:', event);
}

res.sendStatus(200);
});

app.listen(3000);

Python Flask Handler

from flask import Flask, request, abort
import hmac
import hashlib

app = Flask(__name__)
WEBHOOK_SECRET = os.environ.get('TAGD_WEBHOOK_SECRET')

def verify_signature(payload, signature):
expected = 'sha256=' + hmac.new(
WEBHOOK_SECRET.encode(),
payload,
hashlib.sha256
).hexdigest()
return hmac.compare_digest(expected, signature)

@app.route('/webhook', methods=['POST'])
def handle_webhook():
signature = request.headers.get('X-tagd-ai-Signature', '')

if not verify_signature(request.data, signature):
abort(401)

event = request.json.get('event')
data = request.json.get('data')

if event == 'tag.created':
print(f"New tag: {data['tag']['title']}")
elif event == 'qr.scanned':
print(f"QR scanned: {data['tag_id']}")

return '', 200

Error Handling

JavaScript with Retry

async function tagdFetchWithRetry(endpoint, options = {}, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await fetch(`${BASE_URL}${endpoint}`, {
...options,
headers: {
'Authorization': `Bearer ${TAGD_API_KEY}`,
'Content-Type': 'application/json',
...options.headers,
},
});

if (response.status === 429) {
const retryAfter = response.headers.get('Retry-After') || 1;
await new Promise(r => setTimeout(r, retryAfter * 1000));
continue;
}

if (!response.ok) {
const error = await response.json();
throw new Error(error.error?.message || 'API request failed');
}

return response.json();
} catch (error) {
if (attempt === maxRetries - 1) throw error;
await new Promise(r => setTimeout(r, 1000 * Math.pow(2, attempt)));
}
}
}

Full Integration Example

Asset Management System

class tagd-aiAssetManager {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://api.tagd-ai.com/v1';
}

async createAsset(assetData) {
// Create the tag
const tag = await this.createTag({
title: `Asset: ${assetData.name}`,
content: [
{ type: 'heading', level: 1, content: assetData.name },
{ type: 'text', content: `Serial: ${assetData.serial}` },
{ type: 'text', content: `Location: ${assetData.location}` },
{ type: 'callout', style: 'info', content: assetData.notes }
]
});

// Upload documentation if provided
if (assetData.documentPath) {
await this.uploadFile(tag.id, assetData.documentPath);
}

// Return tag info with QR code URL
return {
tagId: tag.id,
shortId: tag.short_id,
qrCodeUrl: `${this.baseUrl}/tags/${tag.id}/qr?format=png&size=512`
};
}

async updateAssetLocation(tagId, newLocation) {
const tag = await this.getTag(tagId);
const content = tag.content.map(block => {
if (block.type === 'text' && block.content.startsWith('Location:')) {
return { ...block, content: `Location: ${newLocation}` };
}
return block;
});

return this.updateTag(tagId, { content });
}

async getAssetHistory(tagId, days = 30) {
const endDate = new Date().toISOString().split('T')[0];
const startDate = new Date(Date.now() - days * 86400000)
.toISOString().split('T')[0];

return this.getAnalytics(tagId, startDate, endDate);
}
}

// Usage
const manager = new tagd-aiAssetManager(process.env.TAGD_API_KEY);

const asset = await manager.createAsset({
name: 'MacBook Pro',
serial: 'C02XL1234567',
location: 'Office 301',
notes: 'Assigned to Engineering team',
documentPath: './manuals/macbook-setup.pdf'
});

console.log(`Asset created! QR: ${asset.qrCodeUrl}`);

Next Steps