Code Examples

Practical, copy-paste examples for every DocForge endpoint. Each example includes curl, JavaScript, and Python snippets.

Markdown to HTML CSV to HTML Table JSON to HTML Batch Conversion CI/CD Integration TXT to HTML
1

Markdown to HTML

Convert a README.md or any Markdown content into clean, styled HTML. The response includes word count and extracted headings for building a table of contents.

curl -X POST https://docforge-api.vercel.app/api/md-to-html \
  -H "Content-Type: application/json" \
  -H "X-Api-Key: YOUR_API_KEY" \
  -d '{
    "markdown": "# Project Setup\n\nInstall dependencies:\n\n```bash\nnpm install\n```\n\n## Features\n\n- **Fast** conversion\n- *Sanitized* output\n- Code block support"
  }'
const res = await fetch('https://docforge-api.vercel.app/api/md-to-html', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-Api-Key': 'YOUR_API_KEY'
  },
  body: JSON.stringify({
    markdown: `# Project Setup

Install dependencies:

\`\`\`bash
npm install
\`\`\`

## Features

- **Fast** conversion
- *Sanitized* output
- Code block support`
  })
});

const { html, meta } = await res.json();
console.log('Word count:', meta.wordCount);
console.log('Headings:', meta.headings);
import requests

response = requests.post(
    "https://docforge-api.vercel.app/api/md-to-html",
    headers={
        "Content-Type": "application/json",
        "X-Api-Key": "YOUR_API_KEY"
    },
    json={
        "markdown": "# Project Setup\n\nInstall dependencies:\n\n```bash\nnpm install\n```\n\n## Features\n\n- **Fast** conversion\n- *Sanitized* output\n- Code block support"
    }
)

data = response.json()
print("HTML:", data["html"][:100])
print("Headings:", data["meta"]["headings"])
Sample Response
{
  "html": "<h1>Project Setup</h1>\n<p>Install dependencies:</p>\n<pre><code class=\"language-bash\">npm install</code></pre>...",
  "meta": {
    "wordCount": 12,
    "headings": ["Project Setup", "Features"]
  }
}
2

CSV to HTML Table

Convert raw CSV sales data into a structured JSON array, then use the data to render an HTML table. This two-step approach gives you full control over table styling.

curl -X POST https://docforge-api.vercel.app/api/csv-to-json \
  -H "Content-Type: application/json" \
  -d '{
    "csv": "product,units_sold,revenue\nWidget Pro,1250,$62500\nGadget Plus,890,$44500\nMega Pack,340,$51000\nStarter Kit,2100,$42000"
  }'
// Step 1: Parse CSV to JSON
const res = await fetch('https://docforge-api.vercel.app/api/csv-to-json', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    csv: `product,units_sold,revenue
Widget Pro,1250,$62500
Gadget Plus,890,$44500
Mega Pack,340,$51000
Starter Kit,2100,$42000`
  })
});

const { data, meta } = await res.json();

// Step 2: Build an HTML table
const headers = meta.columns.map(c => `<th>${c}</th>`).join('');
const rows = data.map(row =>
  `<tr>${meta.columns.map(c => `<td>${row[c]}</td>`).join('')}</tr>`
).join('\n');

const table = `<table><thead><tr>${headers}</tr></thead><tbody>${rows}</tbody></table>`;
console.log(table);
import requests

response = requests.post(
    "https://docforge-api.vercel.app/api/csv-to-json",
    headers={"Content-Type": "application/json"},
    json={
        "csv": "product,units_sold,revenue\nWidget Pro,1250,$62500\nGadget Plus,890,$44500\nMega Pack,340,$51000\nStarter Kit,2100,$42000"
    }
)

data = response.json()
columns = data["meta"]["columns"]
rows = data["data"]

# Build HTML table
header = "".join(f"<th>{c}</th>" for c in columns)
body = "".join(
    f"<tr>{''.join(f'<td>{row[c]}</td>' for c in columns)}</tr>"
    for row in rows
)
print(f"<table><thead><tr>{header}</tr></thead><tbody>{body}</tbody></table>")
Parsed JSON Response
{
  "data": [
    { "product": "Widget Pro", "units_sold": "1250", "revenue": "$62500" },
    { "product": "Gadget Plus", "units_sold": "890", "revenue": "$44500" }
  ],
  "meta": { "rowCount": 4, "columns": ["product", "units_sold", "revenue"] }
}
3

JSON to HTML

Take structured JSON data from an API response and convert it to CSV, then render it as a formatted Markdown document. Useful for generating human-readable summaries from API data.

