How To Import Data From Your CRM Or Another External Source Into Conversation Memory

November 20, 2026
Written by

How To Import Data From Your CRM Or Another External Source Into Conversation Memory

Nobody likes spending too much time on the phone. But it's inevitable that you'll have to call someone about a business transaction, whether it's scheduling a doctor's appointment, placing online orders, getting service for a vehicle, or asking about tech support… and often, you'll have to repeat your account details every single time you make that call. Wouldn't it be nice if the business you were calling already had that information on file and ready to go?

This guide will help the owners of CRM and phone tree systems do just that. In this guide, you’ll learn how to sync customer data from your CRM into Twilio Conversation Memory.

With that external CRM data ready on demand, your voice agents, chat bots, and IVRs can pick up context immediately on incoming interactions, without making extra database calls while the customer waits.

Prerequisites

Before starting this tutorial, ensure you have:

  • A Twilio Account with a voice/messaging-capable number.
  • .NET 9 SDK or later
  • Twilio API Key & Secret with access to Conversation products.

Configuring Conversation Memory

To use Conversation Memory data, you will first need to configure a Conversation Memory Store in the Twilio console. Conversation Memory is only available in the new Twilio console, so navigate to OneConsole and log into your account.

From here, go to Data > Conversation Memory > Memory Stores and create a new Memory Store if you do not already have one.

create new memory store in the console
create new memory store in the console

The console gives you a setup checklist to get you started, but for now, you don't have to do anything else to set up. Just create a new Memory Store with the button on the console. To create your solution, you need your memory store ID, which is at the top left of the memory store screen. There should be a convenient button to copy-paste that ID. Keep that ID for the next step.

Memory Stores use machine learning, and you may have to agree to a warning before proceeding. Keep in mind that Conversation Memory is not intended for use with sensitive information.

Uploading a CSV

If your customer data is downloaded in CSV format, the next step can be done directly in the console. Simply follow the checklist to import your data, until you reach the Upload CSV option.

import csv graphic
import csv graphic

Some terms to understand in Twilio's dashboard, all of which can be tracked by Conversation Memory:

  • Profiles: The central entity tied to an end user (identified via phone number or customer ID)
  • Traits: Static or semi-static properties (e.g., VIPStatus: true, PreferredLanguage: "es", AccountTier: "Enterprise").
  • Observations: Key past events or recent CRM activities (e.g., "Order #9401 delayed in transit", "Opened ticket #1029 regarding billing").

In order for your CSV to be processed, there must be a line for either the customer phone number or email, which will be used as the unique identifier for each customer.

Once your file is uploaded, you can use AI to automatically map some values into Twilio's customer profiles, or, you can create traits and manually select how to map the data from your CSV into those traits. Traits can be in different data types: a string, integer, boolean, or an array of these types, though traits cannot contain nested arrays.

showing trait fields, custom and otherwise
showing trait fields, custom and otherwise

Once your traits are successfully mapped, click Complete, and Conversation Memory will import your CSV.

An automated solution for customer data import

Uploading a CSV via the dash is one solution. However, there is also an automated way to upload your data using API calls, if you'd rather do all your synchronization programmatically. The rest of this tutorial will discuss a solution using .NET 9 or higher. You can use these same APIs to make these calls in your programming language of choice.

Step 1: Set up and configure your environment

To follow along, open up your IDE of choice. Create a new C# Web API project. In Visual Studio Code, you can do this via the menus, or you can use the CLI:

dotnet new web -n TwilioCrmSync
cd TwilioCrmSync

Next you will need to install the DotNetEnv dependency so that your environment variables can be securely stored.

dotnet add package DotNetEnv

Create an .env file in your project folder. This will store important secure environmental variables for your project. Use the following text, replacing the placeholder values here with your real values. You can find all of this on your Twilio console. For your API key, you can create a new Standard API key on your Twilio dashboard. Be sure to copy down both the API key, and the API secret, when you create your key, as the API Secret will not be shown again.

TWILIO_API_KEY = API_KEY_HERE
TWILIO_API_SECRET = API_SECRET_HERE
TWILIO_MEMORY_STORE_ID = MEMORY_STORE_ID
If you are using git, be sure to include a .gitignore that ignores the .env file so that you are not storing any API keys in git.

If you are syncing with a real CRM, you may also need to include any secrets associated with that CRM store in this file. Adjust depending on your needs. For the purposes of this tutorial, you will be using mocked up data so no further API key is required. Proceed to creating the mocked up data.

Step 2: Mock up (or prepare) CRM data

Instead of a CSV upload, this time you will use mocked up customer data in JSON. This file could be replaced with whatever file format is created by your CRM. For the sake of demonstration, this will use fake customer data only.

Create a file named crm-customers.json and add the following:

[
 {
   "phone": "+15551234567",
   "firstName": "Dorothy",
   "lastName": "Parker",
   "email": "dorothy.parker@example.com",
   "city": "Austin",
   "state": "TX",
   "country": "US"
 },
 {
   "phone": "+15552345678",
   "firstName": "Prudence",
   "lastName": "Mortimer",
   "email": "prudence.mortimer@example.com",
   "city": "San Francisco",
   "state": "CA",
   "country": "US"
 },
 {
   "phone": "+15553456789",
   "firstName": "Priya",
   "lastName": "Summer",
   "email": "priya.summer@example.com",
   "city": "London",
   "state": "",
   "country": "GB"
 },
 {
   "phone": "+15554567890",
   "firstName": "Edith",
   "lastName": "Swan",
   "email": "edith.swan@example.com",
   "city": "New Orleans",
   "state": "LA",
   "country": "US"
 }
]

Step 3: Map CRM entities to Twilio Conversation Memory constructs

Your data will be extracted in whatever way your CRM formats that data. In order to map your data to Twilio's Conversations, you will need to create code that maps the CRM formatted data to Twilio's memory constructs.

Create a Models folder in your project. In this folder, create a file named CrmModels.cs . Paste the following code:

namespace TwilioCrmSync.Models;
public record CustomerProfile(
   string Phone,
   string FirstName,
   string LastName,
   string Email,
   string City,
   string State,
   string Country
);

This code will take in the information from the JSON file and serialize it into strings that Conversation Memory will then process.

Note that this code is using information structure that is already built in to Conversation Memory. If you want to add custom Traits, you can also do this using new Traits and Trait Groups in the console or using the Trait Groups API.

Step 4: Implement Profile lookup and creation

The next step in this tutorial is to make API calls to Conversations to post the CRM data.

Turn your attention to the Profiles API. You will be creating a profile using this call programmatically.

Create a Services folder, and in that folder, a file named CrmSyncService.cs. Paste in the following code:

using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using TwilioCrmSync.Models;
namespace TwilioCrmSync.Services;

public sealed class CrmSyncService
{
   private const string MemoryBaseUrl = "https://memory.twilio.com";
   private readonly HttpClient _http;
   private readonly string _storeId;
   private readonly string _crmBaseUrl;
   private readonly ILogger<CrmSyncService> _log;
   public CrmSyncService(HttpClient http, IConfiguration config, ILogger<CrmSyncService> log)
   {
       _http = http;
       _log = log;
       var apiKey = Environment.GetEnvironmentVariable("TWILIO_API_KEY")
           ?? throw new InvalidOperationException("TWILIO_API_KEY is not set.");
       var apiSecret = Environment.GetEnvironmentVariable("TWILIO_API_SECRET")
           ?? throw new InvalidOperationException("TWILIO_API_SECRET is not set.");
       _storeId = Environment.GetEnvironmentVariable("TWILIO_MEMORY_STORE_ID")
           ?? throw new InvalidOperationException("TWILIO_MEMORY_STORE_ID is not set.");
       _crmBaseUrl = config["CrmBaseUrl"] ?? "http://localhost:5000";
       var basicAuth = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{apiKey}:{apiSecret}"));
       _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", basicAuth);
   }
   public async Task<bool> SyncCustomerByPhoneAsync(string phone, CancellationToken ct = default)
   {
       var encodedPhone = Uri.EscapeDataString(phone);
       var customer = await _http.GetFromJsonAsync<CustomerProfile>(
           $"{_crmBaseUrl}/crm/customers/{encodedPhone}", ct);
       if (customer is null)
       {
           _log.LogWarning("No CRM record found for {Phone}", phone);
           return false;
       }
       var profileId = await EnsureProfileAsync(customer, ct);
       if (string.IsNullOrWhiteSpace(profileId))
           return false;
       return await UpdateProfileTraitsAsync(profileId, customer, ct);
   }
   private async Task<string?> EnsureProfileAsync(CustomerProfile customer, CancellationToken ct)
   {
       var lookupBody = JsonSerializer.Serialize(new { idType = "phone", value = customer.Phone });
       using var lookupReq = new HttpRequestMessage(
           HttpMethod.Post,
           $"{MemoryBaseUrl}/v1/Stores/{_storeId}/Profiles/Lookup")
       {
           Content = new StringContent(lookupBody, Encoding.UTF8, "application/json")
       };
       using var lookupResp = await _http.SendAsync(lookupReq, ct);
       if (lookupResp.IsSuccessStatusCode)
       {
           var json = await lookupResp.Content.ReadAsStringAsync(ct);
           using var doc = JsonDocument.Parse(json);
           if (doc.RootElement.TryGetProperty("profileId", out var pid))
               return pid.GetString();
       }
       var createBody = JsonSerializer.Serialize(new
       {
           traits = new
           {
               Contact = new { firstName = customer.FirstName, lastName = customer.LastName, phone = customer.Phone }
           }
       });
       using var createReq = new HttpRequestMessage(
           HttpMethod.Post,
           $"{MemoryBaseUrl}/v1/Stores/{_storeId}/Profiles")
       {
           Content = new StringContent(createBody, Encoding.UTF8, "application/json")
       };
       using var createResp = await _http.SendAsync(createReq, ct);
       if (!createResp.IsSuccessStatusCode)
       {
           var err = await createResp.Content.ReadAsStringAsync(ct);
           _log.LogError("Failed to create profile ({Status}): {Error}", createResp.StatusCode, err);
           return null;
       }
       var createJson = await createResp.Content.ReadAsStringAsync(ct);
       using var createDoc = JsonDocument.Parse(createJson);
       return createDoc.RootElement.TryGetProperty("id", out var newId) ? newId.GetString() : null;
   }
   private async Task<bool> UpdateProfileTraitsAsync(string profileId, CustomerProfile customer, CancellationToken ct)
   {
       var payload = JsonSerializer.Serialize(new
       {
           traits = new
           {
               Contact = new
               {
                   firstName = customer.FirstName,
                   lastName = customer.LastName,
                   phone = customer.Phone,
                   email = customer.Email,
                   city = customer.City,
                   state = customer.State,
                   country = customer.Country
               }
           }
       });
       using var req = new HttpRequestMessage(
           HttpMethod.Patch,
           $"{MemoryBaseUrl}/v1/Stores/{_storeId}/Profiles/{profileId}")
       {
           Content = new StringContent(payload, Encoding.UTF8, "application/json")
       };
       using var resp = await _http.SendAsync(req, ct);
       if (!resp.IsSuccessStatusCode)
       {
           var err = await resp.Content.ReadAsStringAsync(ct);
           _log.LogError("Trait update failed ({Status}): {Error}", resp.StatusCode, err);
           return false;
       }
       _log.LogInformation("Synced {FirstName} {LastName} ({Phone}) -> Profile {ProfileId}",
           customer.FirstName, customer.LastName, customer.Phone, profileId);
       return true;
   }
}

