API Reference

Complete REST API documentation for integrating with the HIVA platform. Build AI-powered healthcare assistants, connect databases, and query your data programmatically.

Overview

The HIVA API is a RESTful interface that allows you to programmatically manage AI assistants, upload training documents, conduct conversations, connect databases, and retrieve analytics. All responses are returned in JSON format.

Base URL

https://api.hiva.chat/v1

API Version

v1 (stable)

Protocol

HTTPS only (TLS 1.2+)

Content Type

All requests must include Content-Type: application/json unless uploading files (use multipart/form-data). All timestamps are returned in ISO 8601 format (UTC).

Authentication

All API requests require a Bearer token in the Authorization header. Obtain your API key from the HIVA Admin dashboard under Settings → API Keys. Each key is scoped to your organisation and can be rotated at any time.

Authorization Header
curl -X GET https://api.hiva.chat/v1/assistants \
  -H "Authorization: Bearer hiva_sk_live_abc123def456..." \
  -H "Content-Type: application/json"

Live Keys

Prefix: hiva_sk_live_

For production use. All operations are real.

Test Keys

Prefix: hiva_sk_test_

For development. Sandboxed data, no billing.

Security: Never expose your API key in client-side code. Always use server-side requests or your backend as a proxy. Rotate keys immediately if compromised.

Rate Limits

Rate limits are applied per API key. Exceeding limits returns a 429 Too Many Requests response. Rate limit headers are included in every response.

PlanRequests/minChat messages/minDocuments/day
Free602010
Pro300100100
Enterprise1,000+500+Unlimited
Rate Limit Response Headers
X-RateLimit-Limit: 300
X-RateLimit-Remaining: 287
X-RateLimit-Reset: 1709312400
Retry-After: 12

Error Handling

The HIVA API uses standard HTTP status codes. Errors include a JSON body with a machine-readable code, human-readable message, and optional details object.

Error Response Format
{
  "error": {
    "code": "invalid_request",
    "message": "The 'name' field is required when creating an assistant.",
    "details": {
      "field": "name",
      "constraint": "required"
    }
  }
}
StatusCodeDescription
400invalid_requestMissing or invalid parameters in the request body
401unauthorizedMissing, expired, or invalid API key
403forbiddenAPI key lacks permission for this operation
404not_foundThe requested resource does not exist
409conflictResource already exists or version conflict
422validation_errorRequest was well-formed but failed validation
429rate_limitedToo many requests — see Retry-After header
500internal_errorUnexpected server error — contact support

Assistants

Create, manage, and configure AI assistants for your organisation. Each assistant can be tailored with custom languages, welcome messages, response behaviour, and training data.

POST/v1/assistants

Create a new AI assistant for your organisation. The assistant will be initialised with default settings and can be customised further.

Parameters

NameTypeRequiredDescription
namestringYesDisplay name for the assistant (max 100 chars)
typestringYesOne of: state_chatbot, medichat, provider_assistant, custom
languagesstring[]NoISO 639-1 codes. Supported: en, ha, yo, ig, pcm. Default: ["en"]
welcome_messagestringNoGreeting shown to users on first interaction
configobjectNoConfiguration object (tone, max_response_length, fallback_message)

Request Body

{
  "name": "Zamfara Health Bot",
  "type": "state_chatbot",
  "languages": ["en", "ha"],
  "welcome_message": "Welcome to Zamfara State Health Service. How can I help you today?",
  "config": {
    "tone": "friendly",
    "max_response_length": 500,
    "fallback_message": "I'm not sure about that. Please contact the helpline at 0800-ZAMFARA."
  }
}

Response 200 OK

{
  "id": "ast_zam_abc123",
  "name": "Zamfara Health Bot",
  "type": "state_chatbot",
  "status": "active",
  "languages": ["en", "ha"],
  "documents_count": 0,
  "conversations_count": 0,
  "created_at": "2026-02-27T10:30:00Z",
  "embed_code": "<script src='https://cdn.hiva.chat/widget/ast_zam_abc123.js'></script>"
}
GET/v1/assistants

List all assistants in your organisation. Supports pagination and filtering by status or type.

Parameters

NameTypeRequiredDescription
pageintegerNoPage number (default: 1)
per_pageintegerNoItems per page (default: 20, max: 100)
statusstringNoFilter by status: active, paused, archived
typestringNoFilter by type: state_chatbot, medichat, provider_assistant, custom

Response 200 OK

