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

# Development

> Development resources and guides for building with PulseGuard API

# Development Resources

This guide provides developers with comprehensive resources for building integrations and custom solutions with PulseGuard.

## Getting Started

### Prerequisites

* Valid PulseGuard account with [Expert Plan](/resources/subscription-plans) for API access
* API token generated from your dashboard
* Basic understanding of REST APIs and HTTP requests

### Authentication

All API requests require authentication using a Bearer token:

```bash theme={null}
curl -H "Authorization: Bearer YOUR_API_TOKEN" \
  https://api.ipulse.one/domains
```

## Quick Start Examples

### Domain Monitoring

#### Create a Domain Monitor

```javascript theme={null}
const response = await fetch('https://api.ipulse.one/domains', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_TOKEN',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'My Website',
    url: 'https://example.com',
    check_interval: 5
  })
});

const domain = await response.json();
console.log('Created domain:', domain.data);
```

#### Get Domain Statistics

```python theme={null}
import requests

response = requests.get(
    'https://api.ipulse.one/stats/domains/DOMAIN-UUID/response-time/stats',
    headers={'Authorization': 'Bearer YOUR_API_TOKEN'},
    params={'period': '24h'}
)

stats = response.json()
print(f"Average response time: {stats['data']['average_response_time']}ms")
print(f"Uptime percentage: {stats['data']['uptime_percentage']}%")
```

#### PHP Domain Management

```php theme={null}
<?php
$client = new \GuzzleHttp\Client();

$response = $client->get('https://api.ipulse.one/domains', [
    'headers' => [
        'Authorization' => 'Bearer ' . $apiToken,
        'Accept' => 'application/json'
    ]
]);

$domains = json_decode($response->getBody(), true);
foreach ($domains['data'] as $domain) {
    echo "Domain: {$domain['name']} - Status: {$domain['status']}\n";
}
?>
```

### Device Management

#### Register a Device

```bash theme={null}
curl -X POST https://api.ipulse.one/devices \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Production Server",
    "hostname": "server01.example.com",
    "description": "Main production server"
  }'
```

#### Get Device Metrics

```javascript theme={null}
const getDeviceMetrics = async (deviceUuid) => {
  const response = await fetch(`https://api.ipulse.one/devices/${deviceUuid}`, {
    headers: {
      'Authorization': 'Bearer YOUR_API_TOKEN'
    }
  });
  
  const device = await response.json();
  return {
    status: device.data.status,
    cpu: device.data.metrics?.cpu_usage,
    memory: device.data.metrics?.memory_usage,
    disk: device.data.metrics?.disk_usage
  };
};
```

### Service Monitoring

#### Create HTTP Service Monitor

```python theme={null}
import requests

service_data = {
    "name": "API Health Check",
    "type": "http",
    "url": "https://api.example.com/health",
    "check_interval": 5,
    "timeout": 30
}

response = requests.post(
    'https://api.ipulse.one/services',
    headers={'Authorization': 'Bearer YOUR_API_TOKEN'},
    json=service_data
)

service = response.json()
print(f"Created service monitor: {service['data']['uuid']}")
```

#### Manual Service Check

```bash theme={null}
curl -X POST https://api.ipulse.one/services/SERVICE-UUID/check \
  -H "Authorization: Bearer YOUR_API_TOKEN"
```

### Toolbox Utilities

#### DNS Lookup

```javascript theme={null}
const dnsLookup = async (domain, recordType = 'A') => {
  const response = await fetch('https://api.ipulse.one/toolbox/dns-lookup', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_TOKEN',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      domain: domain,
      record_type: recordType
    })
  });
  
  return await response.json();
};

// Usage
const result = await dnsLookup('example.com', 'MX');
console.log('DNS records:', result.data.records);
```

#### DNS Lookup (Python)

```python theme={null}
import requests

response = requests.post(
    'https://api.ipulse.one/toolbox/dns-lookup',
    headers={'Authorization': 'Bearer YOUR_API_TOKEN'},
    json={'domain': 'example.com', 'record_type': 'A'}
)

dns_records = response.json()
print(f"DNS Records: {dns_records}")
```

#### Port Scanning

```bash theme={null}
curl -X POST https://api.ipulse.one/toolbox/port-scan \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "host": "example.com",
    "ports": "80,443,22-25"
  }'
```

### Chat Conversations

PulseGuard ondersteunt chat conversaties voor AI integratie:

```javascript theme={null}
// Save a conversation
const saveConversation = async (conversationData) => {
  const response = await fetch('https://api.ipulse.one/chat/conversations', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_TOKEN',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(conversationData)
  });

  return await response.json();
};
```

## Advanced Integration Patterns

### Webhook Integration

Set up webhooks to receive real-time notifications:

```javascript theme={null}
// Express.js webhook handler
app.post('/pulseguard-webhook', (req, res) => {
  const event = req.body;
  
  switch (event.type) {
    case 'domain.down':
      console.log(`Alert: ${event.data.domain} is down!`);
      // Send Slack notification, SMS, etc.
      break;
    case 'anomaly.detected':
      console.log(`Anomaly detected on ${event.data.domain}`);
      // Trigger automated investigation
      break;
  }
  
  res.status(200).send('OK');
});
```

### Batch Operations

Efficiently manage multiple resources:

```python theme={null}
import asyncio
import aiohttp

