SDK Documentation

Official SDKs for integrating with GreenMonkey's marketplace platform.

Available SDKs

  • JavaScript/TypeScript - Full support, recommended
  • Python - Full support
  • Ruby - Coming soon
  • PHP - Coming soon
  • Go - Coming soon
  • Java - Coming soon

JavaScript/TypeScript SDK

Installation

# npm
npm install @greenmonkey/sdk

# yarn
yarn add @greenmonkey/sdk

# pnpm
pnpm add @greenmonkey/sdk

Quick Start

import { GreenMonkey } from '@greenmonkey/sdk';

// Initialize client
const gm = new GreenMonkey({
  apiKey: process.env.GREENMONKEY_API_KEY,
  // Optional configurations
  baseURL: 'https://api.greenmonkey.dev/v1',
  timeout: 30000,
  retries: 3,
});

// List products
const products = await gm.products.list({
  type: 'prompt',
  category: 'marketing',
  limit: 20,
});

// Get specific product
const product = await gm.products.get('prod_123');

// Purchase a product
const order = await gm.purchases.create({
  productId: 'prod_123',
  paymentMethodId: 'pm_456', // Optional
});

Configuration

const gm = new GreenMonkey({
  apiKey: 'your_api_key',

  // Optional settings
  baseURL: 'https://api.greenmonkey.dev/v1',
  timeout: 30000, // 30 seconds
  retries: 3,
  retryDelay: 1000, // 1 second

  // Webhook secret for signature verification
  webhookSecret: process.env.WEBHOOK_SECRET,

  // Custom headers
  headers: {
    'X-Custom-Header': 'value',
  },

  // Request interceptor
  onRequest: (config) => {
    console.log('Request:', config);
    return config;
  },

  // Response interceptor
  onResponse: (response) => {
    console.log('Response:', response);
    return response;
  },
});

Products API

// List products with filters
const products = await gm.products.list({
  type: 'prompt', // Product type
  category: 'marketing', // Category slug
  provider: 'openai', // AI provider
  minPrice: 10, // Minimum price
  maxPrice: 100, // Maximum price
  sort: 'popularity', // Sort field
  order: 'desc', // Sort order
  search: 'SEO', // Search query
  page: 1, // Page number
  limit: 20, // Items per page
});

// Get single product
const product = await gm.products.get('prod_123');

// Create product (seller account required)
const newProduct = await gm.products.create({
  title: 'Advanced SEO Analyzer',
  description: 'AI-powered SEO analysis...',
  type: 'prompt',
  category: 'marketing',
  price: 49.99,
  content: 'System prompt content...',
  requirements: ['OpenAI API key'],
  tags: ['seo', 'marketing', 'analysis'],
});

// Update product
const updated = await gm.products.update('prod_123', {
  price: 39.99,
  description: 'Updated description...',
});

// Delete product
await gm.products.delete('prod_123');

// Product analytics
const analytics = await gm.products.analytics('prod_123', {
  period: 'month',
  startDate: '2024-01-01',
  endDate: '2024-01-31',
});

Purchases API

// Create purchase
const order = await gm.purchases.create({
  productId: 'prod_123',
  paymentMethodId: 'pm_456', // Optional, uses default
  referralCode: 'SAVE10', // Optional
});

// List purchases
const purchases = await gm.purchases.list({
  page: 1,
  limit: 20,
  status: 'completed', // completed, refunded, all
});

// Get purchase details
const purchase = await gm.purchases.get('ord_789');

// Download purchased product
const download = await gm.purchases.download('ord_789');
// Returns: { url: 'https://...', expiresAt: '2024-03-21T10:00:00Z' }

// Request refund
const refund = await gm.purchases.refund('ord_789', {
  reason: 'Not as described',
  details: "The prompt doesn't work with GPT-4",
});

AI Execution API

// Execute a prompt
const result = await gm.ai.executePrompt({
  productId: 'prod_123',
  apiKeyId: 'key_abc', // Your stored API key ID
  variables: {
    topic: 'Artificial Intelligence',
    tone: 'professional',
    length: '1000 words',
  },
  options: {
    model: 'gpt-4',
    temperature: 0.7,
    maxTokens: 2000,
  },
});

console.log(result.output);
console.log(result.usage); // Token usage and cost

