# How to Integrate Fabric's REST API into Your Application

> Seamlessly integrate Fabric's REST API into your app. Launch the HTTP server with fabric --serve and access OpenAPI endpoints at localhost:8080. Secure with X-API-Key for robust integration.

- Repository: [Daniel Miessler 🛡️/fabric](https://github.com/danielmiessler/fabric)
- Tags: how-to-guide
- Published: 2026-02-28

---

**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`](https://github.com/danielmiessler/fabric/blob/main//swagger/index.html).

```bash
fabric --serve

```

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

```bash
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`](https://github.com/danielmiessler/fabric/blob/main/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:

- **[`internal/server/serve.go`](https://github.com/danielmiessler/fabric/blob/main/internal/server/serve.go)** – Bootstraps the Gin engine, registers middleware, and serves the Swagger UI.
- **[`internal/server/chat.go`](https://github.com/danielmiessler/fabric/blob/main/internal/server/chat.go)** – Implements the `/chat` endpoint that streams AI responses via SSE. The `ChatRequest` schema is defined at lines 37‑41.
- **[`internal/server/patterns.go`](https://github.com/danielmiessler/fabric/blob/main/internal/server/patterns.go)** – CRUD operations for pattern resources stored in `~/.config/fabric/patterns`.
- **[`internal/server/contexts.go`](https://github.com/danielmiessler/fabric/blob/main/internal/server/contexts.go)** – Management of context snippets.
- **[`internal/server/sessions.go`](https://github.com/danielmiessler/fabric/blob/main/internal/server/sessions.go)** – Session persistence and retrieval.
- **[`internal/server/youtube.go`](https://github.com/danielmiessler/fabric/blob/main/internal/server/youtube.go)** – YouTube transcript extraction endpoint defined at lines 66‑70.
- **[`internal/server/config.go`](https://github.com/danielmiessler/fabric/blob/main/internal/server/config.go)** – Reads and writes the `.env` configuration file.
- **[`docs/swagger.yaml`](https://github.com/danielmiessler/fabric/blob/main/docs/swagger.yaml)** – OpenAPI specification generated at build time.

## 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`](https://github.com/danielmiessler/fabric/blob/main/internal/server/chat.go)):

```json
{
  "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**:

```python
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**:

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

```

**Create or update a pattern**:

```bash
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**:

```javascript
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**:

```bash
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):

```bash
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`](https://github.com/danielmiessler/fabric/blob/main/internal/server/youtube.go).

### Model Discovery

Retrieve the catalog of available models and vendors:

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

```

Response structure:

```json
{
  "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`](https://github.com/danielmiessler/fabric/blob/main/internal/server/models.go).

## Authentication and Security

When the server is launched with `--api-key`, the Gin middleware registered in [`internal/server/serve.go`](https://github.com/danielmiessler/fabric/blob/main/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:

```bash
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`](https://github.com/danielmiessler/fabric/blob/main/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`](https://github.com/danielmiessler/fabric/blob/main/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.