Skip to main content

Messages API

Send messages to your chatbot and receive AI-powered responses programmatically.

Base URL

https://api.peki.ai/api

Authentication

This API uses HMAC-SHA256 signatures for authentication. You'll need:

  • API Key (starts with pk_) - Your public identifier
  • API Secret (starts with sk_) - Your private signing key

Getting Your API Credentials

You can create your API key and secret in the Peki dashboard:

https://dashboard.peki.ai/dashboard/{chatbotId}/chatbot/api

Replace {chatbotId} with your actual chatbot ID.

⚠️ Keep your API secret secure - Never expose it in client-side code or public repositories.

Send Message

Send a message to your chatbot and receive an AI response.

POST /Dev/{chatbotId}/message

Path Parameters

ParameterTypeRequiredDescription
chatbotIdstringThe unique identifier for your chatbot

Headers

Content-Type: application/json
X-API-Key: pk_your_api_key_here
X-Signature: base64_encoded_signature
X-Timestamp: 1672531200
HeaderRequiredDescription
Content-TypeMust be application/json
X-API-KeyYour API key
X-SignatureHMAC-SHA256 signature (see Signature Generation)
X-TimestampUnix timestamp in seconds

Request Body

{
"user": {
"id": "user_123",
"name": "John Doe"
},
"message": {
"content": "What are the latest crypto trends?",
"file": "https://example.com/document.pdf"
}
}

Body Parameters

ParameterTypeRequiredDescription
userobjectUser information
user.idstringUnique identifier for the user
user.namestringDisplay name for the user
messageobjectMessage details
message.contentstringThe message text to send to the chatbot
message.filestringOptional URL to a file attachment

Response

Success Response

HTTP/1.1 200 OK
Content-Type: application/json
{
"data": "Based on current market trends, here are the key developments in crypto...",
"error": null,
"totalItems": 0,
"pageSize": 0,
"currentPage": 0,
"totalPages": 0
}

Error Response

HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {
"user.name": ["The user.name field is required."]
},
"traceId": "00-abc123-def456-00"
}

Signature Generation

HMAC signatures ensure request authenticity and prevent tampering.

Step 1: Create the Signature Payload

Combine these elements with newline separators:

{HTTP_METHOD}\n{PATH}\n{REQUEST_BODY}\n{TIMESTAMP}

Example:

POST
/api/Dev/chatbot_123/message
{"user":{"id":"user_123","name":"John Doe"},"message":{"content":"Hello"}}
1672531200

Step 2: Generate the Signature

HMAC-SHA256(payload, api_secret) → Base64 encode

Step 3: Include in Headers

Add the signature and timestamp to your request headers.

Code Examples

JavaScript

const crypto = require("crypto");
const https = require("https");

const apiKey = "pk_your_api_key";
const apiSecret = "sk_your_api_secret";
const chatbotId = "your_chatbot_id";

const requestBody = JSON.stringify({
user: { id: "user_123", name: "John Doe" },
message: { content: "What are the latest crypto trends?" },
});

const timestamp = Math.floor(Date.now() / 1000);
const path = `/api/Dev/${chatbotId}/message`;
const payload = `POST\n${path}\n${requestBody}\n${timestamp}`;
const signature = crypto
.createHmac("sha256", apiSecret)
.update(payload)
.digest("base64");

const options = {
hostname: "api.peki.ai",
port: 443,
path: path,
method: "POST",
headers: {
"Content-Type": "application/json",
"X-API-Key": apiKey,
"X-Signature": signature,
"X-Timestamp": timestamp.toString(),
},
};

const req = https.request(options, (res) => {
let data = "";
res.on("data", (chunk) => (data += chunk));
res.on("end", () => {
const response = JSON.parse(data);
console.log("AI Response:", response.data);
});
});

req.on("error", (error) => {
console.error("Error:", error);
});

req.write(requestBody);
req.end();

Python

import hmac
import hashlib
import base64
import time
import json
import requests

api_key = 'pk_your_api_key'
api_secret = 'sk_your_api_secret'
chatbot_id = 'your_chatbot_id'

request_body = json.dumps({
'user': {'id': 'user_123', 'name': 'John Doe'},
'message': {'content': 'What are the latest crypto trends?'}
})

timestamp = str(int(time.time()))
path = f'/api/Dev/{chatbot_id}/message'
payload = f'POST\n{path}\n{request_body}\n{timestamp}'

signature = base64.b64encode(
hmac.new(api_secret.encode(), payload.encode(), hashlib.sha256).digest()
).decode()

headers = {
'Content-Type': 'application/json',
'X-API-Key': api_key,
'X-Signature': signature,
'X-Timestamp': timestamp
}

response = requests.post(
f'https://api.peki.ai{path}',
data=request_body,
headers=headers
)

if response.status_code == 200:
result = response.json()
print('AI Response:', result['data'])
else:
print('Error:', response.json())

cURL

#!/bin/bash

API_KEY="pk_your_api_key"
API_SECRET="sk_your_api_secret"
CHATBOT_ID="your_chatbot_id"

REQUEST_BODY='{"user":{"id":"user_123","name":"John Doe"},"message":{"content":"What are the latest crypto trends?"}}'
TIMESTAMP=$(date +%s)
PATH="/api/Dev/$CHATBOT_ID/message"
PAYLOAD="POST\n$PATH\n$REQUEST_BODY\n$TIMESTAMP"
SIGNATURE=$(echo -n "$PAYLOAD" | openssl dgst -sha256 -hmac "$API_SECRET" -binary | base64)

curl -X POST "https://api.peki.ai$PATH" \
-H "Content-Type: application/json" \
-H "X-API-Key: $API_KEY" \
-H "X-Signature: $SIGNATURE" \
-H "X-Timestamp: $TIMESTAMP" \
-d "$REQUEST_BODY"

Error Codes

Status CodeError TypeDescription
400Bad RequestInvalid request format or missing required fields
401UnauthorizedInvalid API key or signature
403ForbiddenAPI key doesn't have access to the specified chatbot
404Not FoundChatbot not found
429Too Many RequestsRate limit exceeded
500Internal Server ErrorServer error occurred

Rate Limits

  • Free tier: 100 messages per day per chatbot
  • Premium tier: 10,000 messages per day per chatbot
  • Enterprise: Custom limits

Rate limit headers are included in responses:

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1672617600

Best Practices

Security

  • ✅ Always use HTTPS
  • ✅ Keep API secrets secure
  • ✅ Regenerate signatures for each request
  • ✅ Validate timestamps (5-minute window)

Performance

  • ✅ Implement exponential backoff for retries
  • ✅ Cache responses when appropriate
  • ✅ Use connection pooling for multiple requests

Error Handling

  • ✅ Check status codes before parsing responses
  • ✅ Implement proper retry logic
  • ✅ Log errors for debugging