Skip to content

Widget API Reference

The Widget API allows you to create, manage, and deploy custom React components that can be dynamically rendered in peer conversations.

Base URL

https://api.cognipeer.com/api/v1/widget

Authentication

All API requests require authentication:

bash
Authorization: Bearer YOUR_API_KEY

Permissions

  • WIDGETS_USE_BASIC: Can use widgets in peers
  • WIDGETS_MANAGE: Can create and edit widgets

Widgets

Create Widget

Create a new custom widget.

http
POST /api/v1/widget

Request Body:

json
{
  "key": "sales-dashboard",
  "name": "Sales Dashboard",
  "description": "Interactive sales performance dashboard with charts and metrics",
  "category": "analytics",
  "tags": ["sales", "analytics", "dashboard"],
  "schema": {
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "properties": {
      "revenue": {
        "type": "number",
        "description": "Total revenue"
      },
      "deals": {
        "type": "array",
        "items": {
          "type": "object",
          "properties": {
            "id": { "type": "string" },
            "value": { "type": "number" },
            "status": { "type": "string" }
          }
        }
      }
    },
    "required": ["revenue", "deals"]
  },
  "component": "function SalesDashboard({ data }) {\n  const { revenue, deals } = data;\n  \n  return (\n    <div>\n      <h2>Revenue: ${revenue}</h2>\n      <ul>\n        {deals.map(deal => (\n          <li key={deal.id}>\n            {deal.value} - {deal.status}\n          </li>\n        ))}\n      </ul>\n    </div>\n  );\n}\n\nexport default SalesDashboard;"
}

Response:

json
{
  "success": true,
  "data": {
    "id": "widget_abc123",
    "key": "sales-dashboard",
    "name": "Sales Dashboard",
    "description": "Interactive sales performance dashboard...",
    "category": "analytics",
    "tags": ["sales", "analytics", "dashboard"],
    "schema": { /* ... */ },
    "component": "/* React component code */",
    "createdAt": "2025-10-20T10:00:00Z",
    "updatedAt": "2025-10-20T10:00:00Z",
    "createdBy": "user_xyz789"
  }
}

List Widgets

Get all available widgets.

http
GET /api/v1/widget?page=1&limit=20&category=analytics&search=sales

Query Parameters:

ParameterTypeDescription
pagenumberPage number (default: 1)
limitnumberResults per page (default: 20, max: 100)
categorystringFilter by category
searchstringSearch in name, description, tags
tagsstringComma-separated tags to filter

Response:

json
{
  "success": true,
  "data": {
    "widgets": [
      {
        "id": "widget_abc123",
        "key": "sales-dashboard",
        "name": "Sales Dashboard",
        "description": "Interactive sales performance dashboard...",
        "category": "analytics",
        "tags": ["sales", "analytics"],
        "createdAt": "2025-10-20T10:00:00Z"
      }
    ],
    "pagination": {
      "page": 1,
      "limit": 20,
      "total": 15,
      "pages": 1
    }
  }
}

Get Widget

Retrieve a specific widget by ID.

http
GET /api/v1/widget/:widgetId

Response:

json
{
  "success": true,
  "data": {
    "id": "widget_abc123",
    "key": "sales-dashboard",
    "name": "Sales Dashboard",
    "description": "Interactive sales performance dashboard...",
    "category": "analytics",
    "tags": ["sales", "analytics"],
    "schema": {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "object",
      "properties": { /* ... */ }
    },
    "component": "/* Full React component code */",
    "createdAt": "2025-10-20T10:00:00Z",
    "updatedAt": "2025-10-20T10:00:00Z",
    "createdBy": "user_xyz789",
    "usageCount": 5
  }
}

Update Widget

Update an existing widget.

http
PUT /api/v1/widget/:widgetId

Request Body:

json
{
  "name": "Updated Widget Name",
  "description": "Updated description",
  "component": "/* Updated React component code */",
  "schema": { /* Updated schema */ }
}

Response:

json
{
  "success": true,
  "data": {
    "id": "widget_abc123",
    "name": "Updated Widget Name",
    /* ... updated fields ... */
    "updatedAt": "2025-10-20T11:00:00Z"
  }
}

