How to Integrate Fabric's REST API into Your Application

You can integrate Fabric's REST API by launching the built-in HTTP server with fabric --serve and consuming the OpenAPI-compliant endpoints at http://localhost:8080, optionally securing requests with an X-API-Key header.

The danielmiessler/fabric repository provides a built-in HTTP server that exposes all core functionality—chat completions, pattern management, and YouTube transcript extraction—through a clean REST API. By integrating Fabric's REST API into your application, you can programmatically access AI models and reusable prompts without invoking the CLI directly.

Starting the Fabric HTTP Server

Launch the server using the --serve flag. By default, it binds to port 8080 and exposes an interactive Swagger UI at /swagger/index.html.

fabric --serve

For production deployments, specify a custom address and enable authentication:

fabric --serve --address :9090 --api-key my_secret_key

When --api-key is provided, every request must include the X-API-Key header. The middleware enforcing this is registered in internal/server/serve.go at lines 36‑38.

Core API Architecture and Key Components

The server uses Gin for HTTP routing, Server‑Sent Events (SSE) for streaming chat responses, and permissive CORS configured for local development. The following source files define the endpoint logic:

Essential Endpoints for Application Integration

Streaming Chat Completions

The /chat endpoint accepts a ChatRequest JSON body containing an array of PromptRequest objects. Each prompt specifies userInput, vendor, model, and optionally a patternName.

Request structure (as defined in internal/server/chat.go):

{
  "prompts": [
    {
      "userInput": "Explain quantum computing",
      "vendor": "openai",
      "model": "gpt-5.2",
      "patternName": "explain"
    }
  ],
  "language": "en",
  "temperature": 0.7,
  "topP": 0.9
}

The response streams as SSE events (text/readystream). Each line starts with data: followed by a JSON object containing a type field (content, usage, error, complete) and a format field (markdown, mermaid, plain).

Python example with authentication:

import requests
import json

API_BASE = "http://localhost:8080"
API_KEY = "my_secret_key"

headers = {
    "Content-Type": "application/json",
    "X-API-Key": API_KEY,
    "Accept": "text/event-stream"
}

payload = {
    "prompts": [{
        "userInput": "Summarize the latest AI news",
        "vendor": "openai",
        "model": "gpt-5-mini",
        "patternName": "summarize"
    }],
    "language": "en"
}

response = requests.post(f"{API_BASE}/chat", headers=headers, json=payload, stream=True)

for line in response.iter_lines():
    if line:
        event = json.loads(line.decode().removeprefix("data: ").strip())
        print(event.get("content") or event)

Pattern Management

Patterns are reusable system prompts stored on disk. The API exposes CRUD operations via /patterns/names (list) and /patterns/{name} (create, read, update, delete). Patterns are stored as plain text files in ~/.config/fabric/patterns, and the API accepts text/plain bodies when creating or updating content.

List available patterns:

curl http://localhost:8080/patterns/names | jq .

Create or update a pattern:

curl -X POST http://localhost:8080/patterns/my_custom_pattern \
  -H "Content-Type: text/plain" \
  -d "You are an expert in explaining complex topics simply..."

Node.js example:

const fetch = require('node-fetch');

const API_BASE = 'http://localhost:8080';

// List patterns
fetch(`${API_BASE}/patterns/names`)
  .then(res => res.json())
  .then(data => console.log('Available patterns:', data));

// Upload pattern
fetch(`${API_BASE}/patterns/custom_analyzer`, {
  method: 'POST',
  headers: { 'Content-Type': 'text/plain' },
  body: 'Analyze the following text for sentiment...',
})
  .then(res => res.text())
  .then(text => console.log('Upload result:', text));

YouTube Transcript Extraction

The /youtube/transcript endpoint extracts video transcripts for downstream processing.

Request:

curl -X POST http://localhost:8080/youtube/transcript \
  -H "Content-Type: application/json" \
  -d '{"url":"https://youtube.com/watch?v=dQw4w9WgXcQ","timestamps":false}'

