MoonMDSMarkdown Showcase
api-guide.md

API Reference Guide

January 8, 2024
3 min read
589 words
apidocumentationreferencetechnical

API Reference Guide

This guide demonstrates how MoonMDS handles technical documentation with complex code examples.

Authentication

Bearer Token Authentication

hljs typescript
interface AuthConfig {
  token: string;
  refreshToken?: string;
  expiresAt: Date;
}

class ApiClient {
  private config: AuthConfig;
  
  constructor(config: AuthConfig) {
    this.config = config;
  }
  
  async request<T>(endpoint: string, options?: RequestInit): Promise<T> {
    const headers = {
      'Authorization': `Bearer ${this.config.token}`,
      'Content-Type': 'application/json',
      ...options?.headers,
    };
    
    const response = await fetch(endpoint, { ...options, headers });
    
    if (!response.ok) {
      throw new ApiError(response.status, await response.text());
    }
    
    return response.json();
  }
}

API Key Authentication

hljs python
import requests
from typing import Optional, Dict, Any

class APIClient:
    def __init__(self, api_key: str, base_url: str = "https://api.example.com"):
        self.api_key = api_key
        self.base_url = base_url
        self.session = requests.Session()
        self.session.headers.update({
            "X-API-Key": api_key,
            "Accept": "application/json"
        })
    
    def get(self, endpoint: str, params: Optional[Dict] = None) -> Dict[Any, Any]:
        """Make a GET request to the API."""
        response = self.session.get(f"{self.base_url}/{endpoint}", params=params)
        response.raise_for_status()
        return response.json()

Endpoints

GET /api/documents

Retrieve a list of all documents.

Request:

hljs bash
curl -X GET "https://api.example.com/documents" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Accept: application/json"

Response:

hljs json
{
  "data": [
    {
      "id": "doc_123",
      "title": "Welcome Guide",
      "slug": "welcome-guide",
      "createdAt": "2024-01-10T10:00:00Z",
      "updatedAt": "2024-01-10T15:30:00Z",
      "tags": ["welcome", "guide"],
      "readingTime": 5
    }
  ],
  "pagination": {
    "page": 1,
    "pageSize": 20,
    "totalPages": 5,
    "totalItems": 100
  }
}

POST /api/documents

Create a new document.

Request Body:

FieldTypeRequiredDescription
titlestringDocument title
contentstringMarkdown content
tagsstring[]Optional tags
publishedbooleanPublish immediately

Example:

hljs javascript
const createDocument = async (doc) => {
  const response = await fetch('/api/documents', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      title: doc.title,
      content: doc.content,
      tags: doc.tags || [],
      published: true
    })
  });
  
  if (!response.ok) {
    throw new Error(`Failed to create document: ${response.statusText}`);
  }
  
  return response.json();
};

Error Handling

Error Response Format

hljs typescript
interface ApiError {
  code: string;
  message: string;
  details?: Record<string, string[]>;
  timestamp: string;
  requestId: string;
}

Common Error Codes

CodeHTTP StatusDescription
AUTH_REQUIRED401Authentication required
AUTH_INVALID401Invalid credentials
FORBIDDEN403Insufficient permissions
NOT_FOUND404Resource not found
VALIDATION_ERROR422Invalid request data
RATE_LIMITED429Too many requests

Error Handling Example

hljs typescript
try {
  const data = await api.request('/documents');
  console.log('Documents:', data);
} catch (error) {
  if (error instanceof ApiError) {
    switch (error.code) {
      case 'AUTH_REQUIRED':
        redirectToLogin();
        break;
      case 'RATE_LIMITED':
        await delay(error.retryAfter * 1000);
        return retry();
      default:
        showErrorNotification(error.message);
    }
  }
}

Rate Limiting

The API implements rate limiting to ensure fair usage:

  • Standard tier: 100 requests/minute
  • Pro tier: 1000 requests/minute
  • Enterprise: Custom limits

Rate limit headers:

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1704892800

Webhooks

Configuring Webhooks

hljs yaml
# webhook-config.yaml
webhooks:
  - url: https://your-server.com/webhook
    events:
      - document.created
      - document.updated
      - document.deleted
    secret: whsec_your_webhook_secret
    active: true

Webhook Payload

hljs json
{
  "id": "evt_abc123",
  "type": "document.created",
  "timestamp": "2024-01-10T12:00:00Z",
  "data": {
    "document": {
      "id": "doc_xyz",
      "title": "New Document"
    }
  }
}

Verifying Webhook Signatures

hljs javascript
const crypto = require('crypto');

function verifyWebhookSignature(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('hex');
  
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(`sha256=${expectedSignature}`)
  );
}

💡 Tip: Use the interactive API explorer at /api/docs for testing endpoints directly.