Delete Widget

Delete a widget.

http
DELETE /api/v1/widget/:widgetId

Response:

json
{
  "success": true,
  "message": "Widget deleted successfully"
}

Note: Cannot delete widgets that are currently in use by peers.

Validate Widget

Validate widget schema and component code without saving.

http
POST /api/v1/widget/validate

Request Body:

json
{
  "schema": { /* JSON Schema */ },
  "component": "/* React component code */"
}

Response:

json
{
  "success": true,
  "data": {
    "valid": true,
    "schemaValid": true,
    "componentValid": true,
    "errors": [],
    "warnings": [
      "Component uses inline styles which may not be optimal"
    ]
  }
}

Peer Widgets

Add Widget to Peer

Enable a widget for a specific peer.

http
POST /api/v1/peer/:peerId/widgets

Request Body:

json
{
  "widgetId": "widget_abc123",
  "enabled": true,
  "config": {
    "defaultProps": {
      "theme": "dark"
    },
    "allowCustomData": true
  }
}

Response:

json
{
  "success": true,
  "data": {
    "id": "peer_widget_xyz",
    "peerId": "peer_123",
    "widgetId": "widget_abc123",
    "enabled": true,
    "config": { /* ... */ },
    "addedAt": "2025-10-20T10:30:00Z"
  }
}

List Peer Widgets

Get all widgets enabled for a peer.

http
GET /api/v1/peer/:peerId/widgets

Response:

json
{
  "success": true,
  "data": {
    "widgets": [
      {
        "id": "peer_widget_xyz",
        "widgetId": "widget_abc123",
        "widgetKey": "sales-dashboard",
        "widgetName": "Sales Dashboard",
        "enabled": true,
        "config": { /* ... */ },
        "addedAt": "2025-10-20T10:30:00Z"
      }
    ]
  }
}

Update Peer Widget

Update widget configuration for a peer.

http
PUT /api/v1/peer/:peerId/widgets/:peerWidgetId

Request Body:

json
{
  "enabled": false,
  "config": {
    "defaultProps": {
      "theme": "light"
    }
  }
}

Remove Widget from Peer

Remove a widget from a peer.

http
DELETE /api/v1/peer/:peerId/widgets/:peerWidgetId

Sending Widgets in Messages

Send Widget Message

Send a message with embedded widget data.

http
POST /api/v1/conversation/:conversationId/message

Request Body:

json
{
  "type": "widget",
  "widgetKey": "sales-dashboard",
  "data": {
    "revenue": 125000,
    "deals": [
      {
        "id": "deal_1",
        "value": 25000,
        "status": "closed-won"
      },
      {
        "id": "deal_2",
        "value": 50000,
        "status": "negotiation"
      }
    ]
  },
  "text": "Here's your sales dashboard for this quarter."
}

Response:

json
{
  "success": true,
  "data": {
    "messageId": "msg_456",
    "conversationId": "conv_789",
    "type": "widget",
    "widgetKey": "sales-dashboard",
    "data": { /* validated widget data */ },
    "text": "Here's your sales dashboard for this quarter.",
    "timestamp": "2025-10-20T11:00:00Z"
  }
}

Validation: Widget data is automatically validated against the widget's JSON schema.

Widget Categories

Available categories for organizing widgets:

  • analytics - Charts, dashboards, metrics
  • productivity - Tasks, calendars, project management
  • sales - CRM, pipeline, forecasting
  • customer-service - Tickets, support metrics
  • finance - Invoices, payments, reports
  • general - Miscellaneous widgets

Pre-built Widgets

Get Pre-built Widget

Access system-provided widgets.

http
GET /api/v1/widget/prebuilt/:widgetKey

Available Pre-built Widgets:

  • sales-funnel-progress
  • shopping-cart-summary
  • skills-comparison-radar
  • support-ticket-overview
  • task-kanban
  • user-growth-line-chart
  • weather-daily-highlight

Response:

json
{
  "success": true,
  "data": {
    "key": "sales-funnel-progress",
    "name": "Sales Funnel Progress",
    "description": "Displays sales pipeline stages with conversion rates",
    "schema": { /* ... */ },
    "component": "/* ... */",
    "exampleData": {
      "stages": [
        {
          "name": "Leads",
          "count": 1500,
          "value": "$150,000",
          "conversionRate": 0.25
        }
      ]
    }
  }
}

Error Responses

Validation Error

json
{
  "success": false,
  "error": "Widget validation failed",
  "details": {
    "schemaErrors": [
      {
        "field": "schema.properties",
        "message": "Required field 'type' is missing"
      }
    ],
    "componentErrors": [
      {
        "line": 5,
        "message": "Syntax error: Unexpected token"
      }
    ]
  }
}

Widget In Use

json
{
  "success": false,
  "error": "Cannot delete widget",
  "details": {
    "reason": "Widget is currently used by 3 peers",
    "peers": ["peer_123", "peer_456", "peer_789"]
  }
}

Invalid Data

json
{
  "success": false,
  "error": "Widget data validation failed",
  "details": {
    "widgetKey": "sales-dashboard",
    "errors": [
      {
        "field": "data.revenue",
        "message": "Expected number, received string"
      }
    ]
  }
}

Rate Limits

EndpointLimit
Create/Update Widget30/hour
List Widgets300/hour
Send Widget Message100/hour

Best Practices

  1. Schema Validation: Always define comprehensive JSON schemas
  2. Error Handling: Handle missing/invalid data gracefully in components
  3. Performance: Optimize component rendering for large datasets
  4. Security: Never execute untrusted code or render raw HTML
  5. Styling: Use scoped styles (styled-jsx or inline) to avoid conflicts
  6. Testing: Validate widgets with the validation endpoint before saving

Code Examples

Create and Use Widget

javascript
const axios = require('axios');

const API_KEY = 'your_api_key';
const BASE_URL = 'https://api.cognipeer.com/api/v1';

async function createAndUseWidget() {
  // 1. Create widget
  const widget = await axios.post(`${BASE_URL}/widget`, {
    key: 'my-chart',
    name: 'Custom Chart',
    description: 'A custom chart widget',
    category: 'analytics',
    schema: {
      type: 'object',
      properties: {
        data: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              label: { type: 'string' },
              value: { type: 'number' }
            }
          }
        }
      },
      required: ['data']
    },
    component: `
      function CustomChart({ data }) {
        return (
          <div>
            {data.data.map((item, i) => (
              <div key={i}>
                {item.label}: {item.value}
              </div>
            ))}
          </div>
        );
      }
      export default CustomChart;
    `
  }, {
    headers: { Authorization: `Bearer ${API_KEY}` }
  });

  const widgetId = widget.data.data.id;

  // 2. Add to peer
  await axios.post(`${BASE_URL}/peer/peer_123/widgets`, {
    widgetId,
    enabled: true
  }, {
    headers: { Authorization: `Bearer ${API_KEY}` }
  });

  // 3. Send widget in conversation
  await axios.post(`${BASE_URL}/conversation/conv_456/message`, {
    type: 'widget',
    widgetKey: 'my-chart',
    data: {
      data: [
        { label: 'Q1', value: 100 },
        { label: 'Q2', value: 150 },
        { label: 'Q3', value: 200 }
      ]
    },
    text: 'Here are your quarterly results'
  }, {
    headers: { Authorization: `Bearer ${API_KEY}` }
  });
}

createAndUseWidget();

Validate Before Creating

javascript
async function validateAndCreate(widgetData) {
  // Validate first
  const validation = await axios.post(
    `${BASE_URL}/widget/validate`,
    {
      schema: widgetData.schema,
      component: widgetData.component
    },
    { headers: { Authorization: `Bearer ${API_KEY}` } }
  );

  if (!validation.data.data.valid) {
    console.error('Validation failed:', validation.data.data.errors);
    return;
  }

  // Create if valid
  const widget = await axios.post(
    `${BASE_URL}/widget`,
    widgetData,
    { headers: { Authorization: `Bearer ${API_KEY}` } }
  );

  console.log('Widget created:', widget.data.data.id);
}

Support

For widget development support:

Built with VitePress