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

# API Playground

> Interactive testing environment for HITL.sh API endpoints. Test API calls directly in your browser with live responses and code generation.

> [!NOTE]
>
> **Live API Testing**: The playground below connects to the real HITL.sh API. Use your actual API key to test endpoints and see live responses.

## Quick Test Setup

**1. Get Your API Key**

Sign up at [HITL.sh](https://hitl.sh) and generate an API key from your dashboard.

**2. Set Your API Key**

Enter your API key in the playground below. It's stored locally in your browser and never sent to our documentation servers.

**3. Test Endpoints**

Select any endpoint from the dropdown and customize the request parameters.

**4. View Results**

See live responses and generated code examples in multiple programming languages.

## Interactive API Explorer

[HITL.sh API Playground](https://api-playground.hitl.sh)

> [!NOTE]
>
> The API playground above is embedded from our interactive testing environment. If you don't see it loading, you can [open it in a new tab](https://api-playground.hitl.sh).

## Playground Features

> [card] Live Testing
>
> Test real API endpoints with your actual API key and see live responses.

> [card] Code Generation
>
> Automatically generate code examples in Python, JavaScript, cURL, and more.

> [card] Request Builder
>
> Visual request builder with parameter validation and documentation.

> [card] Response Inspector
>
> Detailed response inspection with syntax highlighting and formatting.

## Manual Testing Examples

If you prefer to test manually, here are some quick examples:

### Test Authentication

```bash cURL theme={null}
# Test your API key with a simple request
curl -X GET https://api.hitl.sh/v1/api/loops \
  -H "Authorization: Bearer your_api_key_here"
```

```python Python theme={null}
import requests

# Test API connection
response = requests.get(
    "https://api.hitl.sh/v1/api/loops",
    headers={"Authorization": "Bearer your_api_key_here"}
)

print(f"Status: {response.status_code}")
print(f"Response: {response.json()}")
```

```javascript JavaScript theme={null}
const response = await fetch('https://api.hitl.sh/v1/api/loops', {
  headers: {
    'Authorization': 'Bearer your_api_key_here'
  }
});

const data = await response.json();
console.log('Status:', response.status);
console.log('Response:', data);
```

### Quick Loop Creation Test

```bash cURL theme={null}
# Create a test loop
curl -X POST https://api.hitl.sh/v1/api/loops \
  -H "Authorization: Bearer your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Test Loop from Playground",
    "description": "Testing API integration",
    "icon": "🧪"
  }'
```

```python Python theme={null}
import requests

# Create test loop
response = requests.post(
    "https://api.hitl.sh/v1/api/loops",
    headers={
        "Authorization": "Bearer your_api_key_here",
        "Content-Type": "application/json"
    },
    json={
        "name": "Test Loop from Playground",
        "description": "Testing API integration",
        "icon": "🧪"
    }
)

print(f"Loop created: {response.json()}")
```

```javascript JavaScript theme={null}
const response = await fetch('https://api.hitl.sh/v1/api/loops', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer your_api_key_here',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Test Loop from Playground',
    description: 'Testing API integration',
    icon: '🧪'
  })
});

const loop = await response.json();
console.log('Loop created:', loop);
```

### Test Request Creation

```bash cURL theme={null}
# Create a test request (replace loop_id with actual ID)
curl -X POST https://api.hitl.sh/v1/api/requests \
  -H "Authorization: Bearer your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "loop_id": "your_loop_id_here",
    "request_text": "Please review: Is this API documentation helpful?",
    "response_type": "single_select",
    "response_config": {
      "options": ["Very helpful", "Somewhat helpful", "Not helpful"]
    },
    "priority": "medium",
    "processing_type": "deferred"
  }'
```

```python Python theme={null}
# Create test request
response = requests.post(
    "https://api.hitl.sh/v1/api/requests",
    headers={
        "Authorization": "Bearer your_api_key_here",
        "Content-Type": "application/json"
    },
    json={
        "loop_id": "your_loop_id_here",
        "request_text": "Please review: Is this API documentation helpful?",
        "response_type": "single_select",
        "response_config": {
            "options": ["Very helpful", "Somewhat helpful", "Not helpful"]
        },
        "priority": "medium",
        "processing_type": "deferred"
    }
)

print(f"Request created: {response.json()}")
```

```javascript JavaScript theme={null}
const response = await fetch('https://api.hitl.sh/v1/api/requests', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer your_api_key_here',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    loop_id: 'your_loop_id_here',
    request_text: 'Please review: Is this API documentation helpful?',
    response_type: 'single_select',
    response_config: {
      options: ['Very helpful', 'Somewhat helpful', 'Not helpful']
    },
    priority: 'medium',
    processing_type: 'deferred'
  })
});

const request = await response.json();
console.log('Request created:', request);
```

## Testing Workflows

### Complete Integration Test

Test the full workflow from loop creation to request completion:

```python theme={null}
import requests
import time

class HITLIntegrationTest:
    def __init__(self, api_key):
        self.api_key = api_key
        self.headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
        self.base_url = "https://api.hitl.sh/v1"
        
    def run_complete_test(self):
        """Run complete integration test"""
        print("🧪 Starting HITL.sh Integration Test...")
        
        # Step 1: Create a test loop
        loop = self.create_test_loop()
        if not loop:
            return False
        
        loop_id = loop['data']['loop']['id']
        print(f"✅ Loop created: {loop_id}")
        
        # Step 2: Create a test request
        request = self.create_test_request(loop_id)
        if not request:
            return False
        
        request_id = request['data']['request']['id']
        print(f"✅ Request created: {request_id}")
        
        # Step 3: Monitor request status
        self.monitor_request(request_id)
        
        # Step 4: Cleanup (optional)
        # self.cleanup_test_data(loop_id)
        
        print("🎉 Integration test completed successfully!")
        return True
    
    def create_test_loop(self):
        """Create a test loop"""
        response = requests.post(f"{self.base_url}/loops", headers=self.headers, json={
            "name": f"Integration Test {int(time.time())}",
            "description": "Automated integration test loop",
            "icon": "🧪"
        })
        
        if response.status_code == 201:
            return response.json()
        else:
            print(f"❌ Failed to create loop: {response.text}")
            return None
    
    def create_test_request(self, loop_id):
        """Create a test request"""
        response = requests.post(f"{self.base_url}/requests", headers=self.headers, json={
            "loop_id": loop_id,
            "request_text": "Integration Test: Please confirm this request is working correctly.",
            "response_type": "single_select",
            "response_config": {
                "options": ["Working correctly", "Has issues", "Needs investigation"]
            },
            "priority": "high",
            "processing_type": "time-sensitive"
        })
        
        if response.status_code == 201:
            return response.json()
        else:
            print(f"❌ Failed to create request: {response.text}")
            return None
    
    def monitor_request(self, request_id):
        """Monitor request until completion or timeout"""
        max_checks = 20
        check_interval = 30  # seconds
        
        for i in range(max_checks):
            response = requests.get(
                f"{self.base_url}/requests/{request_id}", 
                headers={"Authorization": f"Bearer {self.api_key}"}
            )
            
            if response.status_code == 200:
                request_data = response.json()['data']['request']
                status = request_data['status']
                
                print(f"📊 Request status: {status}")
                
                if status == 'completed':
                    response_data = request_data.get('response_data')
                    print(f"✅ Request completed with response: {response_data}")
                    return True
                elif status in ['cancelled', 'timeout']:
                    print(f"⚠️ Request ended with status: {status}")
                    return False
            
            time.sleep(check_interval)
        
        print("⏰ Monitoring timeout - request may still be pending")
        return False

# Usage
# tester = HITLIntegrationTest('your_api_key_here')
# tester.run_complete_test()
```

## Environment Testing

### Development vs Production

> [tab] Development
>
> ```python theme={null}
> # Development environment testing
> HITL_API_BASE = "https://api.hitl.sh/v1"  # Development server
> API_KEY = "dev_your_api_key_here"
>
> # Use smaller timeouts and test data
> TEST_CONFIG = {
>     "timeout_minutes": 5,
>     "test_loops": ["Test Loop Dev"],
>     "cleanup_after_test": True
> }
> ```

> [tab] Production
>
> ```python theme={null}
> # Production environment testing
> HITL_API_BASE = "https://api.hitl.sh/v1"  # Production server
> API_KEY = "prod_your_api_key_here"
>
> # Use production timeouts and real data
> PROD_CONFIG = {
>     "timeout_minutes": 60,
>     "test_loops": [],  # No test data in production
>     "cleanup_after_test": False
> }
> ```

## Rate Limit Testing

Test your application's handling of rate limits:

```python theme={null}
def test_rate_limits(api_key):
    """Test rate limit behavior"""
    headers = {"Authorization": f"Bearer {api_key}"}
    
    # Make rapid requests to trigger rate limiting
    for i in range(105):  # Exceed 100/hour limit
        response = requests.get("https://api.hitl.sh/v1/api/loops", headers=headers)
        
        if response.status_code == 429:
            print(f"🚫 Rate limit hit after {i+1} requests")
            print(f"Response: {response.json()}")
            break
        elif response.status_code != 200:
            print(f"❌ Unexpected error: {response.status_code}")
            break
        else:
            print(f"✅ Request {i+1} successful")
    
    return i

# test_rate_limits('your_api_key_here')
```

## Advanced Testing Scenarios

### Webhook Testing

Test webhook delivery and processing:

```python theme={null}
import threading
from flask import Flask, request
import requests

class WebhookTester:
    def __init__(self, webhook_url, webhook_secret):
        self.webhook_url = webhook_url
        self.webhook_secret = webhook_secret
        self.received_events = []
        
    def start_webhook_server(self, port=5000):
        """Start local webhook server for testing"""
        app = Flask(__name__)
        
        @app.route('/webhook', methods=['POST'])
        def handle_webhook():
            # Store received webhook for testing
            self.received_events.append({
                'headers': dict(request.headers),
                'body': request.json,
                'timestamp': time.time()
            })
            return {'status': 'received'}
        
        app.run(port=port, debug=False)
    
    def trigger_webhook_event(self, api_key):
        """Create a request to trigger webhook events"""
        # This would create a request that triggers webhooks
        # when it gets claimed/completed
        pass
    
    def verify_webhook_received(self, event_type, timeout=60):
        """Wait for and verify specific webhook event"""
        start_time = time.time()
        
        while time.time() - start_time < timeout:
            for event in self.received_events:
                if event['body']['event'] == event_type:
                    return event
            time.sleep(1)
        
        return None

# Usage:
# tester = WebhookTester('http://localhost:5000/webhook', 'secret')
# threading.Thread(target=tester.start_webhook_server).start()
# event = tester.verify_webhook_received('request.completed', timeout=120)
```

## Performance Testing

### Load Testing Example

```python theme={null}
import concurrent.futures
import time

def load_test_api(api_key, num_requests=50, max_workers=10):
    """Simple load test for API endpoints"""
    
    def make_request(request_num):
        headers = {"Authorization": f"Bearer {api_key}"}
        start_time = time.time()
        
        try:
            response = requests.get("https://api.hitl.sh/v1/api/loops", headers=headers)
            end_time = time.time()
            
            return {
                'request_num': request_num,
                'status_code': response.status_code,
                'response_time': end_time - start_time,
                'success': response.status_code == 200
            }
        except Exception as e:
            return {
                'request_num': request_num,
                'error': str(e),
                'success': False
            }
    
    # Execute load test
    with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
        futures = [executor.submit(make_request, i) for i in range(num_requests)]
        results = [future.result() for future in concurrent.futures.as_completed(futures)]
    
    # Analyze results
    successful_requests = [r for r in results if r['success']]
    failed_requests = [r for r in results if not r['success']]
    
    if successful_requests:
        avg_response_time = sum(r['response_time'] for r in successful_requests) / len(successful_requests)
    else:
        avg_response_time = 0
    
    print(f"Load Test Results:")
    print(f"  Total requests: {num_requests}")
    print(f"  Successful: {len(successful_requests)}")
    print(f"  Failed: {len(failed_requests)}")
    print(f"  Success rate: {len(successful_requests)/num_requests*100:.1f}%")
    print(f"  Average response time: {avg_response_time:.3f}s")
    
    return results

# load_test_api('your_api_key_here', num_requests=25, max_workers=5)
```

## Next Steps

> [card] [SDK Examples](https://docs.hitl.sh/sdks.md)
>
> Explore our official SDKs and community libraries for easier integration.

> [card] [Quickstart Tutorial](https://docs.hitl.sh/quickstart.md)
>
> Follow our step-by-step tutorial to build your first HITL application.

> [card] [Webhooks](https://docs.hitl.sh/api-reference/webhooks.md)
>
> Set up real-time notifications for your application events.

> [card] [Best Practices](https://docs.hitl.sh/guides/simple-integration.md)
>
> Learn optimization techniques and common patterns for production use.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.