Skip to main content

Get Chat History by Identifier

Retrieve conversation history for a specific user or session identifier across all agents in your organization.

Endpoint

GET /api/v1/chat-history/identifier/{identifier}

Authentication

This endpoint requires API key authentication. Include your API key in the Authorization header using the Bearer scheme.

Header Format:

Authorization: Bearer {PUBLIC_KEY}:{SECRET_KEY}

Request

Path Parameters

ParameterTypeRequiredDescription
identifierstringYesThe unique identifier for the user or session (e.g., email, user ID, phone number)

Headers

HeaderTypeRequiredDescription
AuthorizationstringYesYour API key in the format Bearer pk_xxx:sk_xxx

Query Parameters

ParameterTypeRequiredDefaultDescription
pageintegerNo1Page number for pagination
limitintegerNo50Number of messages to return per page (max: 100)
agent_idstring (UUID)No-Filter by specific agent
thread_idstringNo-Filter by specific thread/conversation ID
start_datestring (ISO 8601)No-Filter messages from this date onwards
end_datestring (ISO 8601)No-Filter messages up to this date

Response

Success Response

Status Code: 200 OK

Response Body:

{
"success": true,
"data": {
"identifier": "user@example.com",
"messages": [
{
"id": "440e8400-e29b-41d4-a716-446655440099",
"agent_id": "550e8400-e29b-41d4-a716-446655440000",
"agent_name": "Customer Support Agent",
"thread_id": "thread_abc123xyz",
"input": "I need help with my account",
"output": "I'd be happy to help you with your account. What specific issue are you experiencing?",
"input_tokens": 8,
"output_tokens": 18,
"total_credits": 3,
"created_at": "2024-01-20T14:30:00Z",
"channel": "WEB"
},
{
"id": "550e8400-e29b-41d4-a716-446655440088",
"agent_id": "660e8400-e29b-41d4-a716-446655440001",
"agent_name": "Sales Assistant",
"thread_id": "thread_xyz789abc",
"input": "What pricing plans do you offer?",
"output": "We offer three pricing tiers: Basic ($29/month), Professional ($99/month), and Enterprise (custom pricing). Each plan includes different features and usage limits.",
"input_tokens": 7,
"output_tokens": 32,
"total_credits": 4,
"created_at": "2024-01-21T10:15:00Z",
"channel": "WHATSAPP"
}
],
"pagination": {
"page": 1,
"limit": 50,
"total": 2,
"has_more": false
}
}
}

Response Fields

FieldTypeDescription
successbooleanIndicates if the request was successful
data.identifierstringThe identifier used to filter the conversation history
data.messagesarrayArray of message objects
data.messages[].idstring (UUID)Unique identifier for the message
data.messages[].agent_idstring (UUID)ID of the agent that processed the message
data.messages[].agent_namestringName of the agent
data.messages[].thread_idstringConversation thread identifier
data.messages[].inputstringUser's input message
data.messages[].outputstringAgent's response message
data.messages[].input_tokensintegerNumber of tokens in the input
data.messages[].output_tokensintegerNumber of tokens in the output
data.messages[].total_creditsintegerTotal credits consumed for this message
data.messages[].created_atstring (ISO 8601)Timestamp when the message was created
data.messages[].channelstringChannel where the message originated (API, WEB, WHATSAPP)
data.paginationobjectPagination information
data.pagination.pageintegerCurrent page number
data.pagination.limitintegerNumber of items per page
data.pagination.totalintegerTotal number of messages
data.pagination.has_morebooleanWhether there are more pages available

Error Responses

401 Unauthorized

Missing or Invalid API Key:

Status: 401 Unauthorized
{
"success": false,
"error": "Invalid or missing API key"
}

400 Bad Request

Invalid Parameters:

Status: 400 Bad Request
{
"success": false,
"error": "Invalid page or limit parameter"
}

Missing Identifier:

Status: 400 Bad Request
{
"success": false,
"error": "Identifier parameter is required"
}

404 Not Found

No Messages Found:

Status: 404 Not Found
{
"success": false,
"error": "No conversation history found for this identifier"
}