{
  "data": [
    {
      "id": "ast_zam_abc123",
      "name": "Zamfara Health Bot",
      "type": "state_chatbot",
      "status": "active",
      "documents_count": 12,
      "conversations_count": 8450,
      "created_at": "2026-02-27T10:30:00Z"
    }
  ],
  "pagination": {
    "page": 1,
    "per_page": 20,
    "total": 5,
    "total_pages": 1
  }
}
GET/v1/assistants/:id

Retrieve detailed information about a specific assistant, including its configuration, document count, and performance metrics.

Response 200 OK

{
  "id": "ast_zam_abc123",
  "name": "Zamfara Health Bot",
  "type": "state_chatbot",
  "status": "active",
  "languages": ["en", "ha"],
  "welcome_message": "Welcome to Zamfara State Health Service.",
  "config": {
    "tone": "friendly",
    "max_response_length": 500,
    "fallback_message": "I'm not sure about that..."
  },
  "documents_count": 12,
  "conversations_count": 8450,
  "avg_satisfaction": 4.6,
  "resolution_rate": 0.89,
  "created_at": "2026-02-27T10:30:00Z",
  "updated_at": "2026-02-27T14:20:00Z"
}
PATCH/v1/assistants/:id

Update an existing assistant's configuration. Only provided fields will be changed — omitted fields retain their current values.

Request Body

{
  "name": "Zamfara State Health Assistant",
  "config": {
    "tone": "professional",
    "max_response_length": 800
  }
}

Response 200 OK

{
  "id": "ast_zam_abc123",
  "name": "Zamfara State Health Assistant",
  "status": "active",
  "updated_at": "2026-02-27T15:00:00Z"
}
DELETE/v1/assistants/:id

Delete an assistant and all associated data. This action is irreversible. Active conversations will be terminated.

Response 200 OK

{
  "deleted": true,
  "id": "ast_zam_abc123"
}

Warning: This permanently deletes the assistant, all uploaded documents, conversation history, and analytics data. This action cannot be undone.

Documents

Upload training documents to your assistants. HIVA processes PDFs, DOCX files, CSV/Excel spreadsheets, and plain text. Documents are automatically chunked, embedded, and indexed for retrieval-augmented generation (RAG).

POST/v1/assistants/:id/documents

Upload one or more training documents to an assistant. Use multipart/form-data for file uploads. Maximum file size: 50 MB per file.

Parameters

NameTypeRequiredDescription
filefileYesThe document file (PDF, DOCX, CSV, XLSX, TXT)
categorystringNoCategory tag: clinical_guidelines, formulary, policy, faq, training_manual, other
descriptionstringNoBrief description of the document content
languagestringNoPrimary language of the document (ISO 639-1)

Request Body

// multipart/form-data
curl -X POST https://api.hiva.chat/v1/assistants/ast_zam_abc123/documents \
  -H "Authorization: Bearer hiva_sk_live_..." \
  -F "file=@malaria_protocol_2026.pdf" \
  -F "category=clinical_guidelines" \
  -F "description=NCDC Malaria Treatment Protocol 2026" \
  -F "language=en"

Response 200 OK

{
  "id": "doc_xyz789",
  "assistant_id": "ast_zam_abc123",
  "filename": "malaria_protocol_2026.pdf",
  "category": "clinical_guidelines",
  "status": "processing",
  "pages": 45,
  "chunks": null,
  "estimated_processing_time": "120 seconds",
  "created_at": "2026-02-27T10:35:00Z"
}

Document processing is asynchronous. Status transitions: processing → indexed → ready. Use GET /v1/assistants/:id/documents/:doc_id to check progress. You'll also receive a webhook event when processing completes.

GET/v1/assistants/:id/documents

List all documents uploaded to an assistant. Supports pagination and filtering by status or category.

Parameters

NameTypeRequiredDescription
pageintegerNoPage number (default: 1)
per_pageintegerNoItems per page (default: 20, max: 100)
statusstringNoFilter: processing, ready, failed
categorystringNoFilter by category tag

Response 200 OK

{
  "data": [
    {
      "id": "doc_xyz789",
      "filename": "malaria_protocol_2026.pdf",
      "category": "clinical_guidelines",
      "status": "ready",
      "pages": 45,
      "chunks": 128,
      "created_at": "2026-02-27T10:35:00Z"
    },
    {
      "id": "doc_abc456",
      "filename": "nhis_drug_formulary.pdf",
      "category": "formulary",
      "status": "ready",
      "pages": 210,
      "chunks": 645,
      "created_at": "2026-02-25T08:00:00Z"
    }
  ],
  "pagination": {
    "page": 1,
    "per_page": 20,
    "total": 12,
    "total_pages": 1
  }
}
DELETE/v1/assistants/:id/documents/:doc_id