// Execute a workflow
const workflowResult = await gm.ai.executeWorkflow('workflow_456', {
  input: {
    data: 'Process this data',
  },
  apiKeys: {
    openai: 'key_abc',
    anthropic: 'key_def',
  },
  webhookUrl: 'https://your-app.com/webhook', // Optional
});

// Stream execution (for long-running processes)
const stream = await gm.ai.streamExecution({
  productId: 'prod_123',
  apiKeyId: 'key_abc',
  variables: { topic: 'AI Ethics' },
});

for await (const chunk of stream) {
  console.log(chunk.delta); // Partial output
}

Analytics API

// Product analytics
const productStats = await gm.analytics.products({
  period: 'month',
  startDate: '2024-03-01',
  endDate: '2024-03-31',
  productId: 'prod_123', // Optional, all products if omitted
});

// Revenue analytics
const revenue = await gm.analytics.revenue({
  period: 'week',
  groupBy: 'day',
});

// Customer analytics
const customers = await gm.analytics.customers({
  period: 'month',
  metric: 'retention',
});

// Export analytics data
const csv = await gm.analytics.export({
  type: 'revenue',
  format: 'csv',
  period: 'year',
});

Webhooks

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

  if (!gm.webhooks.verify(req.body, signature, timestamp)) {
    return res.status(400).send('Invalid signature');
  }

  const event = JSON.parse(req.body);
  // Handle event...

  res.status(200).send('OK');
});

// Construct event from payload (for testing)
const event = gm.webhooks.constructEvent(payload, signature, timestamp);

Error Handling

import { GreenMonkeyError, RateLimitError, ValidationError } from '@greenmonkey/sdk';

try {
  const product = await gm.products.get('invalid_id');
} catch (error) {
  if (error instanceof RateLimitError) {
    console.log('Rate limited, retry after:', error.retryAfter);
  } else if (error instanceof ValidationError) {
    console.log('Validation failed:', error.details);
  } else if (error instanceof GreenMonkeyError) {
    console.log('API error:', error.message, error.code);
  } else {
    console.log('Unknown error:', error);
  }
}

TypeScript Support

Full TypeScript support with exported types:

import type {
  Product,
  Purchase,
  User,
  Analytics,
  WebhookEvent,
  ProductType,
  AIProvider,
} from '@greenmonkey/sdk';

// Type-safe product creation
const product: Partial<Product> = {
  title: 'My Product',
  type: 'PROMPT' as ProductType,
  price: 29.99,
};

// Type-safe event handling
function handleWebhook(event: WebhookEvent) {
  switch (event.type) {
    case 'purchase.completed':
      const purchase = event.data as Purchase;
      console.log('Purchase:', purchase.id);
      break;
  }
}

Python SDK

Installation

pip install greenmonkey

Quick Start

from greenmonkey import GreenMonkey
from greenmonkey.types import ProductType

# Initialize client
gm = GreenMonkey(
    api_key="your_api_key",
    # Optional configurations
    base_url="https://api.greenmonkey.dev/v1",
    timeout=30,
    max_retries=3
)

# List products
products = gm.products.list(
    type=ProductType.PROMPT,
    category="marketing",
    limit=20
)

# Get specific product
product = gm.products.get("prod_123")

# Purchase a product
order = gm.purchases.create(
    product_id="prod_123",
    payment_method_id="pm_456"  # Optional
)

Async Support

import asyncio
from greenmonkey import AsyncGreenMonkey

async def main():
    async with AsyncGreenMonkey(api_key="your_api_key") as gm:
        # Concurrent requests
        products, purchases = await asyncio.gather(
            gm.products.list(type="prompt"),
            gm.purchases.list()
        )

        # Execute AI prompt
        result = await gm.ai.execute_prompt(
            product_id="prod_123",
            api_key_id="key_abc",
            variables={
                "topic": "Machine Learning",
                "style": "technical"
            }
        )

asyncio.run(main())

Error Handling

from greenmonkey.exceptions import (
    GreenMonkeyError,
    RateLimitError,
    ValidationError,
    AuthenticationError
)

try:
    product = gm.products.get("invalid_id")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after} seconds")
except ValidationError as e:
    print(f"Validation error: {e.details}")
except AuthenticationError:
    print("Invalid API key")