500 Internal Server Error

Status: 500 Internal Server Error
{
"success": false,
"error": "Internal server error"
}

Example Usage

cURL

# Get chat history for an identifier
curl -X GET "https://agentsgt.com/api/v1/chat-history/identifier/user@example.com" \
-H "Authorization: Bearer pk_1234567890abcdef:sk_abcdef1234567890"

# With URL encoding for email identifier
curl -X GET "https://agentsgt.com/api/v1/chat-history/identifier/user%40example.com" \
-H "Authorization: Bearer pk_1234567890abcdef:sk_abcdef1234567890"

# Filter by specific agent
curl -X GET "https://agentsgt.com/api/v1/chat-history/identifier/user@example.com?agent_id=550e8400-e29b-41d4-a716-446655440000" \
-H "Authorization: Bearer pk_1234567890abcdef:sk_abcdef1234567890"

# With pagination
curl -X GET "https://agentsgt.com/api/v1/chat-history/identifier/user@example.com?page=2&limit=25" \
-H "Authorization: Bearer pk_1234567890abcdef:sk_abcdef1234567890"

# Filter by date range
curl -X GET "https://agentsgt.com/api/v1/chat-history/identifier/user@example.com?start_date=2024-01-01T00:00:00Z&end_date=2024-01-31T23:59:59Z" \
-H "Authorization: Bearer pk_1234567890abcdef:sk_abcdef1234567890"

JavaScript (Fetch API)

const publicKey = 'pk_1234567890abcdef';
const secretKey = 'sk_abcdef1234567890';
const identifier = 'user@example.com';

// URL encode the identifier
const encodedIdentifier = encodeURIComponent(identifier);

// Basic request
fetch(`https://agentsgt.com/api/v1/chat-history/identifier/${encodedIdentifier}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${publicKey}:${secretKey}`,
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
console.log(`Chat history for: ${data.data.identifier}`);
console.log(`Total messages: ${data.data.pagination.total}`);

// Group messages by agent
const messagesByAgent = {};
data.data.messages.forEach(msg => {
if (!messagesByAgent[msg.agent_name]) {
messagesByAgent[msg.agent_name] = [];
}
messagesByAgent[msg.agent_name].push(msg);
});

// Display messages by agent
Object.keys(messagesByAgent).forEach(agentName => {
console.log(`\n--- ${agentName} ---`);
messagesByAgent[agentName].forEach(msg => {
console.log(`[${msg.created_at}] User: ${msg.input}`);
console.log(`[${msg.created_at}] Agent: ${msg.output}`);
});
});
})
.catch(error => {
console.error('Error:', error);
});

// With filters
const params = new URLSearchParams({
page: '1',
limit: '25',
agent_id: '550e8400-e29b-41d4-a716-446655440000',
start_date: '2024-01-01T00:00:00Z'
});

fetch(`https://agentsgt.com/api/v1/chat-history/identifier/${encodedIdentifier}?${params}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${publicKey}:${secretKey}`,
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
console.log('Filtered chat history:', data.data.messages);
});

Python (Requests)

import requests
from urllib.parse import quote

public_key = 'pk_1234567890abcdef'
secret_key = 'sk_abcdef1234567890'
identifier = 'user@example.com'

# URL encode the identifier
encoded_identifier = quote(identifier)

headers = {
'Authorization': f'Bearer {public_key}:{secret_key}',
'Content-Type': 'application/json'
}

# Basic request
response = requests.get(
f'https://agentsgt.com/api/v1/chat-history/identifier/{encoded_identifier}',
headers=headers
)

if response.status_code == 200:
data = response.json()
print(f"Chat history for: {data['data']['identifier']}")
print(f"Total messages: {data['data']['pagination']['total']}")

for msg in data['data']['messages']:
print(f"\n[{msg['created_at']}] via {msg['channel']}")
print(f"Agent: {msg['agent_name']}")
print(f"User: {msg['input']}")
print(f"Agent: {msg['output']}")
print(f"Credits: {msg['total_credits']}")
else:
print(f"Error: {response.status_code} - {response.json()}")