Remove a document from the assistant's knowledge base. The document's embeddings are purged and it will no longer be used in responses.

Response 200 OK

{
  "deleted": true,
  "id": "doc_xyz789"
}

Chat

Send messages to your AI assistants and receive intelligent responses powered by your uploaded documents and knowledge base. Supports session management for multi-turn conversations.

POST/v1/chat/completions

Send a message to an assistant and receive an AI-generated response. Supports multi-turn conversations via session IDs.

Parameters

NameTypeRequiredDescription
assistant_idstringYesThe assistant to send the message to
messagestringYesThe user message (max 4,000 characters)
session_idstringNoSession ID for multi-turn context. Omit to start a new session.
languagestringNoPreferred response language (ISO 639-1). Default: auto-detect.
streambooleanNoEnable server-sent events (SSE) streaming. Default: false.
metadataobjectNoCustom key-value pairs to attach to this message (e.g., user_id, channel).

Request Body

{
  "assistant_id": "ast_zam_abc123",
  "session_id": "sess_user_001",
  "message": "What is the recommended treatment for malaria in pregnancy?",
  "language": "en"
}

Response 200 OK

{
  "id": "msg_a1b2c3d4",
  "session_id": "sess_user_001",
  "assistant_id": "ast_zam_abc123",
  "response": "According to the NHIS guidelines and NCDC Malaria Treatment Protocol, the recommended first-line treatment for uncomplicated malaria in pregnancy depends on the trimester:\n\n• 1st trimester: Oral Quinine + Clindamycin for 7 days\n• 2nd & 3rd trimester: Artemether-Lumefantrine (ACT) for 3 days\n\nFor severe malaria in any trimester, IV Artesunate is recommended. Always confirm with the latest NCDC protocol updates and consult with the attending physician.",
  "sources": [
    {
      "document": "NCDC Malaria Treatment Protocol 2026",
      "page": 23,
      "relevance": 0.96
    },
    {
      "document": "NHIS Essential Drug List",
      "page": 45,
      "relevance": 0.91
    }
  ],
  "confidence": 0.94,
  "language": "en",
  "tokens_used": 342,
  "created_at": "2026-02-27T11:00:00Z"
}
GET/v1/chat/sessions/:session_id

Retrieve the full message history for a conversation session. Useful for displaying conversation context or auditing.

Parameters

NameTypeRequiredDescription
limitintegerNoNumber of messages to return (default: 50, max: 200)
beforestringNoMessage ID cursor for pagination (return messages before this ID)

Response 200 OK

{
  "session_id": "sess_user_001",
  "assistant_id": "ast_zam_abc123",
  "messages": [
    {
      "id": "msg_0001",
      "role": "user",
      "content": "What is the recommended treatment for malaria in pregnancy?",
      "created_at": "2026-02-27T11:00:00Z"
    },
    {
      "id": "msg_0002",
      "role": "assistant",
      "content": "According to the NHIS guidelines...",
      "sources": [...],
      "confidence": 0.94,
      "created_at": "2026-02-27T11:00:01Z"
    }
  ],
  "has_more": false
}

Database & NL2SQL

Connect your databases (PostgreSQL, MySQL, SQLite) and query them using natural language. HIVA translates your questions into optimised SQL, executes them safely in a read-only sandbox, and returns structured results with optional chart formatting.

POST/v1/connections

Register a database connection. Credentials are encrypted at rest using AES-256. HIVA only requires read-only access.

Parameters

NameTypeRequiredDescription
namestringYesDisplay name for this connection
enginestringYesDatabase engine: postgresql, mysql, sqlite
hoststringYesDatabase host (e.g., db.example.com)
portintegerNoPort number (defaults: PostgreSQL 5432, MySQL 3306)
databasestringYesDatabase name
usernamestringYesDatabase username (read-only recommended)
passwordstringYesDatabase password (encrypted at rest)
sslbooleanNoRequire SSL connection. Default: true.

Request Body

{
  "name": "Zamfara Enrollment DB",
  "engine": "postgresql",
  "host": "db.zamfara-health.gov.ng",
  "port": 5432,
  "database": "nhis_enrollment",
  "username": "hiva_readonly",
  "password": "••••••••",
  "ssl": true
}

Response 200 OK

{
  "id": "conn_pg_001",
  "name": "Zamfara Enrollment DB",
  "engine": "postgresql",
  "status": "connected",
  "tables_discovered": 24,
  "schema_indexed": true,
  "created_at": "2026-02-27T09:00:00Z"
}