Bash pipeline (extract then summarize):

API_BASE="http://localhost:8080"

TRANSCRIPT=$(curl -s -X POST "$API_BASE/youtube/transcript" \
  -H "Content-Type: application/json" \
  -d '{"url":"https://youtube.com/watch?v=EXAMPLE","timestamps":false}' | jq -r '.transcript')

curl -s -X POST "$API_BASE/chat" \
  -H "Content-Type: application/json" \
  -d "$(jq -n --arg txt "$TRANSCRIPT" '{
    prompts: [{userInput:$txt, vendor:"openai", model:"gpt-5.2", patternName:"youtube_summary"}],
    language:"en"
  }')" | jq -r '.content'

Source: YouTube endpoint implementation at lines 66‑70 of internal/server/youtube.go.

Model Discovery

Retrieve the catalog of available models and vendors:

curl http://localhost:8080/models/names | jq .

Response structure:

{
  "models": ["gpt-5.2","gpt-5-mini","claude-sonnet-4.5"],
  "vendors": {
    "openai": ["gpt-5.2","gpt-5-mini"],
    "anthropic": ["claude-sonnet-4.5"]
  }
}

Source: NewModelsHandler registers GET /models/names in internal/server/models.go.

Authentication and Security

When the server is launched with --api-key, the Gin middleware registered in internal/server/serve.go (lines 36‑38) validates the X-API-Key header on every request. If the header is missing or invalid, the server returns 401 Unauthorized.

For production deployments:

  • Run behind a reverse proxy (nginx, Caddy) to add TLS and rate limiting.
  • Configure CORS restrictions; the default configuration permits http://localhost:5173 for local development.
  • Persist configuration by mounting the Fabric config directory when using Docker:
docker run -d -p 8080:8080 \
  -v $HOME/.fabric-config:/root/.config/fabric \
  kayvan/fabric:latest --serve --api-key $FABRIC_API_KEY

Source: Docker deployment guidance from docs/rest-api.md lines 423‑445.

Error Handling Conventions

The API returns standard HTTP status codes with JSON error bodies:

Status Meaning
200 OK Successful request; body contains JSON or SSE stream
400 Bad Request Malformed JSON or missing required fields
401 Unauthorized API key missing or invalid (when enabled)
404 Not Found Resource (pattern, context, session) does not exist
500 Internal Server Error Unexpected server-side failure

Error responses follow the schema { "error": "human readable message" }.

Summary

  • Launch the Fabric HTTP server with fabric --serve to expose the REST API on port 8080 by default.
  • Authenticate requests using the X-API-Key header when the server is started with --api-key.
  • Stream chat completions via Server-Sent Events from the /chat endpoint, sending a ChatRequest with prompts, vendor, and model parameters.
  • Manage reusable system prompts through /patterns/names and /patterns/{name} endpoints that map to on-disk storage.
  • Extract YouTube transcripts via /youtube/transcript and chain them into chat workflows for automated summarization.

Frequently Asked Questions

What port does Fabric's REST API use by default?

By default, the Fabric server listens on port 8080. You can specify a custom port using the --address flag, for example: fabric --serve --address :9090.

How do I enable authentication on the Fabric server?

Start the server with the --api-key flag followed by your secret key: fabric --serve --api-key my_secret_key. Clients must then include the X-API-Key header in every request. The validation logic is implemented in internal/server/serve.go at lines 36‑38.

Can I use the REST API to manage custom patterns?

Yes. The API exposes full CRUD operations for patterns at /patterns/names (to list) and /patterns/{name} (to create, read, update, or delete). Patterns are stored as plain text files in ~/.config/fabric/patterns, and the API accepts text/plain bodies when uploading content.

How do I handle streaming responses from the chat endpoint?

The /chat endpoint returns Server-Sent Events (SSE) with the content type text/readystream. Each line begins with data: followed by a JSON object containing type (content, usage, error, complete) and format (markdown, mermaid, plain). Consume these streams using an SSE client or by iterating over response lines and parsing the JSON fragments as they arrive.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →