The Twilio SDK SDK for .NET provides access to the Twilio SDK REST APIs from .NET applications.
Tip
Looking for a specific signature, model, enum, or error type? This SDK ships a generated, machine-readable SDK map — a lookup index of the SDK's entire C# surface. Consult it before grepping or scanning the source tree; it answers most contract questions directly and, when a source file is genuinely needed, names the exact one to open. Details under SDK map.
This is the public Twilio REST API., Manage configurations, conversations, participants, and communications. Create configurations to define capture rules and channel settings, then use conversations to group related communications., This is the public Twilio REST API., This is the public Twilio REST API., This is the public Twilio REST API., This is the public Twilio REST API., This is the public Twilio REST API., This is the public Twilio REST API., This is the public Twilio REST API., This is the public Twilio REST API., This is the public Twilio REST API., This is the reference API for the rest-proxy server., Insights Domain V3 API.
Add the .NET SDK as a project reference into your solution:
dotnet add reference <path-to-sdk>/src/TwilioSdk/TwilioSdk.csprojThe project takes its build settings from the files around it, so reference it in place. Building from source needs the .NET 10 SDK (C# 14); the package itself targets netstandard2.0.
The assembly embeds its PDB, so stack traces carry SDK file and line numbers.
dotnet pack src/TwilioSdk/TwilioSdk.csproj -c ReleaseRelease packs come from CI, where CI=true makes the build deterministic; to reproduce that locally add -p:ContinuousIntegrationBuild=true.
The generator never emits Directory.Build.targets, so a customer-owned one at the repo root is MSBuild's auto-imported customization seam. It imports after the props and the project body into every project under the root, so put SDK-only settings under <PropertyGroup Condition="'$(MSBuildProjectName)' == 'TwilioSdk'">.
It overrides every property the SDK reads when targets run (package metadata, Version, AssemblyVersion, compiler warnings, package references, which under central package management use VersionOverride). It cannot change values the SDK derives earlier: TargetFramework(s), AssemblyName and output paths stay generator settings; turning off GenerateDocumentationFile also needs <DocumentationFile />; a ContinuousIntegrationBuild set there also needs <DeterministicSourcePaths>true</DeterministicSourcePaths>.
The SDK's props files are a boundary: a parent repository's Directory.Build.props does not apply, while a parent Directory.Build.targets does.
APIMatic's delivery tools do not yet preserve Directory.Build.targets across regeneration — list it in .codegenignore when publishing to GitHub.
Register the client with IServiceCollection and resolve it from the container. The HttpClient is managed by IHttpClientFactory. Configure the client's behavior through TwilioSdkClientOptions.
services.AddTwilioSdkClient(options =>
{
options.AccountSidAuthToken = new BasicAuthCredentials { Username = "YOUR_USERNAME", Password = "YOUR_PASSWORD" };
options.Environment = ServerEnvironment.Production;
// TODO: configure more client options here
});Create the client by passing an HttpClient you manage yourself. Configure the client's behavior through TwilioSdkClientOptions.
var httpClient = new HttpClient();
// TODO: configure more client options here
var options = new TwilioSdkClientOptions
{
AccountSidAuthToken = new BasicAuthCredentials { Username = "YOUR_USERNAME", Password = "YOUR_PASSWORD" },
Environment = ServerEnvironment.Production,
};
var client = new TwilioSdkClient(httpClient, options);For code examples and error responses, see API Reference.
Every enum the spec declares is a sealed record with one public static readonly member per value (ConferenceEnumUpdateStatus.Completed), a JSON converter, and a Match that makes handling exhaustive: one on{Member} arm per known value, then otherwise, which receives the raw wire value the server sent when it is one this SDK does not declare.
var label = received.Match(onCompleted: () => "Completed", otherwise: raw => $"undeclared ({raw})");Prefer named arguments as above. The arms are positional, in the order the spec lists its values, and a regenerated SDK that adds or moves a value changes the Match signature: a positional call site compiled against the old shape either stops compiling or, if the assembly is not rebuilt, throws MissingMethodException at the first call, and a reordered value can rebind a positional argument to a different member without any diagnostic. Treat an added or moved enum value as a breaking change of that enum. Code that must survive regeneration untouched compares instead of matching: received == ConferenceEnumUpdateStatus.Completed or received.Is(rawValue) against a raw wire value; neither reopens construction.
A value the SDK does not declare still round-trips: IsKnownValue() tells you whether it is one of the generated members, and sending the instance back echoes the server's own casing. You cannot construct an undeclared value yourself — there is no public factory — so a typo cannot compile; resolve a raw value with ConferenceEnumUpdateStatus.TryGetKnownValue("completed", out var known).
A spec value whose name would collide with the enum's own name, with a member every enum inherits or generates (such as Value, Match or IsKnownValue), or with a member of object takes a Member suffix — a value value becomes ValueMember — and the other members keep their plain names.
This SDK ships a generated SDK map — sdk-map.md plus the map/ pages — a deterministic, lookup-oriented table of contents of the SDK's C# surface, generated by APIMatic alongside this SDK.
Read it before scanning the source. Whether you are an AI coding assistant or searching by hand, the map answers "what is the exact …" by lookup for every call-level contract, and for anything it does not carry it names the one file that does — so you never have to search the source tree:
sdk-map.md— the index: client construction, servers/auth, the options/retry reference, the SDK-wide defaults the operation rows rely on, and link tables intomap/.map/operations/— one page per controller: the exact C# signature, the return type, the error type with its typedTryGet…accessors, and pagination — plus, per operation, a Type sources table naming the file that declares every type that operation mentions.
Model shapes — record fields with their JSON wire names, enum member names and wire values, OneOf/AnyOf union variants — are not duplicated in the map. Take the path from the operation's Type sources table and read the declaring file; it is the single source of truth and cannot go stale against the code.
Each operation row states what is specific to that operation. The SDK-wide defaults are stated once in sdk-map.md — throw-only (no Result-style no-throw variants), no pagination, the four fixed RawError accessors, the Default server group — and a row appears only where its operation departs from one. A row silent on pagination is telling you that operation has none.
The HTTP verb and route, and the endpoint's behavioural prose, live on the operation itself, in the source file named at the top of its operations page. Read them there when something needs them — wiring a mock, reading a provider log, or settling a rule about what you must pass.
Workflow: look the fact up in the map → where the map leaves something ambiguous, open the one source file the row names → the compiler is the backstop (a name that isn't in the map won't build). Don't scan or grep the tree to find things — the map is the locator.
The map and the API Reference answer different questions, and the map is generated from this SDK's source so it stays in lockstep with the code it describes.
| Use | For |
|---|---|
sdk-map.md + map/ |
Traversing the SDK and working out its surface — locating the operation you need (this SDK exposes 898 operations), its exact signature and request record, the shape and JSON wire names of the models it takes and returns, which error type it throws and how to read it, and the source file behind any of it. This is the index to consume the SDK from, and the one to reach for first. |
api-reference.md |
Usage guidance for a single operation once you know which one you want — a runnable code sample, a link to its request record, and the error responses it can return. |
Operations throw when the server answers with an error status. TError is the operation's error type from the spec — RawError (the status code plus the raw body) when the spec declares none.
using TwilioSdk.Core.Exceptions; // the exception family
using TwilioSdk.Errors; // generated error types such as CreateLookupPhoneNumberOverridesError
using TwilioSdk.Requests; // request records such as CreateLookupPhoneNumberOverridesRequest
try
{
var response = await client.CreateLookupPhoneNumberOverrides(new CreateLookupPhoneNumberOverridesRequest
{
Field = "some example string",
PhoneNumber = "some example string",
});
}
catch (ApiException<CreateLookupPhoneNumberOverridesError> ex)
{
// "POST <server>/v2/PhoneNumbers/{PhoneNumber}/Overrides/{Field} returned 400 (BadRequest)."
Console.Error.WriteLine(ex.Message);
if (ex.Error.TryGetAccountsCallsRecordingsSidJson201041408Error1(
out var accountsCallsRecordingsSidJson201041408Error1))
{
// TODO: handle 'accountsCallsRecordingsSidJson201041408Error1' of type AccountsCallsRecordingsSidJson201041408Error1
}
}Everything the SDK raises for a call derives from SdkException, which carries the failed call's Method and RequestUri. Every message starts with that call, and the underlying cause is always InnerException.
| Exception | When | Extra members |
|---|---|---|
ApiException<TError> |
The server answered with an error status | Error, plus StatusCode, Headers and ContentType from ApiException |
ResponseDeserializationException |
A response body did not match the type the spec declares | TargetType, plus the ApiException members |
SdkConnectionException |
The request could not be sent, or the response body could not be read | |
SdkTimeoutException |
An attempt, the transport, or a Server-Sent Events stream went silent (derives from SdkConnectionException) |
Timeout |
AuthSchemeException |
A credential could not be applied — for example the OAuth2 token endpoint refused it | SchemeFailures |
Catch from specific to general: ApiException means the server answered, SdkConnectionException means it did not, and SdkException is everything the SDK raises. Your own cancellation surfaces as the usual OperationCanceledException, never wrapped.
Tip
Use a single TwilioSdkClient instance for the lifetime of your application and
reuse it across all requests. Creating a new instance per request might exhaust the
connection pool.
Tip
Let the SDK own timeouts. RetryOptions.Timeout bounds each attempt (default 100 s)
and a timed-out attempt is retried under the configured retry policy before it surfaces as
SdkTimeoutException; Retry-After response headers are honored when the server sends them.
Set HttpClient.Timeout to Timeout.InfiniteTimeSpan (or comfortably above
RetryOptions.Timeout) so the transport does not race the SDK — a transport-level timeout
surfaces as the same SdkTimeoutException but cannot be retried.
Tip
The SDK reads time only through TwilioSdkClientOptions.TimeProvider (default
TimeProvider.System): retry backoff, Retry-After, the SSE idle timeout, OAuth2 token
expiry and the logged request durations all follow it. Under AddTwilioSdkClient a
TimeProvider registered in the container is picked up automatically, and setting the
option explicitly wins. To fake time in your own tests use a provider that implements
timers, such as FakeTimeProvider from Microsoft.Extensions.TimeProvider.Testing, so
retries and idle timeouts advance with it.
This SDK is distributed under the MIT License.
Refer to the API reference for detailed information on available operations with code samples.
For further assistance, please contact support at support@twilio.com.