# 🔗 API Reference

Dynamic CSS generation API for Anthropic Fonts CDN.

## Overview

The Anthropic Fonts API generates custom CSS on-demand based on query parameters. Load only the fonts and weights you need.

---

## Base URL

```
https://cdn.jsdelivr.net/gh/devchauhann/fonts@v1.1.0/cdn/api
```

For local development:
```
http://localhost:3000/api
```

---

## Endpoints

### GET /css

Generate dynamic CSS for specified fonts and weights.

#### Parameters

| Parameter | Type | Required | Example | Description |
|-----------|------|----------|---------|-------------|
| `family` | string | Yes | `AnthropicSans` | Font family name |
| `weights` | string | Yes | `400;700` | Semicolon-separated weights |

#### Font Families

- `AnthropicSans` (or `sans`)
- `AnthropicSerif` (or `serif`)
- `AnthropicMono` (or `mono`)

#### Valid Weights

- `AnthropicSans`: 300, 400, 500, 600, 700, 800, 900
- `AnthropicSerif`: 300, 400, 500, 600, 700, 800, 900
- `AnthropicMono`: 400

#### Examples

##### Basic Request

```bash
curl "https://cdn.jsdelivr.net/gh/devchauhann/fonts@v1.1.0/cdn/api/css?family=AnthropicSans&weights=400;700"
```

##### Multiple Weights

```bash
curl "https://cdn.jsdelivr.net/gh/devchauhann/fonts@v1.1.0/cdn/api/css?family=AnthropicSans&weights=300;400;500;700"
```

##### Serif Font

```bash
curl "https://cdn.jsdelivr.net/gh/devchauhann/fonts@v1.1.0/cdn/api/css?family=AnthropicSerif&weights=400;700"
```

##### Short Name

```bash
curl "https://cdn.jsdelivr.net/gh/devchauhann/fonts@v1.1.0/cdn/api/css?family=sans&weights=400"
```

---

## Response Format

### Success Response (200)

**Content-Type:** `text/css; charset=utf-8`

```css
/* Anthropic Fonts - Dynamic CSS API */
/* Family: Anthropic Sans, Weights: 400,700 */
/* Generated: 2026-04-01T12:00:00.000Z */

@font-face {
  font-family: 'Anthropic Sans';
  src: url('/v1/fonts/AnthropicSans@400.woff2') format('woff2');
  font-weight: 400;
  font-style: normal;
  font-display: swap;
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, ...;
}

@font-face {
  font-family: 'Anthropic Sans';
  src: url('/v1/fonts/AnthropicSans@700.woff2') format('woff2');
  font-weight: 700;
  font-style: normal;
  font-display: swap;
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, ...;
}
```

### Error Responses

#### 400 - Bad Request

```json
{
  "error": "Font not found",
  "available": ["AnthropicSans", "AnthropicSerif", "AnthropicMono"]
}
```

#### 400 - Invalid Weights

```json
{
  "error": "Invalid weights parameter"
}
```

#### 500 - Server Error

```json
{
  "error": "Internal server error"
}
```

---

## Caching

All responses are cached aggressively:

```
Cache-Control: public, max-age=31536000, immutable
```

This caches CSS for **1 year** safely because:
- URLs are versioned in the CDN path
- Query parameters are permanent
- Content never changes

---

## Usage Examples

### HTML

```html
<link rel="stylesheet" 
  href="https://cdn.jsdelivr.net/gh/devchauhann/fonts@v1.1.0/cdn/api/css?family=AnthropicSans&weights=400;700">
```

### CSS

```css
@import url('https://cdn.jsdelivr.net/gh/devchauhann/fonts@v1.1.0/cdn/api/css?family=AnthropicSans&weights=400;700');

body {
  font-family: 'Anthropic Sans', sans-serif;
}
```

### JavaScript

```javascript
const fontUrl = new URL('https://cdn.jsdelivr.net/gh/devchauhann/fonts@v1.1.0/cdn/api/css');
fontUrl.searchParams.set('family', 'AnthropicSans');
fontUrl.searchParams.set('weights', '400;700');

const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = fontUrl.toString();
document.head.appendChild(link);
```

### React

```jsx
export function FontLoader() {
  useEffect(() => {
    const params = new URLSearchParams({
      family: 'AnthropicSans',
      weights: '400;700'
    });
    
    const link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = `https://cdn.jsdelivr.net/gh/devchauhann/fonts@v1.1.0/cdn/api/css?${params}`;
    document.head.appendChild(link);
  }, []);

  return <h1 style={{ fontFamily: 'Anthropic Sans' }}>Hello</h1>;
}
```

---

## Alternative Endpoint: /fonts

Legacy format endpoint (maps to `/css`):

```bash
# Query format: FontName@weight1;weight2
curl "https://cdn.jsdelivr.net/gh/devchauhann/fonts@v1.1.0/cdn/api/fonts?query=AnthropicSans@400;700"
```

---

## Metadata Endpoint

### GET /v1/metadata

Get font family information and available variants.

**Response:**

```json
{
  "version": "1.0.0",
  "updated": "2026-04-01T06:04:30.100Z",
  "fonts": [
    {
      "family": "Anthropic Sans",
      "category": "sans-serif",
      "variants": [
        {
          "weight": 300,
          "style": "normal",
          "file": "AnthropicSans@300.woff2",
          "unicodeRanges": {
            "latin": "U+0000-00FF, ...",
            "latin-ext": "U+0100-024F, ..."
          }
        },
        ...
      ],
      "unicodeRange": "U+0000-00FF, U+0131, ..."
    },
    ...
  ]
}
```

**Usage:**

```javascript
fetch('https://cdn.jsdelivr.net/gh/devchauhann/fonts@v1.1.0/cdn/v1/metadata')
  .then(r => r.json())
  .then(meta => {
    console.log('Available fonts:', meta.fonts);
  });