This code queries a mock CRM endpoint and gets the JSON data for the customers. If a profile exists that matches the phone number for this customer, it looks up that phone number first to avoid creating duplicate entries. Then it updates that profile with the information from the CRM data. If there is no profile for a customer, such as on your first run of the code, it will make a call to /v1/Stores/{_storeId}/Profiles and create a new profile for that customer.

Step 5: Sync external data to Conversation Memory

To finish the demonstration, you will create a sync service that writes CRM updates to the user's Conversation Memory Store.

To wire your synchronized data into Conversation Memory, you will update Program.cs to load crm-customers.json into memory. Then you expose the mock GET /crm/customers/{phone} endpoint for each customer, and add a POST /sync/{phone} endpoint to trigger synchronization.

Replace the code in your Program.cs with the following:

using System.Text.Json;
using DotNetEnv;
using TwilioCrmSync.Models;
using TwilioCrmSync.Services;

Env.TraversePath().Load();
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient<CrmSyncService>();
var app = builder.Build();
// Load mock CRM data from local JSON file
var jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var crmJson = File.ReadAllText("crm-customers.json");
var mockCustomers = JsonSerializer.Deserialize<List<CustomerProfile>>(crmJson, jsonOptions)
   ?? new List<CustomerProfile>();
// Mock CRM REST endpoint
app.MapGet("/crm/customers/{phone}", (string phone) =>
{
   var decodedPhone = Uri.UnescapeDataString(phone);
   var customer = mockCustomers.FirstOrDefault(c => c.Phone == decodedPhone);
   return customer is not null ? Results.Ok(customer) : Results.NotFound();
});
// Trigger CRM-to-Twilio sync for a specific phone number
app.MapPost("/sync/{phone}", async (string phone, CrmSyncService syncService) =>
{
   var decodedPhone = Uri.UnescapeDataString(phone);
   var success = await syncService.SyncCustomerByPhoneAsync(decodedPhone);
   return success
       ? Results.Ok(new { status = "synced", phone = decodedPhone })
       : Results.NotFound(new { status = "failed", phone = decodedPhone });
}).DisableAntiforgery();
app.Run();

Testing your CRM data

Now you can test your endpoint.

Run your code:

dotnet run

Now, you can trigger a sync for any of the four mock customers in crm-customers.json using curl:

curl -X POST http://localhost:5000/sync/%2B15551234567

%2B is the URL-encoded + sign in E.164 phone numbers. This, combined with the phone number, is your customer's unique identifier and is how the API decides which customer profile to create.

In URL paths, the + symbol must be percent-encoded as %2B so the server interprets it as part of the E.164 phone number (+15551234567) rather than a space character.

In your console, you should see {"status":"synced","phone":"+15551234567"} if the call went through correctly. Check your Twilio console to see how the data has been imported. If all goes well, you should see customer data imported into your memory store.

showing the profile IDs in the console
showing the profile IDs in the console

Conclusion

Now you know how to sync up data from your CRM to Twilio's Conversation Memory. What's next? Conversations and Conversation Memory give you a wide variety of options to make customer calls a smooth experience. Check out the documentation, or read more:

Amanda Lange is a .NET Engineer of Technical Content. She is here to teach how to create great things using C# and .NET programming. She can be reached at amlange [ at] twilio.com.