# Step 1: Convert JSON array to CSV
curl -X POST https://docforge-api.vercel.app/api/json-to-csv \
  -H "Content-Type: application/json" \
  -d '{
    "data": [
      {"name": "Alice", "role": "Engineer", "status": "Active"},
      {"name": "Bob", "role": "Designer", "status": "Active"},
      {"name": "Charlie", "role": "PM", "status": "On Leave"}
    ]
  }'

# Step 2: Render the CSV as Markdown and convert to HTML
curl -X POST https://docforge-api.vercel.app/api/md-to-html \
  -H "Content-Type: application/json" \
  -d '{
    "markdown": "# Team Directory\n\n| Name | Role | Status |\n|------|------|--------|\n| Alice | Engineer | Active |\n| Bob | Designer | Active |\n| Charlie | PM | On Leave |"
  }'
const BASE = 'https://docforge-api.vercel.app';

// Step 1: Convert JSON to CSV
const csvRes = await fetch(`${BASE}/api/json-to-csv`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    data: [
      { name: 'Alice', role: 'Engineer', status: 'Active' },
      { name: 'Bob', role: 'Designer', status: 'Active' },
      { name: 'Charlie', role: 'PM', status: 'On Leave' }
    ]
  })
});
const { csv } = await csvRes.json();

// Step 2: Build Markdown table and convert to HTML
const mdTable = `# Team Directory\n\n` + csv;
const htmlRes = await fetch(`${BASE}/api/md-to-html`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ markdown: mdTable })
});
const { html } = await htmlRes.json();
console.log(html);
import requests

BASE = "https://docforge-api.vercel.app"

# Step 1: Convert JSON to CSV
csv_res = requests.post(f"{BASE}/api/json-to-csv", json={
    "data": [
        {"name": "Alice", "role": "Engineer", "status": "Active"},
        {"name": "Bob", "role": "Designer", "status": "Active"},
        {"name": "Charlie", "role": "PM", "status": "On Leave"}
    ]
})
csv_text = csv_res.json()["csv"]

# Step 2: Build Markdown table and convert to HTML
md = f"# Team Directory\n\n{csv_text}"
html_res = requests.post(f"{BASE}/api/md-to-html", json={"markdown": md})
print(html_res.json()["html"])
JSON to CSV Response
{
  "csv": "name,role,status\nAlice,Engineer,Active\nBob,Designer,Active\nCharlie,PM,On Leave",
  "meta": { "rowCount": 3, "columns": ["name", "role", "status"] }
}
4

Batch Conversion

Convert multiple Markdown files to HTML in a loop. This Node.js script reads all .md files from a directory and writes the converted HTML output alongside each source file.

import { readdir, readFile, writeFile } from 'node:fs/promises';
import { join, basename } from 'node:path';

const API = 'https://docforge-api.vercel.app/api/md-to-html';
const DIR = './docs';

const files = (await readdir(DIR)).filter(f => f.endsWith('.md'));

for (const file of files) {
  const md = await readFile(join(DIR, file), 'utf-8');

  const res = await fetch(API, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Api-Key': process.env.DOCFORGE_KEY
    },
    body: JSON.stringify({ markdown: md })
  });

  const { html } = await res.json();
  const outName = basename(file, '.md') + '.html';
  await writeFile(join(DIR, outName), html);
  console.log(`Converted ${file} -> ${outName}`);
}
import os, requests

API = "https://docforge-api.vercel.app/api/md-to-html"
DIR = "./docs"
HEADERS = {
    "Content-Type": "application/json",
    "X-Api-Key": os.environ["DOCFORGE_KEY"]
}

for filename in os.listdir(DIR):
    if not filename.endswith(".md"):
        continue

    with open(os.path.join(DIR, filename)) as f:
        md = f.read()

    res = requests.post(API, headers=HEADERS, json={"markdown": md})
    html = res.json()["html"]

    out_name = filename.replace(".md", ".html")
    with open(os.path.join(DIR, out_name), "w") as f:
        f.write(html)
    print(f"Converted {filename} -> {out_name}")
#!/bin/bash
# Convert all .md files in ./docs to HTML

for file in ./docs/*.md; do
  content=$(cat "$file" | jq -Rs .)
  outfile="${file%.md}.html"

  curl -s -X POST https://docforge-api.vercel.app/api/md-to-html \
    -H "Content-Type: application/json" \
    -H "X-Api-Key: $DOCFORGE_KEY" \
    -d "{\"markdown\": $content}" \
    | jq -r '.html' > "$outfile"

  echo "Converted $file -> $outfile"
done
5

CI/CD Integration

Auto-generate HTML documentation from Markdown files in a GitHub Actions workflow. The converted docs are committed back to the repo on every push to main.

# .github/workflows/docs.yml
name: Generate HTML Docs
on:
  push:
    branches: [main]
    paths: ['docs/**/*.md']