```

---

## Static Endpoints

### All Fonts CSS

```
GET /v1/css/all.css
```

Includes all font families and weights.

### Individual Font CSS

```
GET /v1/css/anthropicsans.css
GET /v1/css/anthropicserif.css
GET /v1/css/anthropicmono.css
```

Individual font family CSS files.

### Minified CSS

```
GET /v1/css/all.min.css
```

Minified version of all.css (saves ~60%).

### Font Files

```
GET /v1/fonts/AnthropicSans@400.woff2
GET /v1/fonts/AnthropicSans@700.woff2
GET /v1/fonts/AnthropicSerif@400.woff2
... (all weights available)
```

---

## Health Check

### GET /health

Check if API is running.

**Response:**

```json
{
  "status": "ok",
  "timestamp": "2026-04-01T12:00:00.000Z"
}
```

---

## Performance Tips

### 1. Load Only Needed Weights

```html
<!-- ❌ Load all (5.63 KB) -->
<link rel="stylesheet" href="...all.css">

<!-- ✅ Load specific (1.5 KB) -->
<link rel="stylesheet" href="...api/css?family=AnthropicSans&weights=400;700">
```

### 2. Use Preconnect

```html
<link rel="preconnect" href="https://cdn.jsdelivr.net">
<link rel="stylesheet" href="...api/css?family=AnthropicSans&weights=400">
```

### 3. Cache Aggressively

Responses include `immutable` cache header - safe to cache forever.

### 4. Combine with Preload

```html
<link rel="preload" as="font" type="font/woff2"
  href="https://cdn.jsdelivr.net/gh/devchauhann/fonts@v1.1.0/cdn/v1/fonts/AnthropicSans@400.woff2"
  crossorigin>

<link rel="stylesheet" 
  href="https://cdn.jsdelivr.net/gh/devchauhann/fonts@v1.1.0/cdn/api/css?family=AnthropicSans&weights=400">
```

---

## API Conventions

### URL Format

```
https://cdn.jsdelivr.net/gh/devchauhann/fonts@v1.1.0/cdn/api/css
  ?family=AnthropicSans      ← Font family
  &weights=400;700            ← Semicolon-separated weights
```

### Allowed Characters

- Font names: Alphanumeric (AnthropicSans, sans, serif)
- Weights: Numbers 100-900 separated by semicolons (300;400;700)

### Query Parameter Validation

- Missing `family`: Returns 400 error
- Invalid `family`: Returns 400 with available list
- Invalid `weights`: Returns 400 error
- Missing `weights`: Defaults to 400

---

## Rate Limiting

The API respects jsDelivr's rate limits:

- **Per IP:** 1000 requests per hour
- **Per file:** 5000 requests per minute

For most use cases, static CDN URLs are cached, so minimal requests.

---

## CORS Headers

All API responses include:

```
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, OPTIONS
Access-Control-Allow-Headers: Content-Type
```

Safe for cross-origin requests from any domain.

---

## Content Negotiation

### Content-Type

API responds with appropriate content types:

- **CSS endpoint:** `text/css; charset=utf-8`
- **JSON endpoints:** `application/json`
- **Font files:** `application/font-woff2`

### Accept Header

The API ignores Accept headers and serves based on endpoint:

```bash
# Always returns CSS regardless of Accept header
GET /api/css?family=AnthropicSans&weights=400

# Always returns JSON
GET /v1/metadata
```

---

## Versioning

API versions in CDN path:

```
/v1/css/...        ← Version 1 CSS
/v1/fonts/...      ← Version 1 fonts
/api/css?...       ← Latest API
```

To lock to specific version, use Git tags:

```
https://cdn.jsdelivr.net/gh/devchauhann/fonts@v1.0.0/cdn/api/css?...
```

---

## Changelog

### v1.0.0 (Current)

- ✅ Dynamic CSS generation
- ✅ Multiple weights support
- ✅ All three font families (Sans, Serif, Mono)
- ✅ Metadata endpoint
- ✅ CORS support
- ✅ Aggressive caching

### Planned Features

- [ ] Font subsetting by character range
- [ ] Italic style support
- [ ] Variable font format (single file, any weight)
- [ ] WebP image format for fallback
- [ ] Usage analytics

---

## Support & Issues

Report issues or request features:
- GitHub Issues: https://github.com/devchauhann/fonts/issues
- Documentation: See [USAGE.md](./USAGE.md) and [PERFORMANCE.md](./PERFORMANCE.md)

---

## License

API and fonts are provided as-is. See [LICENSE](../LICENSE) file.
