Skip to main content

Overview

This section provides comprehensive code examples and implementations for integrating with the SundayPyjamas AI Suite API. All examples are production-ready and include proper error handling, authentication, and best practices.
Choose your preferred programming language to get started with complete, runnable examples.

Available Examples

Quick Start Examples

Get started immediately with these simple examples:
const response = await fetch('https://suite.sundaypyjamas.com/api/v1/chat', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer spj_ai_your_api_key_here',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    messages: [{ role: 'user', content: 'Hello!' }]
  })
});

const reader = response.body.getReader();
const decoder = new TextDecoder();
let result = '';

while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  result += decoder.decode(value);
}

console.log(result);

Example Applications

Content Generation Tools

Create engaging blog posts with customizable tone, length, and audience targeting.Features:
  • Dynamic prompt generation
  • Content structure templates
  • SEO optimization
  • Multiple output formats
View JavaScript Implementation → View Python Implementation →
Generate professional emails for various purposes and audiences.Features:
  • Template-based generation
  • Tone customization
  • Recipient personalization
  • Follow-up sequences
View Examples →
Create compelling marketing copy that drives conversions.Features:
  • Audience targeting
  • A/B testing variants
  • Call-to-action optimization
  • Brand voice consistency
View Examples →

Interactive Applications

Build conversational AI interfaces with real-time streaming.Features:
  • Real-time streaming responses
  • Message history management
  • React component examples
  • Mobile-responsive design
View React Implementation →
Create powerful CLI applications for batch processing and automation.Features:
  • Interactive chat mode
  • Batch processing
  • Progress tracking
  • Configuration management
View CLI Implementation →
Full-featured web applications with API integration.Features:
  • Express.js server examples
  • Authentication middleware
  • Error handling
  • Rate limiting
View Server Examples →

Advanced Use Cases

Process multiple requests efficiently with queue management.Features:
  • Concurrent request handling
  • Progress tracking
  • Error recovery
  • Performance optimization
View Implementation →
Real-time streaming responses for better user experience.Features:
  • Progressive response display
  • Cancellation support
  • Error handling
  • Performance monitoring
View Examples →
Automated content generation workflows.Features:
  • Multi-step processing
  • Quality control
  • Template management
  • Output formatting
View Pipeline Examples →

Implementation Features

All examples include these production-ready features:

Error Handling

Comprehensive error handling with retry logic and graceful degradation

Authentication

Secure API key management and best practices

Rate Limiting

Built-in rate limiting and usage optimization

Streaming Support

Real-time streaming responses for better UX

TypeScript Support

Full TypeScript definitions and type safety

Testing

Unit tests and integration examples

Documentation

Inline documentation and usage examples

Monitoring

Usage tracking and performance monitoring

Best Practices Covered

Security

  • Environment variable management
  • API key protection
  • Input validation and sanitization
  • HTTPS enforcement

Performance

  • Connection pooling
  • Request batching
  • Caching strategies
  • Memory optimization

Reliability

  • Exponential backoff
  • Circuit breaker patterns
  • Timeout handling
  • Graceful degradation

Monitoring

  • Usage tracking
  • Error logging
  • Performance metrics
  • Alert systems

Environment Setup

Prerequisites

package.json
{
  "name": "sundaypyjamas-ai-examples",
  "version": "1.0.0",
  "type": "module",
  "dependencies": {
    "node-fetch": "^3.0.0",
    "@types/node": "^20.0.0"
  },
  "devDependencies": {
    "typescript": "^5.0.0",
    "@types/jest": "^29.0.0",
    "jest": "^29.0.0"
  }
}
Installation:
npm install
# or
yarn install

Testing Your Setup

Verify your environment is configured correctly:
// test-setup.js
import fetch from 'node-fetch';

const API_KEY = process.env.SUNDAYPYJAMAS_API_KEY;
const API_URL = process.env.SUNDAYPYJAMAS_API_URL;

async function testSetup() {
  if (!API_KEY) {
    console.error('❌ SUNDAYPYJAMAS_API_KEY not set');
    return;
  }

  try {
    const response = await fetch(`${API_URL}/chat`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        messages: [{ role: 'user', content: 'Test connection' }]
      })
    });

    if (response.ok) {
      console.log('✅ API connection successful');
    } else {
      console.error('❌ API connection failed:', response.status);
    }
  } catch (error) {
    console.error('❌ Connection error:', error.message);
  }
}

testSetup();

Contributing Examples

We welcome contributions to improve and expand our examples:

Submit Examples

Share your own implementations and use cases

Report Issues

Help us fix bugs and improve documentation

Request Features

Suggest new examples or improvements

Join Community

Connect with other developers using the API

Next Steps

All examples are designed to be copied and adapted for your specific use case. Feel free to modify them as needed for your applications.