# Overview

KayakNet exposes a REST API on port 8080 for programmatic access to all features.

## Base URL

```
http://127.0.0.1:8080
```

For remote access (if `--public-api` enabled):

```
http://<node-ip>:8080
```

## Authentication

Most endpoints don't require authentication - they operate on behalf of the local node.

For multi-user setups, API keys can be configured (see Configuration).

## Response Format

All responses are JSON:

```json
{
  "success": true,
  "data": { ... }
}
```

Error responses:

```json
{
  "error": "Error message"
}
```

## Endpoints Overview

| Category    | Prefix          | Description         |
| ----------- | --------------- | ------------------- |
| Network     | `/api/network/` | Node and peer info  |
| Chat        | `/api/chat/`    | Messaging           |
| Marketplace | `/api/market/`  | Listings and orders |
| Escrow      | `/api/escrow/`  | Payment management  |
| Domains     | `/api/domains/` | .kyk registration   |

## Network API

### Get Node Info

```
GET /api/network/info
```

Response:

```json
{
  "node_id": "abc123...",
  "name": "my-node",
  "version": "v0.1.28",
  "uptime": 3600,
  "peer_count": 12
}
```

### List Peers

```
GET /api/network/peers
```

Response:

```json
{
  "peers": [
    {
      "id": "peer1...",
      "name": "peer-name",
      "address": "1.2.3.4:4242",
      "latency_ms": 45,
      "connected_at": "2026-01-15T10:00:00Z"
    }
  ]
}
```

### Get Statistics

```
GET /api/network/stats
```

Response:

```json
{
  "messages_sent": 1234,
  "messages_received": 5678,
  "bytes_sent": 1048576,
  "bytes_received": 2097152,
  "circuits_created": 42,
  "dht_records": 256
}
```

## Chat API

### List Rooms

```
GET /api/chat/rooms
```

### Join Room

```
POST /api/chat/join
{
  "room": "#general"
}
```

### Send Message (Room)

```
POST /api/chat/send
{
  "room": "#general",
  "content": "Hello world!"
}
```

### Send Direct Message

```
POST /api/chat/dm
{
  "recipient": "node_id",
  "content": "Private message"
}
```

### Get History

```
GET /api/chat/history?room=#general&limit=50
```

## Marketplace API

### List Listings

```
GET /api/market/listings?category=all&sort=newest&page=1
```

### Get Listing

```
GET /api/market/listing?id=abc123
```

### Create Listing

```
POST /api/market/create
{
  "title": "Product Name",
  "description": "Product description",
  "category": "digital",
  "price": 99.99,
  "currency": "XMR",
  "seller_xmr_address": "44zFk...",
  "stock": 10,
  "ships_from": "US",
  "ships_to": ["US", "EU"],
  "images": ["data:image/png;base64,..."]
}
```

### Update Listing

```
POST /api/market/update
{
  "id": "abc123",
  "price": 89.99,
  "stock": 5
}
```

### Delete Listing

```
POST /api/market/delete
{
  "id": "abc123"
}
```

### Search

```
GET /api/market/search?q=keyword&category=digital&min_price=10&max_price=100
```

## Escrow API

### Create Escrow

```
POST /api/escrow/create
{
  "listing_id": "abc123",
  "currency": "XMR",
  "buyer_address": "44zFk...",
  "delivery_info": "encrypted delivery details"
}
```

Response:

```json
{
  "success": true,
  "escrow_id": "esc123",
  "order_id": "ord456",
  "payment_address": "escrow_address...",
  "amount": 0.5,
  "currency": "XMR",
  "expires_at": "2026-01-16T10:00:00Z"
}
```

### Get Status

```
GET /api/escrow/status?id=esc123
```

### Mark Shipped

```
POST /api/escrow/ship
{
  "escrow_id": "esc123",
  "tracking_info": "TRACK123"
}
```

### Confirm Receipt

```
POST /api/escrow/release
{
  "escrow_id": "esc123"
}
```

### Open Dispute

```
POST /api/escrow/dispute
{
  "escrow_id": "esc123",
  "reason": "Item not received",
  "description": "Details..."
}
```

### My Orders

```
GET /api/escrow/my?type=buying
GET /api/escrow/my?type=selling
```

## Domain API

### Register

```
POST /api/domains/register
{
  "domain": "mysite.kyk",
  "target": "node_id:abc123"
}
```

### Lookup

```
GET /api/domains/lookup?domain=mysite.kyk
```

### Update

```
POST /api/domains/update
{
  "domain": "mysite.kyk",
  "target": "new_target"
}
```

### My Domains

```
GET /api/domains/mine
```

## Error Codes

| Code | Meaning                          |
| ---- | -------------------------------- |
| 200  | Success                          |
| 400  | Bad Request (invalid parameters) |
| 401  | Unauthorized                     |
| 403  | Forbidden                        |
| 404  | Not Found                        |
| 429  | Rate Limited                     |
| 500  | Internal Server Error            |
| 503  | Service Unavailable              |

## Rate Limits

| Endpoint        | Limit       |
| --------------- | ----------- |
| General         | 100 req/min |
| Chat Send       | 30 req/min  |
| Escrow Create   | 10 req/min  |
| Domain Register | 5 req/min   |

## WebSocket API

Real-time updates via WebSocket:

```javascript
const ws = new WebSocket('ws://127.0.0.1:8080/ws');

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log(data.type, data.payload);
};
```

### Event Types

| Type                | Description         |
| ------------------- | ------------------- |
| `chat.message`      | New chat message    |
| `chat.dm`           | New direct message  |
| `market.listing`    | New/updated listing |
| `escrow.update`     | Escrow state change |
| `peer.connected`    | New peer connected  |
| `peer.disconnected` | Peer disconnected   |

## SDK Examples

### Python

```python
import requests

class KayakNet:
    def __init__(self, base_url='http://127.0.0.1:8080'):
        self.base = base_url
    
    def get_info(self):
        return requests.get(f'{self.base}/api/network/info').json()
    
    def send_message(self, room, content):
        return requests.post(f'{self.base}/api/chat/send', 
            data={'room': room, 'content': content}).json()

kn = KayakNet()
print(kn.get_info())
```

### JavaScript

```javascript
class KayakNet {
  constructor(baseUrl = 'http://127.0.0.1:8080') {
    this.base = baseUrl;
  }

  async getInfo() {
    const res = await fetch(`${this.base}/api/network/info`);
    return res.json();
  }

  async sendMessage(room, content) {
    const res = await fetch(`${this.base}/api/chat/send`, {
      method: 'POST',
      body: new URLSearchParams({ room, content })
    });
    return res.json();
  }
}
```