# With filters
params = {
'page': 1,
'limit': 25,
'agent_id': '550e8400-e29b-41d4-a716-446655440000',
'thread_id': 'thread_abc123xyz'
}

response = requests.get(
f'https://agentsgt.com/api/v1/chat-history/identifier/{encoded_identifier}',
headers=headers,
params=params
)

# Paginate through all messages
def get_all_messages(identifier, agent_id=None):
all_messages = []
page = 1
has_more = True

while has_more:
params = {'page': page, 'limit': 100}
if agent_id:
params['agent_id'] = agent_id

response = requests.get(
f'https://agentsgt.com/api/v1/chat-history/identifier/{quote(identifier)}',
headers=headers,
params=params
)

if response.status_code == 200:
data = response.json()
all_messages.extend(data['data']['messages'])
has_more = data['data']['pagination']['has_more']
page += 1
else:
break

return all_messages

# Get all messages for the identifier
messages = get_all_messages('user@example.com')
print(f"Retrieved {len(messages)} total messages")

Node.js (Axios)

const axios = require('axios');

const publicKey = 'pk_1234567890abcdef';
const secretKey = 'sk_abcdef1234567890';
const identifier = 'user@example.com';

// URL encode the identifier
const encodedIdentifier = encodeURIComponent(identifier);

axios.get(`https://agentsgt.com/api/v1/chat-history/identifier/${encodedIdentifier}`, {
headers: {
'Authorization': `Bearer ${publicKey}:${secretKey}`,
'Content-Type': 'application/json'
},
params: {
page: 1,
limit: 50
}
})
.then(response => {
const { identifier, messages, pagination } = response.data.data;

console.log(`\nChat History for: ${identifier}`);
console.log(`Total messages: ${pagination.total}`);
console.log(`Page ${pagination.page}`);

// Display messages chronologically
messages.forEach(msg => {
console.log(`\n[${ msg.created_at}] ${msg.channel}`);
console.log(`Agent: ${msg.agent_name}`);
console.log(`User: ${msg.input}`);
console.log(`Agent: ${msg.output}`);
});

if (pagination.has_more) {
console.log('\n--- More messages available ---');
}
})
.catch(error => {
console.error('Error:', error.response?.data || error.message);
});

// Function to get all pages
async function getAllChatHistory(identifier, agentId = null) {
const allMessages = [];
let page = 1;
let hasMore = true;

while (hasMore) {
try {
const response = await axios.get(
`https://agentsgt.com/api/v1/chat-history/identifier/${encodeURIComponent(identifier)}`,
{
headers: {
'Authorization': `Bearer ${publicKey}:${secretKey}`
},
params: {
page,
limit: 100,
...(agentId && { agent_id: agentId })
}
}
);

allMessages.push(...response.data.data.messages);
hasMore = response.data.data.pagination.has_more;
page++;
} catch (error) {
console.error('Error fetching page:', page, error.message);
break;
}
}

return allMessages;
}

// Usage
getAllChatHistory('user@example.com')
.then(messages => {
console.log(`Retrieved ${messages.length} total messages`);
});

Use Cases

Customer Support History

Retrieve all interactions a customer has had across different support agents:

const customerEmail = 'customer@example.com';
// Get complete conversation history for customer support analysis

User Journey Tracking

Track how a user has interacted with different agents (sales, support, onboarding):

// See which agents a user has engaged with and their conversation flow

Compliance and Auditing

Access complete conversation records for compliance purposes:

# Export all conversations for a specific user with date filtering

Notes

  • The identifier is typically an email, user ID, phone number, or any unique user identifier you provide when sending messages
  • Messages are returned in ascending order by creation date (oldest first)
  • Maximum limit is 100 messages per page
  • Results include conversations across all agents in your organization
  • The agent_name field is included to help identify which agent handled each conversation
  • Identifiers should be URL-encoded, especially if they contain special characters (e.g., @ in email addresses)
  • Date filters use ISO 8601 format with timezone information
  • The API key's last_used_at timestamp is automatically updated when this endpoint is called