chatwoot-sdk
v4.5.2-v1.3.0
Published
TypeScript SDK for Chatwoot API, generated by OpenAPI Generator Typescript-fetch
Maintainers
Readme
Chatwoot SDK
A TypeScript SDK for the Chatwoot API, automatically generated from OpenAPI specifications using OpenAPI Generator.
📦 Installation
npm install chatwoot-sdk
# or
yarn add chatwoot-sdk
# or
pnpm add chatwoot-sdk🚀 Quick Start
Unified Client (Recommended)
The easiest way to use the SDK is with the unified ChatwootClient:
import { ChatwootClient } from 'chatwoot-sdk'
// Create client with single configuration
const client = new ChatwootClient({
basePath: 'https://your-chatwoot-instance.com',
headers: {
'api_access_token': process.env.CHATWOOT_API_KEY || ''
}
})
// Access any API directly - no need to create separate instances!
try {
// Account operations
const account = await client.accounts.getDetailsOfAnAccount({ accountId: 1 })
// Contact operations
const contacts = await client.contacts.contactList({ accountId: 1 })
// Conversation operations
const conversations = await client.conversations.conversationList({ accountId: 1 })
console.log('Account:', account)
} catch (error) {
console.error('Error:', error)
}Individual API Classes (Alternative)
For fine-grained control, you can still use individual API classes:
import { Configuration, AccountsApi } from 'chatwoot-sdk'
const configuration = new Configuration({
basePath: 'https://your-chatwoot-instance.com',
headers: {
'api_access_token': process.env.CHATWOOT_API_KEY || ''
}
})
const accountsApi = new AccountsApi(configuration)
const account = await accountsApi.getDetailsOfAnAccount({ accountId: 1 })🔧 Configuration
The SDK accepts the following configuration options:
- basePath: Your Chatwoot instance URL (e.g.,
https://app.chatwoot.com) - headers: Object containing the
api_access_tokenheader - apiKey: Alternative way to provide API authentication
- accessToken: OAuth2 access token (if using OAuth)
Using the Unified Client
import { ChatwootClient, createChatwootClient } from 'chatwoot-sdk'
// Option 1: Direct instantiation
const client = new ChatwootClient({
basePath: 'https://your-chatwoot-instance.com',
headers: {
'api_access_token': process.env.CHATWOOT_API_KEY || ''
}
})
// Option 2: Using convenience function
const client = createChatwootClient({
basePath: 'https://your-chatwoot-instance.com',
apiKey: process.env.CHATWOOT_API_KEY || ''
})
// Option 3: Update configuration at runtime
client.updateConfiguration({
basePath: 'https://new-instance.com',
apiKey: 'new-api-key'
})Using Individual API Classes
import { Configuration } from 'chatwoot-sdk'
const configuration = new Configuration({
basePath: 'https://your-chatwoot-instance.com',
headers: {
'api_access_token': process.env.CHATWOOT_API_KEY || ''
}
})📚 Available APIs
The unified ChatwootClient provides access to all Chatwoot API endpoints through organized properties:
Core APIs
client.account: Account details and settingsclient.accounts: Account CRUD operationsclient.accountUsers: Account user managementclient.agents: Agent managementclient.users: User creation and managementclient.profile: User profile operations
Contact & Customer APIs
client.contacts: Contact managementclient.contactsAPI: Public contact operationsclient.contact: Contact-inbox operationsclient.contactLabels: Contact labeling
Conversation & Messaging APIs
client.conversations: Conversation managementclient.conversationsAPI: Public conversation operationsclient.conversation: Individual conversation operationsclient.conversationAssignments: Conversation assignmentsclient.messages: Message operationsclient.messagesAPI: Public message operations
Inbox & Channel APIs
client.inboxes: Inbox managementclient.inboxAPI: Public inbox operations
Automation & Tools APIs
client.agentBots: Agent bot managementclient.accountAgentBots: Account-specific agent botsclient.automationRule: Automation rulesclient.cannedResponses: Pre-written responsesclient.customAttributes: Custom fieldsclient.customFilters: Custom conversation filters
Admin & Analytics APIs
client.teams: Team managementclient.webhooks: Webhook configurationclient.integrations: Third-party integrationsclient.reports: Analytics and reportingclient.auditLogs: Audit trailclient.helpCenter: Knowledge base management
Survey & Feedback APIs
client.csatSurveyPage: Customer satisfaction surveys
Quick Access Examples
// All APIs accessible from single client instance
const client = new ChatwootClient({ /* config */ })
// Account operations
await client.accounts.getDetailsOfAnAccount({ accountId: 1 })
// Contact operations
await client.contacts.contactCreate({ accountId: 1, contactCreatePayload: {...} })
// Conversation operations
await client.conversations.conversationList({ accountId: 1 })
// Message operations
await client.messages.createANewMessageInAConversation({ accountId: 1, conversationId: 123, conversationMessageCreatePayload: {...} })📝 Examples
Complete Integration Example
import { ChatwootClient, ContactCreatePayload, ConversationMessageCreatePayload } from 'chatwoot-sdk'
// Initialize the client once
const client = new ChatwootClient({
basePath: 'https://your-chatwoot-instance.com',
headers: {
'api_access_token': process.env.CHATWOOT_API_KEY || ''
}
})
async function handleCustomerInteraction() {
try {
// 1. Create a contact
const contactData: ContactCreatePayload = {
name: 'John Doe',
email: '[email protected]',
phone: '+1234567890'
}
const contact = await client.contacts.contactCreate({
accountId: 1,
contactCreatePayload: contactData
})
// 2. List conversations for the account
const conversations = await client.conversations.conversationList({
accountId: 1,
page: 1,
perPage: 20
})
// 3. Send a message to a conversation
const messageData: ConversationMessageCreatePayload = {
content: 'Hello! How can I help you?',
messageType: 'outgoing'
}
const message = await client.messages.createANewMessageInAConversation({
accountId: 1,
conversationId: 123,
conversationMessageCreatePayload: messageData
})
// 4. Get conversation details
const conversation = await client.conversations.getDetailsOfAConversation({
accountId: 1,
conversationId: 123
})
console.log('Successfully handled customer interaction')
} catch (error) {
console.error('Error handling customer interaction:', error)
}
}Creating a Contact
import { ChatwootClient, ContactCreatePayload } from 'chatwoot-sdk'
const client = new ChatwootClient({ /* config */ })
const contactData: ContactCreatePayload = {
name: 'John Doe',
email: '[email protected]',
phone: '+1234567890'
}
const contact = await client.contacts.contactCreate({
accountId: 1,
contactCreatePayload: contactData
})Sending a Message
import { ChatwootClient, ConversationMessageCreatePayload } from 'chatwoot-sdk'
const client = new ChatwootClient({ /* config */ })
const messageData: ConversationMessageCreatePayload = {
content: 'Hello! How can I help you?',
messageType: 'outgoing'
}
const message = await client.messages.createANewMessageInAConversation({
accountId: 1,
conversationId: 123,
conversationMessageCreatePayload: messageData
})Managing Conversations
import { ChatwootClient } from 'chatwoot-sdk'
const client = new ChatwootClient({ /* config */ })
// List conversations
const conversations = await client.conversations.conversationList({
accountId: 1,
page: 1,
perPage: 20
})
// Get conversation details
const conversation = await client.conversations.getDetailsOfAConversation({
accountId: 1,
conversationId: 123
})
// Assign conversation to an agent
await client.conversationAssignments.assignAConversation({
accountId: 1,
conversationId: 123,
assignAConversationRequest: { assigneeId: 456 }
})Working with Teams and Agents
import { ChatwootClient } from 'chatwoot-sdk'
const client = new ChatwootClient({ /* config */ })
// List all teams
const teams = await client.teams.listAllTeams({ accountId: 1 })
// Get team members
const teamMembers = await client.teams.getTeamMembers({
accountId: 1,
teamId: 10
})
// List all agents
const agents = await client.agents.getAccountAgents({ accountId: 1 })Setting up Automation
import { ChatwootClient } from 'chatwoot-sdk'
const client = new ChatwootClient({ /* config */ })
// Create canned response
const cannedResponse = await client.cannedResponses.addNewCannedResponseToAccount({
accountId: 1,
cannedResponseCreateUpdatePayload: {
content: 'Thank you for contacting us!',
short_code: 'thanks'
}
})
// Create automation rule
const automationRule = await client.automationRule.addNewAutomationRuleToAccount({
accountId: 1,
automationRuleCreateUpdatePayload: {
name: 'Welcome Message',
description: 'Send welcome message to new conversations',
event_name: 'conversation_created',
conditions: [],
actions: [
{
action_name: 'send_message',
action_params: ['Welcome to our support!']
}
]
}
})🚨 Error Handling
import { ChatwootClient, ResponseError, FetchError, RequiredError } from 'chatwoot-sdk'
try {
const contact = await client.contacts.contactCreate({
accountId: 1,
contactCreatePayload: { name: 'John', email: '[email protected]' }
})
} catch (error) {
if (error instanceof ResponseError) {
// HTTP errors (4xx, 5xx) - access error.response
console.error(`HTTP ${error.response.status}:`, error.message)
const errorBody = await error.response.clone().json()
} else if (error instanceof FetchError) {
// Network errors - access error.cause
console.error('Network error:', error.cause)
} else if (error instanceof RequiredError) {
// Missing params - access error.field
console.error(`Missing: ${error.field}`)
}
}✨ Why Use the Unified Client?
The ChatwootClient provides several advantages over individual API classes:
🎯 Single Configuration
- Configure once, use everywhere
- No need to pass configuration to each API class
- Consistent authentication across all operations
🧹 Cleaner Code
// Before: Multiple imports and instances
import { ContactsApi, ConversationsApi, MessagesApi, Configuration } from 'chatwoot-sdk'
const config = new Configuration({...})
const contactsApi = new ContactsApi(config)
const conversationsApi = new ConversationsApi(config)
const messagesApi = new MessagesApi(config)
// After: Single import and instance
import { ChatwootClient } from 'chatwoot-sdk'
const client = new ChatwootClient({...})🔄 Dynamic Configuration
// Update configuration for all APIs at once
client.updateConfiguration({
basePath: 'https://new-instance.com',
apiKey: 'new-api-key'
})🎨 Better Developer Experience
- Organized API access with logical grouping
- Full TypeScript IntelliSense support
- Consistent method naming and patterns
- Easy discovery of available operations
🚀 Future-Proof
- Automatically includes new APIs as they're added
- Maintains backward compatibility
- Single entry point for all Chatwoot operations
🔄 Regenerating the SDK
This SDK is automatically generated from Chatwoot's OpenAPI specification. To regenerate it:
Prerequisites
- Docker installed on your system
- Access to the Chatwoot OpenAPI specification
Regeneration Command
docker run --rm -v "${PWD}:/local" openapitools/openapi-generator-cli generate \
-i https://raw.githubusercontent.com/chatwoot/chatwoot/refs/heads/develop/swagger/swagger.json \
-g typescript-fetch \
-o /local🔧 Changes Made to OpenAPI-Generated Code
This SDK includes several modifications to the standard OpenAPI-generated code to improve usability and error handling:
1. Added Unified Client (init.ts)
- File:
init.ts - Purpose: Created a unified
ChatwootClientclass that consolidates all API endpoints into a single, easy-to-use interface - Benefits:
- Single configuration point for all APIs
- Simplified developer experience
- Consistent authentication across all operations
- Better organization of API endpoints
2. Enhanced Error Handling (runtime.ts)
- File:
runtime.ts - Improvement: Enhanced the
ResponseErrorthrow statement to include response status and body information - Before: Generic error message without detailed information
- After: Detailed error message including HTTP status code and response body
- Benefits:
- Improved error detection and debugging
- No need to manually inspect
error.responsefor details - Standardized error handling even when specific OpenAPI error handling isn't defined
- Implementation:
// IMPROVED ERROR MESSAGE throw new ResponseError(response, 'Response returned an error code ' + response.status + ' | Body:' + await response.clone().text());
3. Code Duplication Fixes
- Issue: Removed duplicated automatically generated code that was causing build errors
- Solution: Cleaned up redundant code sections that were preventing successful compilation
- Note: This issue will likely be resolved in future OpenAPI generator versions
4. Removed "/accounts/{account_id}/conversations/{conversation_id}/messages" endpoint from the OpenAPI specification (since it does not start with "/api/v1/")
- Issue: The endpoint was causing runtime errors due to basePath issues.
- Solution: Removed the endpoint "/accounts/{account_id}/conversations/{conversation_id}/messages" from the OpenAPI specification.
What Gets Generated
- APIs: All API endpoint classes with TypeScript types
- Models: Complete data models and interfaces
- Runtime: HTTP client and configuration utilities
- Types: Full TypeScript type definitions
🏗️ Development
Building
npm run build
# or
pnpm buildCleaning
npm run clean
# or
pnpm clean📋 Requirements
- Node.js >= 18.0.0
- TypeScript support
📄 License
ISC License
🤝 Contributing
This SDK is automatically generated, so please:
- Report issues with the generated code
- Submit feature requests for the OpenAPI specification
- Contribute to the main Chatwoot project for API improvements
🔗 Links
📊 Version
Current Chatwootversion: 4.5.2
This SDK is generated from Chatwoot's latest OpenAPI specification and is kept up-to-date with the main Chatwoot project. The unified client provides a modern, developer-friendly interface while maintaining full compatibility with the underlying API structure.
