> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sundaypyjamas.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Code Examples Overview

> Ready-to-use implementations for integrating the SundayPyjamas AI Suite API in multiple programming languages

## 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.

<Info>
  Choose your preferred programming language to get started with complete, runnable examples.
</Info>

## Available Examples

<CardGroup cols={3}>
  <Card title="JavaScript/TypeScript" icon="js" href="/examples/javascript">
    Node.js and browser examples with React components, streaming responses, and TypeScript support
  </Card>

  <Card title="Python" icon="python" href="/examples/python">
    Comprehensive Python integration with async support, batch processing, and CLI tools
  </Card>

  <Card title="cURL" icon="terminal" href="/examples/curl">
    Command-line examples for testing, automation, and shell scripting
  </Card>
</CardGroup>

## Quick Start Examples

Get started immediately with these simple examples:

<Tabs>
  <Tab title="JavaScript">
    ```javascript theme={null}
    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);
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import requests

    response = requests.post(
        'https://suite.sundaypyjamas.com/api/v1/chat',
        headers={'Authorization': 'Bearer spj_ai_your_api_key_here'},
        json={'messages': [{'role': 'user', 'content': 'Hello!'}]},
        stream=True
    )

    full_response = ''
    for chunk in response.iter_content(chunk_size=None, decode_unicode=True):
        if chunk:
            full_response += chunk

    print(full_response)
    ```
  </Tab>

  <Tab title="cURL">
    ```bash theme={null}
    curl -X POST https://suite.sundaypyjamas.com/api/v1/chat \
      -H "Authorization: Bearer spj_ai_your_api_key_here" \
      -H "Content-Type: application/json" \
      -d '{"messages": [{"role": "user", "content": "Hello!"}]}'
    ```
  </Tab>
</Tabs>

## Example Applications

### Content Generation Tools