jobs:
  build-docs:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Convert Markdown to HTML
        run: |
          for file in docs/*.md; do
            content=$(cat "$file" | jq -Rs .)
            outfile="public/${file##*/}"
            outfile="${outfile%.md}.html"
            curl -s -X POST https://docforge-api.vercel.app/api/md-to-html \
              -H "Content-Type: application/json" \
              -H "X-Api-Key: ${{ secrets.DOCFORGE_KEY }}" \
              -d "{\"markdown\": $content}" \
              | jq -r '.html' > "$outfile"
          done

      - name: Commit generated docs
        run: |
          git config user.name "github-actions"
          git config user.email "actions@github.com"
          git add public/
          git diff --staged --quiet || git commit -m "docs: auto-generate HTML"
          git push
// scripts/generate-docs.mjs — run in CI with: node scripts/generate-docs.mjs
import { readdir, readFile, writeFile, mkdir } from 'node:fs/promises';
import { join, basename } from 'node:path';

const API = 'https://docforge-api.vercel.app/api/md-to-html';
const SRC = './docs';
const OUT = './public';

await mkdir(OUT, { recursive: true });

const files = (await readdir(SRC)).filter(f => f.endsWith('.md'));

for (const file of files) {
  const md = await readFile(join(SRC, file), 'utf-8');
  const res = await fetch(API, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Api-Key': process.env.DOCFORGE_KEY
    },
    body: JSON.stringify({ markdown: md })
  });
  const { html } = await res.json();
  await writeFile(join(OUT, basename(file, '.md') + '.html'), html);
}
console.log(`Generated ${files.length} HTML files`);
# scripts/generate_docs.py — run in CI with: python scripts/generate_docs.py
import os, requests
from pathlib import Path

API = "https://docforge-api.vercel.app/api/md-to-html"
SRC = Path("./docs")
OUT = Path("./public")
OUT.mkdir(exist_ok=True)

headers = {
    "Content-Type": "application/json",
    "X-Api-Key": os.environ["DOCFORGE_KEY"]
}

for md_file in SRC.glob("*.md"):
    res = requests.post(API, headers=headers, json={
        "markdown": md_file.read_text()
    })
    out_file = OUT / md_file.stem + ".html"
    out_file.write_text(res.json()["html"])

print(f"Generated {len(list(SRC.glob('*.md')))} HTML files")
6

TXT to HTML

Convert plain text content (like email bodies or log files) to formatted HTML by treating it as Markdown. Line breaks and basic formatting are preserved.

curl -X POST https://docforge-api.vercel.app/api/md-to-html \
  -H "Content-Type: application/json" \
  -d '{
    "markdown": "Dear Team,\n\nPlease review the Q1 budget proposal attached.\n\nKey highlights:\n- Total budget: $240,000\n- Engineering: $150,000\n- Marketing: $60,000\n- Operations: $30,000\n\nDeadline for feedback: March 15, 2026.\n\nBest regards,\nFinance Department"
  }'
// Convert a plain text email to formatted HTML
const plainText = `Dear Team,

Please review the Q1 budget proposal attached.

Key highlights:
- Total budget: $240,000
- Engineering: $150,000
- Marketing: $60,000
- Operations: $30,000

Deadline for feedback: March 15, 2026.

Best regards,
Finance Department`;

const res = await fetch('https://docforge-api.vercel.app/api/md-to-html', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ markdown: plainText })
});

const { html } = await res.json();
// html now contains <p> tags, a <ul> list, and proper formatting
document.getElementById('email-preview').innerHTML = html;
import requests

plain_text = """Dear Team,

Please review the Q1 budget proposal attached.

Key highlights:
- Total budget: $240,000
- Engineering: $150,000
- Marketing: $60,000
- Operations: $30,000

Deadline for feedback: March 15, 2026.

Best regards,
Finance Department"""

response = requests.post(
    "https://docforge-api.vercel.app/api/md-to-html",
    json={"markdown": plain_text}
)

html = response.json()["html"]
# Save to file for email template use
with open("email.html", "w") as f:
    f.write(html)
print("Saved formatted email to email.html")
Sample Response
{
  "html": "<p>Dear Team,</p>\n<p>Please review the Q1 budget proposal attached.</p>\n<p>Key highlights:</p>\n<ul>\n<li>Total budget: $240,000</li>...",
  "meta": {
    "wordCount": 35,
    "headings": []
  }
}