HIVA automatically discovers your schema (tables, columns, types, relationships) to generate accurate SQL. We strongly recommend using a read-only database user.

POST/v1/query

Ask a question in natural language and receive structured data from your connected database. HIVA translates the question to SQL, executes it safely, and formats the results.

Parameters

NameTypeRequiredDescription
connection_idstringYesThe database connection to query
questionstringYesNatural language question (max 1,000 chars)
formatstringNoResponse format: table, chart, summary. Default: table.
limitintegerNoMaximum rows to return (default: 100, max: 10,000)

Request Body

{
  "connection_id": "conn_pg_001",
  "question": "How many beneficiaries enrolled in Zamfara this month, broken down by week?",
  "format": "chart"
}

Response 200 OK

{
  "id": "qry_abc123",
  "answer": "3,247 beneficiaries enrolled in Zamfara State in February 2026.",
  "data": [
    { "week": "Feb 3–9", "enrollments": 812 },
    { "week": "Feb 10–16", "enrollments": 956 },
    { "week": "Feb 17–23", "enrollments": 748 },
    { "week": "Feb 24–27", "enrollments": 731 }
  ],
  "sql": "SELECT date_trunc('week', enrolled_at) AS week, COUNT(*) AS enrollments FROM beneficiaries WHERE state = 'Zamfara' AND enrolled_at >= '2026-02-01' GROUP BY 1 ORDER BY 1;",
  "execution_time_ms": 45,
  "rows_returned": 4,
  "format": "chart",
  "created_at": "2026-02-27T11:15:00Z"
}
GET/v1/connections

List all database connections for your organisation.

Response 200 OK

{
  "data": [
    {
      "id": "conn_pg_001",
      "name": "Zamfara Enrollment DB",
      "engine": "postgresql",
      "status": "connected",
      "tables_discovered": 24,
      "last_query_at": "2026-02-27T11:15:00Z"
    },
    {
      "id": "conn_mysql_002",
      "name": "Claims Processing DB",
      "engine": "mysql",
      "status": "connected",
      "tables_discovered": 18,
      "last_query_at": "2026-02-26T16:30:00Z"
    }
  ],
  "pagination": {
    "page": 1,
    "per_page": 20,
    "total": 2,
    "total_pages": 1
  }
}

Analytics

Access real-time analytics for your assistants including conversation volumes, resolution rates, user satisfaction scores, response times, and language usage breakdown.

GET/v1/analytics

Retrieve aggregated analytics for your organisation or a specific assistant. Supports custom date ranges and metric selection.

Parameters

NameTypeRequiredDescription
assistant_idstringNoFilter by assistant. Omit for org-wide analytics.
periodstringNoPredefined period: 7d, 30d, 90d, 1y. Default: 30d.
start_datestringNoCustom start date (ISO 8601). Overrides period.
end_datestringNoCustom end date (ISO 8601). Overrides period.
metricsstringNoComma-separated: conversations, messages, resolution_rate, satisfaction, response_time, languages
granularitystringNoTime series granularity: hour, day, week, month. Default: day.

Response 200 OK

{
  "period": {
    "start": "2026-01-28T00:00:00Z",
    "end": "2026-02-27T23:59:59Z"
  },
  "summary": {
    "total_conversations": 12450,
    "total_messages": 38200,
    "unique_users": 8930,
    "resolution_rate": 0.89,
    "avg_satisfaction": 4.6,
    "avg_response_time_ms": 1200,
    "languages": {
      "en": 0.45,
      "ha": 0.32,
      "pcm": 0.15,
      "yo": 0.05,
      "ig": 0.03
    }
  },
  "time_series": [
    {
      "date": "2026-02-27",
      "conversations": 420,
      "messages": 1280,
      "satisfaction": 4.7
    }
  ]
}
GET/v1/analytics/top-queries

Get the most frequently asked questions across your assistants. Useful for identifying knowledge gaps and training priorities.

Parameters

NameTypeRequiredDescription
assistant_idstringNoFilter by assistant ID
periodstringNoTime period: 7d, 30d, 90d. Default: 30d.
limitintegerNoNumber of top queries (default: 20, max: 100)

Response 200 OK

{
  "data": [
    {
      "query": "How do I enroll in NHIS?",
      "count": 1240,
      "avg_confidence": 0.92,
      "resolved_rate": 0.95
    },
    {
      "query": "What drugs are covered under my plan?",
      "count": 890,
      "avg_confidence": 0.88,
      "resolved_rate": 0.87
    },
    {
      "query": "Where is the nearest accredited hospital?",
      "count": 756,
      "avg_confidence": 0.85,
      "resolved_rate": 0.82
    }
  ]
}

