Developer-friendly & type-safe Csharp SDK specifically catered to leverage Novu API.
Novu API: Novu REST API. Please see https://docs.novu.co/api-reference for more details.
For more information about the API: Novu Documentation
To add the NuGet package to a .NET project:
dotnet add package NovuTo add a reference to a local instance of the SDK in a .NET project:
dotnet add reference src/Novu/Novu.csprojusing Novu;
using Novu.Models.Components;
using System.Collections.Generic;
var sdk = new NovuSDK(secretKey: "YOUR_SECRET_KEY_HERE");
var res = await sdk.TriggerAsync(triggerEventRequestDto: new TriggerEventRequestDto() {
WorkflowId = "workflow_identifier",
Payload = new Dictionary<string, object>() {
{ "comment_id", "string" },
{ "post", new Dictionary<string, object>() {
{ "text", "string" },
} },
},
Overrides = new Overrides() {},
To = To.CreateStr(
"SUBSCRIBER_ID"
),
Actor = Actor.CreateStr(
"<value>"
),
Context = new Dictionary<string, Context>() {
{ "key", Context.CreateStr(
"org-acme"
) },
},
});
// handle responseusing Novu;
using Novu.Models.Components;
var sdk = new NovuSDK(secretKey: "YOUR_SECRET_KEY_HERE");
var res = await sdk.CancelAsync(transactionId: "<id>");
// handle responseusing Novu;
using Novu.Models.Components;
using System.Collections.Generic;
var sdk = new NovuSDK(secretKey: "YOUR_SECRET_KEY_HERE");
var res = await sdk.BroadcastAsync(triggerEventToAllRequestDto: new TriggerEventToAllRequestDto() {
Name = "<value>",
Payload = new Dictionary<string, object>() {
{ "comment_id", "string" },
{ "post", new Dictionary<string, object>() {
{ "text", "string" },
} },
},
Overrides = new TriggerEventToAllRequestDtoOverrides() {
AdditionalProperties = new Dictionary<string, Dictionary<string, object>>() {
{ "fcm", new Dictionary<string, object>() {
{ "data", new Dictionary<string, object>() {
{ "key", "value" },
} },
} },
},
},
Actor = TriggerEventToAllRequestDtoActor.CreateSubscriberPayloadDto(
new SubscriberPayloadDto() {
FirstName = "John",
LastName = "Doe",
Email = "[email protected]",
Phone = "+1234567890",
Avatar = "https://example.com/avatar.jpg",
Locale = "en-US",
Timezone = "America/New_York",
SubscriberId = "<id>",
}
),
});
// handle responseusing Novu;
using Novu.Models.Components;
using System.Collections.Generic;
var sdk = new NovuSDK(secretKey: "YOUR_SECRET_KEY_HERE");
var res = await sdk.TriggerBulkAsync(bulkTriggerEventDto: new BulkTriggerEventDto() {
Events = new List<TriggerEventRequestDto>() {
new TriggerEventRequestDto() {
WorkflowId = "workflow_identifier",
Payload = new Dictionary<string, object>() {
{ "comment_id", "string" },
{ "post", new Dictionary<string, object>() {
{ "text", "string" },
} },
},
Overrides = new Overrides() {},
To = To.CreateStr(
"SUBSCRIBER_ID"
),
},
new TriggerEventRequestDto() {
WorkflowId = "workflow_identifier",
Payload = new Dictionary<string, object>() {
{ "comment_id", "string" },
{ "post", new Dictionary<string, object>() {
{ "text", "string" },
} },
},
Overrides = new Overrides() {},
To = To.CreateStr(
"SUBSCRIBER_ID"
),
},
new TriggerEventRequestDto() {
WorkflowId = "workflow_identifier",
Payload = new Dictionary<string, object>() {
{ "comment_id", "string" },
{ "post", new Dictionary<string, object>() {
{ "text", "string" },
} },
},
Overrides = new Overrides() {},
To = To.CreateStr(
"SUBSCRIBER_ID"
),
},
},
});
// handle responseThis SDK supports the following security scheme globally:
| Name | Type | Scheme |
|---|---|---|
SecretKey |
apiKey | API key |
To authenticate with the API the SecretKey parameter must be set when initializing the SDK client instance. For example:
using Novu;
using Novu.Models.Components;
using System.Collections.Generic;
var sdk = new NovuSDK(secretKey: "YOUR_SECRET_KEY_HERE");
var res = await sdk.TriggerAsync(triggerEventRequestDto: new TriggerEventRequestDto() {
WorkflowId = "workflow_identifier",
Payload = new Dictionary<string, object>() {
{ "comment_id", "string" },
{ "post", new Dictionary<string, object>() {
{ "text", "string" },
} },
},
Overrides = new Overrides() {},
To = To.CreateStr(
"SUBSCRIBER_ID"
),
Actor = Actor.CreateStr(
"<value>"
),
Context = new Dictionary<string, Context>() {
{ "key", Context.CreateStr(
"org-acme"
) },
},
});
// handle responseAvailable methods
- Track - Track activity and engagement events
- Create - Create a context
- List - List all contexts
- Update - Update a context
- Retrieve - Retrieve a context
- Delete - Delete a context
- GetTags - Get environment tags
- Create - Create an environment
- List - List all environments
- Update - Update an environment
- Delete - Delete an environment
- GetAll - List all integrations
- Create - Create an integration
- Update - Update an integration
- Delete - Delete an integration
- IntegrationsControllerAutoConfigureIntegration - Auto-configure an integration for inbound webhooks
- SetPrimary - Update integration as primary
- ListActive - List active integrations
- Create - Create a layout
- List - List all layouts
- Update - Update a layout
- Retrieve - Retrieve a layout
- Delete - Delete a layout
- Duplicate - Duplicate a layout
- GeneratePreview - Generate layout preview
- Usage - Get layout usage
- Get - List all messages
- Delete - Delete a message
- DeleteByTransactionId - Delete messages by transactionId
- Trigger - Trigger event
- Cancel - Cancel triggered event
- Broadcast - Broadcast event to all
- TriggerBulk - Bulk trigger event
- Search - Search subscribers
- Create - Create a subscriber
- Retrieve - Retrieve a subscriber
- Patch - Update a subscriber
- Delete - Delete a subscriber
- CreateBulk - Bulk create subscribers
- UpdateCredentials - Update provider credentials
- AppendCredentials - Upsert provider credentials
- DeleteCredentials - Delete provider credentials
- UpdateOnlineStatus - Update subscriber online status
- BulkUpdate - Bulk update subscriber preferences
- List - Retrieve subscriber subscriptions
- UpdateAction - Update notification action status
- MarkAll - Update all notifications state
- MarkAllAs - Update notifications state
- Feed - Retrieve subscriber notifications
- UnseenCount - Retrieve unseen notifications count
- List - List all topics
- Create - Create a topic
- Get - Retrieve a topic
- Update - Update a topic
- Delete - Delete a topic
- List - List topic subscriptions
- Create - Create topic subscriptions
- Delete - Delete topic subscriptions
- Get - Check topic subscriber
- Create - Create a translation
- Retrieve - Retrieve a translation
- Delete - Delete a translation
- Upload - Upload translation files
- Retrieve - Retrieve master translations JSON
- Import - Import master translations JSON
- Upload - Upload master translations JSON file
- Create - Create a workflow
- List - List all workflows
- Update - Update a workflow
- Get - Retrieve a workflow
- Delete - Delete a workflow
- Patch - Update a workflow
- Sync - Sync a workflow
- Retrieve - Retrieve workflow step
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply pass a RetryConfig to the call:
using Novu;
using Novu.Models.Components;
using System.Collections.Generic;
var sdk = new NovuSDK(secretKey: "YOUR_SECRET_KEY_HERE");
var res = await sdk.TriggerAsync(
retryConfig: new RetryConfig(
strategy: RetryConfig.RetryStrategy.BACKOFF,
backoff: new BackoffStrategy(
initialIntervalMs: 1L,
maxIntervalMs: 50L,
maxElapsedTimeMs: 100L,
exponent: 1.1
),
retryConnectionErrors: false
),
triggerEventRequestDto: new TriggerEventRequestDto() {
WorkflowId = "workflow_identifier",
Payload = new Dictionary<string, object>() {
{ "comment_id", "string" },
{ "post", new Dictionary<string, object>() {
{ "text", "string" },
} },
},
Overrides = new Overrides() {},
To = To.CreateStr(
"SUBSCRIBER_ID"
),
Actor = Actor.CreateStr(
"<value>"
),
Context = new Dictionary<string, Context>() {
{ "key", Context.CreateStr(
"org-acme"
) },
},
}
);
// handle responseIf you'd like to override the default retry strategy for all operations that support retries, you can use the RetryConfig optional parameter when intitializing the SDK:
using Novu;
using Novu.Models.Components;
using System.Collections.Generic;
var sdk = new NovuSDK(
retryConfig: new RetryConfig(
strategy: RetryConfig.RetryStrategy.BACKOFF,
backoff: new BackoffStrategy(
initialIntervalMs: 1L,
maxIntervalMs: 50L,
maxElapsedTimeMs: 100L,
exponent: 1.1
),
retryConnectionErrors: false
),
secretKey: "YOUR_SECRET_KEY_HERE"
);
var res = await sdk.TriggerAsync(triggerEventRequestDto: new TriggerEventRequestDto() {
WorkflowId = "workflow_identifier",
Payload = new Dictionary<string, object>() {
{ "comment_id", "string" },
{ "post", new Dictionary<string, object>() {
{ "text", "string" },
} },
},
Overrides = new Overrides() {},
To = To.CreateStr(
"SUBSCRIBER_ID"
),
Actor = Actor.CreateStr(
"<value>"
),
Context = new Dictionary<string, Context>() {
{ "key", Context.CreateStr(
"org-acme"
) },
},
});
// handle responseBaseException is the base exception class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
|---|---|---|
Message |
string | Error message |
Request |
HttpRequestMessage | HTTP request object |
Response |
HttpResponseMessage | HTTP response object |
Some exceptions in this SDK include an additional Payload field, which will contain deserialized custom error data when present. Possible exceptions are listed in the Error Classes section.
using Novu;
using Novu.Models.Components;
using Novu.Models.Errors;
using System.Collections.Generic;
var sdk = new NovuSDK(secretKey: "YOUR_SECRET_KEY_HERE");
try
{
var res = await sdk.TriggerAsync(triggerEventRequestDto: new TriggerEventRequestDto() {
WorkflowId = "workflow_identifier",
Payload = new Dictionary<string, object>() {
{ "comment_id", "string" },
{ "post", new Dictionary<string, object>() {
{ "text", "string" },
} },
},
Overrides = new Overrides() {},
To = To.CreateStr(
"SUBSCRIBER_ID"
),
Actor = Actor.CreateStr(
"<value>"
),
Context = new Dictionary<string, Context>() {
{ "key", Context.CreateStr(
"org-acme"
) },
},
});
// handle response
}
catch (BaseException ex) // all SDK exceptions inherit from BaseException
{
// ex.ToString() provides a detailed error message
System.Console.WriteLine(ex);
// Base exception fields
HttpRequestMessage request = ex.Request;
HttpResponseMessage response = ex.Response;
var statusCode = (int)response.StatusCode;
var responseBody = ex.Body;
if (ex is PayloadValidationExceptionDto) // different exceptions may be thrown depending on the method
{
// Check error data fields
PayloadValidationExceptionDtoPayload payload = ex.Payload;
double StatusCode = payload.StatusCode;
string Timestamp = payload.Timestamp;
// ...
}
// An underlying cause may be provided
if (ex.InnerException != null)
{
Exception cause = ex.InnerException;
}
}
catch (System.Net.Http.HttpRequestException ex)
{
// Check ex.InnerException for Network connectivity errors
}Primary exceptions:
BaseException: The base class for HTTP error responses.ErrorDto: *ValidationErrorDto: Unprocessable Entity. Status code422. *
Less common exceptions (5)
-
System.Net.Http.HttpRequestException: Network connectivity error. For more details about the underlying cause, inspect theex.InnerException. -
Inheriting from
BaseException:PayloadValidationExceptionDto: Status code400. Applicable to 3 of 80 methods.*SubscriberResponseDto: Created. Status code409. Applicable to 1 of 80 methods.*TopicResponseDto: OK. Status code409. Applicable to 1 of 80 methods.*ResponseValidationError: Thrown when the response data could not be deserialized into the expected type.
* Refer to the relevant documentation to determine whether an exception applies to a specific operation.
You can override the default server globally by passing a server index to the serverIndex: int optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the indexes associated with the available servers:
| # | Server | Description |
|---|---|---|
| 0 | https://api.novu.co |
|
| 1 | https://eu.api.novu.co |
using Novu;
using Novu.Models.Components;
using System.Collections.Generic;
var sdk = new NovuSDK(
serverIndex: 0,
secretKey: "YOUR_SECRET_KEY_HERE"
);
var res = await sdk.TriggerAsync(triggerEventRequestDto: new TriggerEventRequestDto() {
WorkflowId = "workflow_identifier",
Payload = new Dictionary<string, object>() {
{ "comment_id", "string" },
{ "post", new Dictionary<string, object>() {
{ "text", "string" },
} },
},
Overrides = new Overrides() {},
To = To.CreateStr(
"SUBSCRIBER_ID"
),
Actor = Actor.CreateStr(
"<value>"
),
Context = new Dictionary<string, Context>() {
{ "key", Context.CreateStr(
"org-acme"
) },
},
});
// handle responseThe default server can also be overridden globally by passing a URL to the serverUrl: string optional parameter when initializing the SDK client instance. For example:
using Novu;
using Novu.Models.Components;
using System.Collections.Generic;
var sdk = new NovuSDK(
serverUrl: "https://eu.api.novu.co",
secretKey: "YOUR_SECRET_KEY_HERE"
);
var res = await sdk.TriggerAsync(triggerEventRequestDto: new TriggerEventRequestDto() {
WorkflowId = "workflow_identifier",
Payload = new Dictionary<string, object>() {
{ "comment_id", "string" },
{ "post", new Dictionary<string, object>() {
{ "text", "string" },
} },
},
Overrides = new Overrides() {},
To = To.CreateStr(
"SUBSCRIBER_ID"
),
Actor = Actor.CreateStr(
"<value>"
),
Context = new Dictionary<string, Context>() {
{ "key", Context.CreateStr(
"org-acme"
) },
},
});
// handle responseThe C# SDK makes API calls using an ISpeakeasyHttpClient that wraps the native
HttpClient. This
client provides the ability to attach hooks around the request lifecycle that can be used to modify the request or handle
errors and response.
The ISpeakeasyHttpClient interface allows you to either use the default SpeakeasyHttpClient that comes with the SDK,
or provide your own custom implementation with customized configuration such as custom message handlers, timeouts,
connection pooling, and other HTTP client settings.
The following example shows how to create a custom HTTP client with request modification and error handling:
using Novu;
using Novu.Utils;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
// Create a custom HTTP client
public class CustomHttpClient : ISpeakeasyHttpClient
{
private readonly ISpeakeasyHttpClient _defaultClient;
public CustomHttpClient()
{
_defaultClient = new SpeakeasyHttpClient();
}
public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken? cancellationToken = null)
{
// Add custom header and timeout
request.Headers.Add("x-custom-header", "custom value");
request.Headers.Add("x-request-timeout", "30");
try
{
var response = await _defaultClient.SendAsync(request, cancellationToken);
// Log successful response
Console.WriteLine($"Request successful: {response.StatusCode}");
return response;
}
catch (Exception error)
{
// Log error
Console.WriteLine($"Request failed: {error.Message}");
throw;
}
}
public void Dispose()
{
_httpClient?.Dispose();
_defaultClient?.Dispose();
}
}
// Use the custom HTTP client with the SDK
var customHttpClient = new CustomHttpClient();
var sdk = new Novu(client: customHttpClient);You can also provide a completely custom HTTP client with your own configuration:
using Novu.Utils;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
// Custom HTTP client with custom configuration
public class AdvancedHttpClient : ISpeakeasyHttpClient
{
private readonly HttpClient _httpClient;
public AdvancedHttpClient()
{
var handler = new HttpClientHandler()
{
MaxConnectionsPerServer = 10,
// ServerCertificateCustomValidationCallback = customCertValidation, // Custom SSL validation if needed
};
_httpClient = new HttpClient(handler)
{
Timeout = TimeSpan.FromSeconds(30)
};
}
public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken? cancellationToken = null)
{
return await _httpClient.SendAsync(request, cancellationToken ?? CancellationToken.None);
}
public void Dispose()
{
_httpClient?.Dispose();
}
}
var sdk = Novu.Builder()
.WithClient(new AdvancedHttpClient())
.Build();For simple debugging, you can enable request/response logging by implementing a custom client:
public class LoggingHttpClient : ISpeakeasyHttpClient
{
private readonly ISpeakeasyHttpClient _innerClient;
public LoggingHttpClient(ISpeakeasyHttpClient innerClient = null)
{
_innerClient = innerClient ?? new SpeakeasyHttpClient();
}
public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken? cancellationToken = null)
{
// Log request
Console.WriteLine($"Sending {request.Method} request to {request.RequestUri}");
var response = await _innerClient.SendAsync(request, cancellationToken);
// Log response
Console.WriteLine($"Received {response.StatusCode} response");
return response;
}
public void Dispose() => _innerClient?.Dispose();
}
var sdk = new Novu(client: new LoggingHttpClient());The SDK also provides built-in hook support through the SDKConfiguration.Hooks system, which automatically handles
BeforeRequestAsync, AfterSuccessAsync, and AfterErrorAsync hooks for advanced request lifecycle management.
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.