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/v1API 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.
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.
| Plan | Requests/min | Chat messages/min | Documents/day |
|---|---|---|---|
| Free | 60 | 20 | 10 |
| Pro | 300 | 100 | 100 |
| Enterprise | 1,000+ | 500+ | Unlimited |
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": {
"code": "invalid_request",
"message": "The 'name' field is required when creating an assistant.",
"details": {
"field": "name",
"constraint": "required"
}
}
}| Status | Code | Description |
|---|---|---|
| 400 | invalid_request | Missing or invalid parameters in the request body |
| 401 | unauthorized | Missing, expired, or invalid API key |
| 403 | forbidden | API key lacks permission for this operation |
| 404 | not_found | The requested resource does not exist |
| 409 | conflict | Resource already exists or version conflict |
| 422 | validation_error | Request was well-formed but failed validation |
| 429 | rate_limited | Too many requests — see Retry-After header |
| 500 | internal_error | Unexpected 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.
/v1/assistantsCreate a new AI assistant for your organisation. The assistant will be initialised with default settings and can be customised further.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| name | string | Yes | Display name for the assistant (max 100 chars) |
| type | string | Yes | One of: state_chatbot, medichat, provider_assistant, custom |
| languages | string[] | No | ISO 639-1 codes. Supported: en, ha, yo, ig, pcm. Default: ["en"] |
| welcome_message | string | No | Greeting shown to users on first interaction |
| config | object | No | Configuration 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>"
}/v1/assistantsList all assistants in your organisation. Supports pagination and filtering by status or type.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| page | integer | No | Page number (default: 1) |
| per_page | integer | No | Items per page (default: 20, max: 100) |
| status | string | No | Filter by status: active, paused, archived |
| type | string | No | Filter 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
}
}/v1/assistants/:idRetrieve 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"
}/v1/assistants/:idUpdate 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"
}/v1/assistants/:idDelete 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).
/v1/assistants/:id/documentsUpload one or more training documents to an assistant. Use multipart/form-data for file uploads. Maximum file size: 50 MB per file.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| file | file | Yes | The document file (PDF, DOCX, CSV, XLSX, TXT) |
| category | string | No | Category tag: clinical_guidelines, formulary, policy, faq, training_manual, other |
| description | string | No | Brief description of the document content |
| language | string | No | Primary 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.
/v1/assistants/:id/documentsList all documents uploaded to an assistant. Supports pagination and filtering by status or category.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| page | integer | No | Page number (default: 1) |
| per_page | integer | No | Items per page (default: 20, max: 100) |
| status | string | No | Filter: processing, ready, failed |
| category | string | No | Filter 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
}
}/v1/assistants/:id/documents/:doc_idRemove 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.
/v1/chat/completionsSend a message to an assistant and receive an AI-generated response. Supports multi-turn conversations via session IDs.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| assistant_id | string | Yes | The assistant to send the message to |
| message | string | Yes | The user message (max 4,000 characters) |
| session_id | string | No | Session ID for multi-turn context. Omit to start a new session. |
| language | string | No | Preferred response language (ISO 639-1). Default: auto-detect. |
| stream | boolean | No | Enable server-sent events (SSE) streaming. Default: false. |
| metadata | object | No | Custom 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"
}/v1/chat/sessions/:session_idRetrieve the full message history for a conversation session. Useful for displaying conversation context or auditing.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| limit | integer | No | Number of messages to return (default: 50, max: 200) |
| before | string | No | Message 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.
/v1/connectionsRegister a database connection. Credentials are encrypted at rest using AES-256. HIVA only requires read-only access.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| name | string | Yes | Display name for this connection |
| engine | string | Yes | Database engine: postgresql, mysql, sqlite |
| host | string | Yes | Database host (e.g., db.example.com) |
| port | integer | No | Port number (defaults: PostgreSQL 5432, MySQL 3306) |
| database | string | Yes | Database name |
| username | string | Yes | Database username (read-only recommended) |
| password | string | Yes | Database password (encrypted at rest) |
| ssl | boolean | No | Require 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.
/v1/queryAsk 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
| Name | Type | Required | Description |
|---|---|---|---|
| connection_id | string | Yes | The database connection to query |
| question | string | Yes | Natural language question (max 1,000 chars) |
| format | string | No | Response format: table, chart, summary. Default: table. |
| limit | integer | No | Maximum 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"
}/v1/connectionsList 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.
/v1/analyticsRetrieve aggregated analytics for your organisation or a specific assistant. Supports custom date ranges and metric selection.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| assistant_id | string | No | Filter by assistant. Omit for org-wide analytics. |
| period | string | No | Predefined period: 7d, 30d, 90d, 1y. Default: 30d. |
| start_date | string | No | Custom start date (ISO 8601). Overrides period. |
| end_date | string | No | Custom end date (ISO 8601). Overrides period. |
| metrics | string | No | Comma-separated: conversations, messages, resolution_rate, satisfaction, response_time, languages |
| granularity | string | No | Time 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
}
]
}/v1/analytics/top-queriesGet the most frequently asked questions across your assistants. Useful for identifying knowledge gaps and training priorities.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| assistant_id | string | No | Filter by assistant ID |
| period | string | No | Time period: 7d, 30d, 90d. Default: 30d. |
| limit | integer | No | Number 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.
/v1/webhooksRegister a new webhook endpoint. You can subscribe to specific events or receive all events.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| url | string | Yes | The HTTPS URL to receive webhook payloads |
| events | string[] | Yes | Events to subscribe to (see list below) |
| secret | string | No | Custom 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
{
"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
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 headerAvailable Events
assistant.created— New assistant createdassistant.updated— Assistant config changedassistant.deleted— Assistant removeddocument.processing— Document upload starteddocument.ready— Document indexed and readydocument.failed— Document processing failedchat.message— New chat message sentchat.feedback— User rated a responseconnection.status_changed— DB connection status updatequery.completed— NL2SQL query finishedSDKs & 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/sdkStatus: Stable
Python
pip install hiva-sdkStatus: Stable
PHP
composer require hiva/sdkStatus: Beta
Go
go get github.com/hiva-chat/go-sdkStatus: Coming Soon
cURL / REST
Direct HTTP — no SDK neededStatus: Stable
Postman Collection
Import from docs dashboardStatus: 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.
// 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
{
"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