Webhooks

Receive real-time notifications when events occur in your HIVA account. Webhooks are sent as HTTP POST requests to your specified URL with a JSON payload signed using HMAC-SHA256.

POST/v1/webhooks

Register a new webhook endpoint. You can subscribe to specific events or receive all events.

Parameters

NameTypeRequiredDescription
urlstringYesThe HTTPS URL to receive webhook payloads
eventsstring[]YesEvents to subscribe to (see list below)
secretstringNoCustom signing secret. Auto-generated if omitted.

Request Body

{
  "url": "https://your-app.com/webhooks/hiva",
  "events": [
    "assistant.created",
    "document.ready",
    "document.failed",
    "chat.message",
    "chat.feedback",
    "connection.status_changed",
    "query.completed"
  ]
}

Response 200 OK

{
  "id": "wh_001",
  "url": "https://your-app.com/webhooks/hiva",
  "events": ["assistant.created", "document.ready", ...],
  "secret": "whsec_abc123...",
  "status": "active",
  "created_at": "2026-02-27T09:00:00Z"
}

Webhook Payload Format

Example: document.ready
{
  "id": "evt_abc123",
  "type": "document.ready",
  "created_at": "2026-02-27T10:37:00Z",
  "data": {
    "document_id": "doc_xyz789",
    "assistant_id": "ast_zam_abc123",
    "filename": "malaria_protocol_2026.pdf",
    "chunks": 128,
    "processing_time_seconds": 118
  }
}

Verifying Signatures

Node.js verification example
const crypto = require('crypto');

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

// The signature is in the X-Hiva-Signature header

Available Events

assistant.createdNew assistant created
assistant.updatedAssistant config changed
assistant.deletedAssistant removed
document.processingDocument upload started
document.readyDocument indexed and ready
document.failedDocument processing failed
chat.messageNew chat message sent
chat.feedbackUser rated a response
connection.status_changedDB connection status update
query.completedNL2SQL query finished

SDKs & Libraries

Official client libraries make it easy to integrate HIVA into your application. All SDKs handle authentication, retries, rate limit backoff, and type safety.

JavaScript / TypeScript

npm install @hiva/sdk

Status: Stable

Python

pip install hiva-sdk

Status: Stable

PHP

composer require hiva/sdk

Status: Beta

Go

go get github.com/hiva-chat/go-sdk

Status: Coming Soon

cURL / REST

Direct HTTP — no SDK needed

Status: Stable

Postman Collection

Import from docs dashboard

Status: Available

Quick Start — JavaScript

import { HivaClient } from '@hiva/sdk';

const hiva = new HivaClient({
  apiKey: process.env.HIVA_API_KEY,
});

// Create an assistant
const assistant = await hiva.assistants.create({
  name: 'My Health Bot',
  type: 'custom',
  languages: ['en', 'ha'],
});

// Upload a document
await hiva.documents.upload(assistant.id, {
  file: './guidelines.pdf',
  category: 'clinical_guidelines',
});

// Send a chat message
const response = await hiva.chat.send({
  assistantId: assistant.id,
  message: 'What vaccines are required for children under 5?',
});

console.log(response.response);
console.log('Sources:', response.sources);

Quick Start — Python

from hiva_sdk import HivaClient

client = HivaClient(api_key="hiva_sk_live_...")

# Query your database in natural language
result = client.query(
    connection_id="conn_pg_001",
    question="Show me the top 10 LGAs by enrollment count this month",
    format="table"
)

print(result.answer)
for row in result.data:
    print(f"  {row['lga']}: {row['count']}")

Pagination

All list endpoints support cursor-based or offset-based pagination. Results are returned in a standard envelope with a data array and pagination object.

Pagination Parameters
// Offset-based (default)
GET /v1/assistants?page=2&per_page=20

// Cursor-based (for real-time data like messages)
GET /v1/chat/sessions/sess_001?before=msg_abc123&limit=50
Pagination Response
{
  "data": [...],
  "pagination": {
    "page": 2,
    "per_page": 20,
    "total": 87,
    "total_pages": 5,
    "has_next": true,
    "has_prev": true
  }
}

Need Help?

If you encounter any issues or have questions about the API, our team is here to help.

Email Support

api-support@hiva.chat

Status Page

status.hiva.chat

Community

community.hiva.chat