Overview
The Twilio Conversations API allows you to manage conversations, participants, and messages. You can list messages within a conversation using this API.
When listing messages, pagination is essential for handling large sets of data. You can control the size of pages with the PageSize parameter. For example, to limit the number of conversation messages returned to 10 per page:
curl -X GET "https://conversations.twilio.com/v1/Conversations/ConversationSid/Messages?PageSize=10"\
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN
For Multiservice Conversations, the Conversation Service Sid needs to be added to the URL:
curl -X GET "https://conversations.twilio.com/v1/Services/ISxx/Conversations/ConversationSid/Messages?PageSize=10"\
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN
The following code samples are provided for the default conversation service option, but they work for multiple services as well. For reference, please check Service Conversation Resource.
Product
Conversations, REST API
What You Need To Know
Below are code samples for paginating through the list of conversation messages in different programming languages.
Node.js
// Download the helper library from https://www.twilio.com/docs/node/install
const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";
// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = twilio(accountSid, authToken);
async function listConversationMessages(){
try{
var page = await client.conversations.v1.conversations("CHxxxx")
.messages
.page({ pageSize: 5 });
while(page!=null){
page.instances.forEach(message => console.log("Message Sid:", message.sid));
page = await page.nextPage();
}
}catch(err){
console.log(err);
}
}
listConversationMessages();
Python
# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client
# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ["TWILIO_ACCOUNT_SID"]
auth_token = os.environ["TWILIO_AUTH_TOKEN"]
client = Client(account_sid, auth_token)
# Function to list messages with pagination
def list_messages(conversation_sid, page_size):
try:
page = client.conversations.v1.conversations(conversation_sid).messages.page(page_size=page_size)
while page:
for message in page:
print("Message SID:", message.sid)
# Get the next page
page = page.next_page() if page.next_page_url else None
except Exception as e:
print("Error:", e)
# Call the function with your conversation SID
list_messages("CHxxxx", 5)
C#
// Install the C# / .NET helper library from twilio.com/docs/csharp/install
using System;
using Twilio;
using Twilio.Rest.Conversations.V1.Conversation;
using System.Threading.Tasks;
class Program {
public static async Task Main(string[] args) {
// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");
TwilioClient.Init(accountSid, authToken);
//pass the conversation sid in the targetURL below
//pass the page size
//pass the ordering (asc/desc)
string targetURL = "https://conversations.twilio.com/v1/Conversations/CHxxxx/Messages?PageSize=5&Order=desc";
int indexPage = 1;
var pageConversations = MessageResource.GetPage(targetURL, TwilioClient.GetRestClient());
//Get the results of page 1 and print it
Console.WriteLine("Printing page " + indexPage);
foreach(var record in pageConversations.Records) {
Console.WriteLine(record.Sid);
Console.WriteLine(record.DateCreated);
}
// If there are more pages, get the next page and print
while(pageConversations.HasNextPage()){
pageConversations = MessageResource.NextPage(pageConversations,TwilioClient.GetRestClient() );
indexPage = indexPage +1;
Console.WriteLine("Printing page " + indexPage);
foreach(var record in pageConversations.Records) {
Console.WriteLine(record.Sid);
Console.WriteLine(record.DateCreated);
}}
}
}
Java
// Install the Java helper library from twilio.com/docs/java/install
import com.twilio.Twilio;
import com.twilio.rest.conversations.v1.conversation.Message;
import com.twilio.base.*;
public class Example {
// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");
private static void listConversationMessages(String conversationSid, int pageSize) {
try {
Reader<Message> reader = Message.reader(conversationSid).pageSize(pageSize);
Page<Message> page = reader.firstPage();
while (page != null) {
for (Message message : page.getRecords()) {
System.out.println("Message SID: " + message.getSid());
}
if (page.hasNextPage()) {
page = reader.nextPage(page);
} else {
page = null;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
String conversationSid = "CHxxxx";
int pageSize = 5;
listConversationMessages(conversationSid, pageSize);
}
}
Go
package main
import (
"fmt"
"log"
"net/url"
"github.com/twilio/twilio-go"
conversations "github.com/twilio/twilio-go/rest/conversations/v1"
)
func main() {
// Replace with your actual credentials and Conversation SID
accountSid := "ACxxxxx" //Your Twilio Account SID, available from the Twilio Console
authToken := "auth_token" // Your Twilio Auth Token, available from the Twilio Console
conversationSid := "CHxxxx" // The SID of the conversation you want to interact with, can be found in your Twilio Console under Conversations.
client := twilio.NewRestClientWithParams(twilio.ClientParams{
Username: accountSid,
Password: authToken,
})
params := &conversations.ListConversationMessageParams{}
params.SetPageSize(5) // You can change page size as needed
// Track page number
currentPage := 1
// First page fetch
page, err := client.ConversationsV1.PageConversationMessage(conversationSid, params, "", "")
if err != nil {
log.Fatalf("Error fetching page %d: %v", currentPage, err)
}
// Print messages on the first page
fmt.Printf("\n--- Page %d ---\n", currentPage)
for _, msg := range page.Messages {
if msg.Body != nil {
fmt.Println("Message Sid:", *msg.Sid)
}
}
// Paginate through remaining pages
for page.Meta.NextPageUrl != nil {
currentPage++
u, _ := url.Parse(*page.Meta.NextPageUrl)
q := u.Query()
pageToken := q.Get("PageToken")
pageNumber := q.Get("Page")
page, err = client.ConversationsV1.PageConversationMessage(conversationSid, params, pageToken, pageNumber)
if err != nil {
log.Fatalf("Error fetching page %d: %v", currentPage, err)
}
fmt.Printf("\n--- Page %d ---\n", currentPage)
for _, msg := range page.Messages {
if msg.Body != nil {
fmt.Println("Message Sid:", *msg.Sid)
}
}
}}
PHP
<?php
// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once "/path/to/vendor/autoload.php";
use Twilio\Rest\Client;
// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
$sid = getenv("TWILIO_ACCOUNT_SID");
$token = getenv("TWILIO_AUTH_TOKEN");
$twilio = new Client($sid, $token);
$conversationSid = "CHxxxx";
$pageSize = 5;
$pageData = $twilio->conversations->v1
->conversations($conversationSid)
->messages->page([], $pageSize);
while($pageData){
foreach ($pageData as $record) {
echo $record->sid . "\n";
}
$pageData = $pageData->nextPage();
}
Ruby
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'rubygems'
require 'twilio-ruby'
# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
@client = Twilio::REST::Client.new(account_sid, auth_token)
def list_messages(conversation_sid, page_size)
begin
page = @client.conversations.v1
.conversations(conversation_sid)
.messages
.page(page_size: page_size)
while page
page.each do |message|
puts "Message SID: #{message.sid}"
end
page = page.next_page_url ? page.next_page : nil
end
rescue StandardError => e
puts "Error: #{e.message}"
end
end
list_messages('CHxxxx', 5)
Additional Information