npm package: @matteuccimarco/slim-api
Description: Express/Fastify middleware for automatic SLIM API response compression
Author: Marco Matteucci
Latest version: 0.1.0

# @anthropic/slim-api

Express/Fastify middleware for automatic SLIM API response compression. Reduce API bandwidth by 40-50% with zero code changes.

## Installation

```bash
npm install @anthropic/slim-api
```

## Quick Start

### Express

```typescript
import express from 'express';
import { slimMiddleware } from '@anthropic/slim-api/express';

const app = express();

// Add SLIM middleware
app.use(slimMiddleware());

// Your existing routes - no changes needed!
app.get('/api/users', (req, res) => {
  res.json({ users: [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }] });
  // If client sends Accept: application/slim
  // Response is SLIM-encoded automatically
});

app.listen(3000);
```

### Fastify

```typescript
import Fastify from 'fastify';
import { slimPlugin } from '@anthropic/slim-api/fastify';

const app = Fastify();

// Register SLIM plugin
app.register(slimPlugin);

// Your existing routes
app.get('/api/users', async () => {
  return { users: [{ id: 1, name: 'Alice' }] };
});

app.listen({ port: 3000 });
```

### Client

```typescript
import { SlimClient } from '@anthropic/slim-api/client';

const client = new SlimClient('https://api.example.com');

// Automatically requests SLIM, decodes response
const { data, isSlim, compressionRatio } = await client.get('/api/users');

console.log(data); // { users: [...] }
console.log(isSlim); // true
console.log(compressionRatio); // 42.5
```

## How It Works

### Content Negotiation

```
Client Request:
  Accept: application/slim, application/json

Server Response (if client accepts SLIM):
  Content-Type: application/slim
  X-Original-Size: 1250
  X-Slim-Size: 780
  X-Compression-Ratio: 37.6

  {users:|2|id#,name,active?|1,Alice,T|2,Bob,F}

Server Response (fallback for non-SLIM clients):
  Content-Type: application/json

  {"users":[{"id":1,"name":"Alice","active":true},{"id":2,"name":"Bob","active":false}]}
```

## Middleware Options

```typescript
app.use(slimMiddleware({
  // Only SLIM responses larger than threshold (bytes)
  threshold: 1024,  // default: 0

  // Skip certain paths
  skip: (req) => req.path.startsWith('/static'),

  // Force SLIM regardless of Accept header
  force: false,  // default: false

  // Add compression stats headers
  includeStats: true,  // default: true

  // Custom MIME type
  mimeType: 'application/slim',  // default
}));
```

## Client Options

```typescript
const client = new SlimClient({
  baseUrl: 'https://api.example.com',

  // Fallback to JSON if SLIM fails
  fallbackToJson: true,  // default: true

  // Request timeout (ms)
  timeout: 5000,  // default: 30000

  // Custom headers
  headers: { 'Authorization': 'Bearer ...' },

  // Prefer JSON over SLIM
  preferJson: false,  // default: false
});
```

## API Reference

### Express

```typescript
import { slimMiddleware, slimBodyParser } from '@anthropic/slim-api/express';

// Response encoding
app.use(slimMiddleware(options));

// Request body parsing (for SLIM request bodies)
app.use(slimBodyParser());
```

### Fastify

```typescript
import { slimPlugin } from '@anthropic/slim-api/fastify';

app.register(slimPlugin, options);
```

### Client

```typescript
import { SlimClient, createSlimFetch, slimFetch } from '@anthropic/slim-api/client';

// Class-based client
const client = new SlimClient('https://api.example.com');
await client.get('/users');
await client.post('/users', { body: { name: 'Alice' } });
await client.put('/users/1', { body: { name: 'Updated' } });
await client.patch('/users/1', { body: { active: false } });
await client.delete('/users/1');

// Factory function
const fetch = createSlimFetch({ baseUrl: 'https://api.example.com' });
await fetch('/users');

// Standalone function
import { slimFetch } from '@anthropic/slim-api/client';
await slimFetch('https://api.example.com/users');
```

## Response Object

```typescript
interface SlimResponse<T> {
  data: T;                    // Decoded response data
  headers: Headers;           // Response headers
  status: number;             // HTTP status code
  isSlim: boolean;            // Was response SLIM-encoded?
  originalSize?: number;      // Original JSON size (bytes)
  slimSize?: number;          // SLIM size (bytes)
  compressionRatio?: number;  // Compression percentage
}
```

## Benchmarks

| Response Type | JSON Size | SLIM Size | Savings |
|---------------|-----------|-----------|---------|
| User list (10) | 2.5 KB | 1.5 KB | 40% |
| Product catalog | 15 KB | 8 KB | 47% |
| Dashboard data | 50 KB | 28 KB | 44% |
| Paginated list | 100 KB | 55 KB | 45% |

## Use Cases

- **Mobile APIs**: Reduce bandwidth for mobile apps
- **Real-time dashboards**: Faster data updates
- **Microservices**: Internal service communication
- **Public APIs**: Optional SLIM support for bandwidth-conscious clients
- **AI/LLM APIs**: Reduce token usage when passing API data to LLMs

## Browser Support

The client works in all modern browsers that support `fetch`. For older browsers, use a fetch polyfill.

## License

MIT