async def batch_check_domains(domains):
    async with aiohttp.ClientSession() as session:
        tasks = []
        for domain_uuid in domains:
            task = check_domain_status(session, domain_uuid)
            tasks.append(task)
        
        results = await asyncio.gather(*tasks)
        return results

async def check_domain_status(session, domain_uuid):
    async with session.get(
        f'https://api.ipulse.one/domains/{domain_uuid}',
        headers={'Authorization': 'Bearer YOUR_API_TOKEN'}
    ) as response:
        data = await response.json()
        return {
            'uuid': domain_uuid,
            'status': data['data']['status'],
            'response_time': data['data']['response_time']
        }
```

### Error Handling & Retry Logic

```python theme={null}
import time
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

def create_api_client():
    session = requests.Session()
    
    # Configure retry strategy
    retry_strategy = Retry(
        total=3,
        status_forcelist=[429, 500, 502, 503, 504],
        method_whitelist=["HEAD", "GET", "OPTIONS"],
        backoff_factor=1
    )
    
    adapter = HTTPAdapter(max_retries=retry_strategy)
    session.mount("http://", adapter)
    session.mount("https://", adapter)
    
    session.headers.update({
        'Authorization': 'Bearer YOUR_API_TOKEN',
        'Content-Type': 'application/json',
        'User-Agent': 'MyApp/1.0'
    })
    
    return session

# Usage with proper error handling
def safe_api_call(client, url):
    try:
        response = client.get(url, timeout=30)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.HTTPError as e:
        if e.response.status_code == 401:
            print("Authentication failed. Check your API token.")
        elif e.response.status_code == 403:
            print("Access denied. Expert Plan required.")
        else:
            print(f"HTTP error: {e}")
    except requests.exceptions.RequestException as e:
        print(f"Request failed: {e}")
    
    return None
```

## Migration Guide

### Migrating from Legacy API (v2)

The legacy v2 endpoints are deprecated. Here's how to migrate:

#### Domain Endpoints

```diff theme={null}
- GET /api/v2/domains
+ GET /api/v2/domains

- POST /api/v2/domains
+ POST /api/v2/domains

- GET /api/v2/domains/{uuid}
+ GET /api/v2/domains/{uuid}
```

#### Service Monitor Endpoints

```diff theme={null}
- GET /api/v2/service-monitors
+ GET /api/v2/services

- POST /api/v2/service-monitors
+ POST /api/v2/services
```

#### Device Management Endpoints

```diff theme={null}
- GET /api/v2/device-monitoring
+ GET /api/v2/devices

- POST /api/v2/device-monitoring
+ POST /api/v2/devices
```

### Breaking Changes in v2.0

* Response format standardization
* Enhanced authentication requirements
* New rate limiting policies
* Deprecated fields removal

## Best Practices

### Security

1. **Store API tokens securely** - Use environment variables or secure key management
2. **Validate SSL certificates** - Always verify HTTPS connections
3. **Implement proper error handling** - Don't expose sensitive information in logs
4. **Use HTTPS only** - Never send API tokens over unencrypted connections

### Performance

1. **Implement caching** - Cache frequently accessed data locally
2. **Use pagination** - For large datasets, use page parameters
3. **Batch requests** - Combine multiple operations when possible
4. **Respect rate limits** - Implement exponential backoff

### Monitoring

1. **Log API usage** - Track your integration's API calls
2. **Monitor response times** - Set up alerts for slow API responses
3. **Health checks** - Regularly verify your integration is working
4. **Version tracking** - Stay updated with API changes

## SDKs & Libraries

### Official SDKs (Coming Soon)

* PHP SDK with Laravel integration
* Python SDK with async support
* Node.js SDK with TypeScript
* Go SDK for high-performance applications

### Community Libraries

Check our [GitHub organization](https://github.com/PulseGuardHQ) for community-maintained libraries and examples.

## Support & Resources

* **API Documentation**: Interactive playground available in this documentation
* **Status Page**: [status.ipulse.one](https://status.ipulse.one)
* **GitHub Issues**: [Report bugs and feature requests](https://github.com/PulseGuardHQ/feedback)
* **Email Support**: [info@ipulse.one](mailto:info@ipulse.one)
* **Discord Community**: [Join our developer community](https://discord.gg/pulseguard)

## Rate Limits

| Plan   | Requests/Minute | Requests/Hour | Requests/Day |
| ------ | --------------- | ------------- | ------------ |
| Expert | 1,000           | 10,000        | 100,000      |
| Pro    | 300             | 3,000         | 30,000       |
| Free   | 100             | 1,000         | 10,000       |

Rate limit headers are included in all responses:

* `X-RateLimit-Limit`: Request limit per window
* `X-RateLimit-Remaining`: Remaining requests in current window
* `X-RateLimit-Reset`: Time when the rate limit resets

***

Need help getting started? Contact our support team at [info@pulseguard.nl](mailto:info@pulseguard.nl)