except GreenMonkeyError as e:
    print(f"API error: {e.message} (Code: {e.code})")

Pandas Integration

import pandas as pd

# Get analytics as DataFrame
analytics = gm.analytics.products(
    period="month",
    start_date="2024-03-01",
    end_date="2024-03-31"
)

df = pd.DataFrame(analytics.timeline)
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)

# Plot revenue over time
df['revenue'].plot(title='Monthly Revenue')

SDK Features Comparison

Feature JavaScript Python Ruby PHP Go Java
Basic API calls 🚧 🚧 🚧 🚧
Async/await 🚧 🚧 🚧 🚧
Streaming 🚧 🚧 🚧 🚧
Webhooks 🚧 🚧 🚧 🚧
TypeScript N/A N/A N/A N/A N/A
Retry logic 🚧 🚧 🚧 🚧
Rate limiting 🚧 🚧 🚧 🚧
File uploads 🚧 🚧 🚧 🚧

Advanced Usage

Batch Operations

// JavaScript - Batch operations
const batchResults = await gm.batch([
  { method: 'products.get', params: ['prod_123'] },
  { method: 'products.get', params: ['prod_456'] },
  { method: 'products.get', params: ['prod_789'] },
]);

// Process results
batchResults.forEach((result, index) => {
  if (result.success) {
    console.log(`Product ${index}:`, result.data.title);
  } else {
    console.error(`Failed to get product ${index}:`, result.error);
  }
});

Caching

// JavaScript - With caching
import { GreenMonkey, MemoryCache } from '@greenmonkey/sdk';

const gm = new GreenMonkey({
  apiKey: 'your_api_key',
  cache: new MemoryCache({
    ttl: 300, // 5 minutes
    max: 100, // Max 100 items
  }),
});

// First call hits API
const product1 = await gm.products.get('prod_123');

// Second call uses cache
const product2 = await gm.products.get('prod_123');

Custom HTTP Client

// JavaScript - Custom axios instance
import axios from 'axios';

const customAxios = axios.create({
  proxy: {
    host: 'proxy.example.com',
    port: 8080,
  },
});

const gm = new GreenMonkey({
  apiKey: 'your_api_key',
  httpClient: customAxios,
});

Middleware

// JavaScript - Request/Response middleware
const gm = new GreenMonkey({
  apiKey: 'your_api_key',
  middleware: [
    // Logging middleware
    {
      onRequest: (config) => {
        console.log(`[${new Date().toISOString()}] ${config.method} ${config.url}`);
        return config;
      },
      onResponse: (response) => {
        console.log(`[${new Date().toISOString()}] Response: ${response.status}`);
        return response;
      },
    },
    // Metrics middleware
    {
      onRequest: (config) => {
        config.metadata = { startTime: Date.now() };
        return config;
      },
      onResponse: (response) => {
        const duration = Date.now() - response.config.metadata.startTime;
        metrics.record('api.request.duration', duration);
        return response;
      },
    },
  ],
});

Testing with SDKs

Mock Mode

// JavaScript - Mock mode for testing
import { GreenMonkey, MockAdapter } from '@greenmonkey/sdk';

const mock = new MockAdapter();

mock.onGet('/products/prod_123').reply(200, {
  id: 'prod_123',
  title: 'Test Product',
  price: 29.99,
});

const gm = new GreenMonkey({
  apiKey: 'test_key',
  adapter: mock,
});

// This won't hit the real API
const product = await gm.products.get('prod_123');

Test Helpers

// JavaScript - Test helpers
import { createTestProduct, createTestPurchase } from '@greenmonkey/sdk/test';

describe('Product Integration', () => {
  let product;

  beforeEach(async () => {
    product = await createTestProduct({
      title: 'Test Product',
      type: 'prompt',
    });
  });

  afterEach(async () => {
    await product.cleanup();
  });

  test('should purchase product', async () => {
    const purchase = await createTestPurchase({
      productId: product.id,
    });

    expect(purchase.status).toBe('completed');
  });
});

SDK Development

Contributing

We welcome contributions to our SDKs! See our GitHub repositories:

Custom SDK

Building your own SDK? Follow our patterns:

# OpenAPI specification available at:
https://api.greenmonkey.dev/v1/openapi.json

# Postman collection:
https://api.greenmonkey.dev/v1/postman.json

Support

Next Steps