Optimly API Overview
Connect Optimly to your applications, websites, and systems using our powerful REST API.
What You Can Do with the API
The Optimly API lets you:
- Send messages to your agents programmatically
- Create chat sessions for your users
- Collect leads directly through your forms
- Schedule appointments via your booking system
- Handle conversation handoffs to email or human agents
- Integrate agent functionality into your existing applications
Getting Started
1. Get Your API Key
Each agent has its own unique API key:
- Go to your Agents dashboard
- Click on the agent you want to integrate
- Navigate to the Configuration tab
- Copy the API Key from the integration panel
2. Authentication
Include your API key in the Authorization
header of all requests:
Authorization: Bearer YOUR_AGENT_API_KEY
3. Base URL
All API endpoints use this base URL:
https://api.optimly.io
Core Concepts
Agents
Each agent is an AI assistant with its own knowledge base, personality, and capabilities. Your API key is tied to a specific agent.
Conversations
When a user starts chatting, a conversation (chat session) is created. All messages in that conversation maintain context and history.
Messages
Individual messages sent by users or responses from your agent. Messages are always part of a conversation.
Tools
Optional features your agent can use like lead capture, appointment scheduling, and email handoff.
Quick Examples
Send a Message (Enhanced)
const response = await fetch('https://api.optimly.io/external/agent/v2', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
chat_id: 'conversation_123',
content: 'Hello! I need help with pricing.',
metadata: {
source: 'website',
user_tier: 'premium'
}
})
});
const data = await response.json();
console.log(data.response); // Agent's reply
console.log(data.tools_executed); // Any tools that were automatically executed
Create a New Conversation
const response = await fetch('https://api.optimly.io/external/message/new-chat', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
client_id: 'user_456'
})
});
const data = await response.json();
console.log(data.chat_id); // Use this for future messages
Capture a Lead
const response = await fetch('https://api.optimly.io/external/tools/lead-form', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
full_name: 'John Doe',
email: 'john@example.com',
phone: '+1234567890',
company: 'Acme Corp',
message: 'Interested in your services'
})
});
Available Endpoints
🤖 Agent Interaction
- Enhanced Agent (v2) - Send messages with automatic tool execution
- Legacy Agent - Basic agent interaction
💬 Chat Management
- Chat Sessions - Create and manage conversations
- Create Chat - Start a new conversation
- Get Messages - Retrieve conversation history
📝 Message Handling
- Message Management - Add messages to conversations
- Get Conversations - List user's chat sessions
🛠️ Tools & Actions
- Tools Overview - Automation features guide
- Lead Capture - Collect customer information
- Appointment Booking - Schedule meetings
- Email Handoff - Transfer to human support
🔐 Security & Setup
- Authentication Guide - Secure API access
- Health Check - Verify API status
Integration Patterns
Website Chat Widget
Perfect for adding live chat to your website:
<!-- Add this to your website -->
<script>
async function sendChatMessage(message) {
const response = await fetch('https://api.optimly.io/external/agent/v2', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
chat_id: window.currentChatId,
content: message
})
});
return await response.json();
}
</script>
Lead Generation Forms
Capture leads from any form on your site:
// When user submits your form
async function submitLead(formData) {
await fetch('https://api.optimly.io/external/tools/lead-form', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
full_name: formData.name,
email: formData.email,
phone: formData.phone,
message: formData.inquiry
})
});
}
Booking System Integration
Let customers schedule appointments:
async function bookAppointment(appointmentData) {
const response = await fetch('https://api.optimly.io/external/tools/appointment', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: appointmentData.name,
email: appointmentData.email,
date: appointmentData.date,
time: appointmentData.time,
duration_minutes: 30,
notes: appointmentData.notes
})
});
return await response.json();
}
Best Practices
🔒 Security
- Never expose your API key in frontend JavaScript code
- Use environment variables to store API keys securely
- Implement API key rotation if you suspect compromise
- Validate input data before sending to the API
⚡ Performance
- Reuse chat IDs for ongoing conversations
- Implement proper error handling for network issues
- Use appropriate timeouts for API calls
- Cache responses when appropriate
🎯 User Experience
- Show typing indicators while waiting for responses
- Handle errors gracefully with user-friendly messages
- Implement conversation history for better context
- Provide fallback options if the agent can't help
Error Handling
The API returns standard HTTP status codes:
200
- Success400
- Bad Request (invalid data)401
- Unauthorized (invalid API key)404
- Not Found (agent or resource doesn't exist)429
- Too Many Requests (rate limit exceeded)500
- Internal Server Error
try {
const response = await fetch('https://api.optimly.io/external/agent/v2', {
// ... your request
});
if (!response.ok) {
throw new Error(`API Error: ${response.status}`);
}
const data = await response.json();
// Handle success
} catch (error) {
console.error('Failed to send message:', error);
// Show user-friendly error message
}
Rate Limits
- 100 requests per minute per API key
- 1,000 requests per hour per API key
- 10,000 requests per day per API key
If you need higher limits, contact our support team.
Support & Resources
📚 Documentation
- Complete API Reference - Detailed endpoint documentation
- Code Examples - Ready-to-use integration examples
- SDKs & Libraries - Official libraries for popular languages
🆘 Get Help
- Technical Issues: contact@optimly.io
- Community Support: Join our Discord
- Feature Requests: Submit on GitHub
🔄 Stay Updated
- API Changelog: Track updates and breaking changes
- Developer Newsletter: Get notified of new features
- Status Page: Monitor API uptime and incidents
Ready to integrate? Check out our detailed API reference for complete endpoint documentation.