<AccordionGroup>
  <Accordion title="Blog Post Generator">
    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 →](/examples/javascript#content-generation)
    [View Python Implementation →](/examples/python#content-generation-tools)
  </Accordion>

  <Accordion title="Email Writer">
    Generate professional emails for various purposes and audiences.

    **Features:**

    * Template-based generation
    * Tone customization
    * Recipient personalization
    * Follow-up sequences

    [View Examples →](/examples/javascript#content-generation)
  </Accordion>

  <Accordion title="Marketing Copy Generator">
    Create compelling marketing copy that drives conversions.

    **Features:**

    * Audience targeting
    * A/B testing variants
    * Call-to-action optimization
    * Brand voice consistency

    [View Examples →](/examples/python#content-generation-tools)
  </Accordion>
</AccordionGroup>

### Interactive Applications

<AccordionGroup>
  <Accordion title="Chat Interface">
    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 →](/examples/javascript#chat-interface-component)
  </Accordion>

  <Accordion title="Command-Line Tools">
    Create powerful CLI applications for batch processing and automation.

    **Features:**

    * Interactive chat mode
    * Batch processing
    * Progress tracking
    * Configuration management

    [View CLI Implementation →](/examples/python#cli-tool-example)
  </Accordion>

  <Accordion title="Web Applications">
    Full-featured web applications with API integration.

    **Features:**

    * Express.js server examples
    * Authentication middleware
    * Error handling
    * Rate limiting

    [View Server Examples →](/examples/javascript#nodejs-server-example)
  </Accordion>
</AccordionGroup>

### Advanced Use Cases

<AccordionGroup>
  <Accordion title="Batch Processing">
    Process multiple requests efficiently with queue management.

    **Features:**

    * Concurrent request handling
    * Progress tracking
    * Error recovery
    * Performance optimization

    [View Implementation →](/examples/python#batch-processing)
  </Accordion>

  <Accordion title="Streaming Chat">
    Real-time streaming responses for better user experience.

    **Features:**

    * Progressive response display
    * Cancellation support
    * Error handling
    * Performance monitoring

    [View Examples →](/examples/javascript#streaming-responses)
  </Accordion>

  <Accordion title="Content Pipelines">
    Automated content generation workflows.

    **Features:**

    * Multi-step processing
    * Quality control
    * Template management
    * Output formatting

    [View Pipeline Examples →](/examples/curl#content-generation-pipeline)
  </Accordion>
</AccordionGroup>

## Implementation Features

All examples include these production-ready features:

<CardGroup cols={2}>
  <Card title="Error Handling" icon="shield-check">
    Comprehensive error handling with retry logic and graceful degradation
  </Card>

  <Card title="Authentication" icon="key">
    Secure API key management and best practices
  </Card>

  <Card title="Rate Limiting" icon="clock">
    Built-in rate limiting and usage optimization
  </Card>

  <Card title="Streaming Support" icon="bolt">
    Real-time streaming responses for better UX
  </Card>

  <Card title="TypeScript Support" icon="code">
    Full TypeScript definitions and type safety
  </Card>

  <Card title="Testing" icon="vial">
    Unit tests and integration examples
  </Card>

  <Card title="Documentation" icon="book">
    Inline documentation and usage examples
  </Card>

  <Card title="Monitoring" icon="chart-line">
    Usage tracking and performance monitoring
  </Card>
</CardGroup>

## 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

<Tabs>
  <Tab title="JavaScript/Node.js">
    ```json package.json theme={null}
    {
      "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:**

    ```bash theme={null}
    npm install
    # or
    yarn install
    ```
  </Tab>

  <Tab title="Python">
    ```txt requirements.txt theme={null}
    requests>=2.28.0
    python-dotenv>=1.0.0
    asyncio>=3.7.0
    aiohttp>=3.8.0
    click>=8.0.0
    rich>=13.0.0
    ```

    **Installation:**

    ```bash theme={null}
    pip install -r requirements.txt
    # or
    poetry install
    ```
  </Tab>

  <Tab title="Environment Variables">
    ```bash .env theme={null}
    # API Configuration
    SUNDAYPYJAMAS_API_KEY=spj_ai_your_api_key_here
    SUNDAYPYJAMAS_API_URL=https://suite.sundaypyjamas.com/api/v1

    # Optional Configuration
    MAX_RETRIES=3
    REQUEST_TIMEOUT=30
    RATE_LIMIT_PER_MINUTE=60
    ```
  </Tab>
</Tabs>

## Testing Your Setup

Verify your environment is configured correctly:

<CodeGroup>
  ```javascript test-setup.js theme={null}
  // 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();
  ```

  ```python test_setup.py theme={null}
  # test_setup.py
  import os
  import requests
  from dotenv import load_dotenv

  load_dotenv()

  API_KEY = os.getenv('SUNDAYPYJAMAS_API_KEY')
  API_URL = os.getenv('SUNDAYPYJAMAS_API_URL')

  def test_setup():
      if not API_KEY:
          print('❌ SUNDAYPYJAMAS_API_KEY not set')
          return

      try:
          response = requests.post(
              f'{API_URL}/chat',
              headers={
                  'Authorization': f'Bearer {API_KEY}',
                  'Content-Type': 'application/json'
              },
              json={
                  'messages': [{'role': 'user', 'content': 'Test connection'}]
              }
          )

          if response.ok:
              print('✅ API connection successful')
          else:
              print(f'❌ API connection failed: {response.status_code}')
      except Exception as error:
          print(f'❌ Connection error: {error}')

  if __name__ == '__main__':
      test_setup()
  ```

  ```bash test-setup.sh theme={null}
  #!/bin/bash
  # test-setup.sh

  if [ -z "$SUNDAYPYJAMAS_API_KEY" ]; then
      echo "❌ SUNDAYPYJAMAS_API_KEY not set"
      exit 1
  fi

  response=$(curl -s -w "%{http_code}" -o /dev/null \
      -X POST "$SUNDAYPYJAMAS_API_URL/chat" \
      -H "Authorization: Bearer $SUNDAYPYJAMAS_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{"messages": [{"role": "user", "content": "Test connection"}]}')

  if [ "$response" = "200" ]; then
      echo "✅ API connection successful"
  else
      echo "❌ API connection failed: HTTP $response"
  fi
  ```
</CodeGroup>

## Contributing Examples

We welcome contributions to improve and expand our examples:

<CardGroup cols={2}>
  <Card title="Submit Examples" icon="plus">
    Share your own implementations and use cases
  </Card>

  <Card title="Report Issues" icon="bug">
    Help us fix bugs and improve documentation
  </Card>

  <Card title="Request Features" icon="lightbulb">
    Suggest new examples or improvements
  </Card>

  <Card title="Join Community" icon="users">
    Connect with other developers using the API
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="JavaScript Examples" icon="js" href="/examples/javascript">
    Explore comprehensive JavaScript/TypeScript implementations
  </Card>

  <Card title="Python Examples" icon="python" href="/examples/python">
    View detailed Python examples with async support
  </Card>

  <Card title="cURL Examples" icon="terminal" href="/examples/curl">
    Command-line examples for testing and automation
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/chat/introduction">
    Complete API documentation with schemas
  </Card>
</CardGroup>

<Note>
  These examples focus on the Chat API. For Agents, RAG, Artifacts, Image, and Vector Store — see the language-specific "Beyond Chat" sections at the end of each [JavaScript](/examples/javascript#beyond-chat-other-apis), [Python](/examples/python#beyond-chat-other-apis), and [cURL](/examples/curl#beyond-chat-other-apis) guide, or jump straight to the [full API Reference](/api-reference/agents/introduction).
</Note>

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