SendGrid API API in C#
SendGrid API API in C#
This guide shows you how to integrate the SendGrid API into your C# application. Email API for transactional and marketing email with templates and analytics.
Prerequisites
- C# installed on your system
- An SendGrid API API key (sign up at https://sendgrid.com)
- Basic familiarity with HTTP APIs
Installation
dotnet add package RestSharp
dotnet add package Newtonsoft.Json
Basic Usage
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program {
private static readonly string ApiKey = Environment.GetEnvironmentVariable("API_KEY") ?? "YOUR_API_KEY";
private static readonly string BaseUrl = "https://api.sendgrid.com";
static async Task Main(string[] args) {
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {ApiKey}");
var response = await client.GetAsync($"{BaseUrl}/v1/resources");
Console.WriteLine($"Status: {(int)response.StatusCode}");
var body = await response.Content.ReadAsStringAsync();
Console.WriteLine(body);
}
}
Error Handling
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program {
private static readonly string ApiKey = Environment.GetEnvironmentVariable("API_KEY") ?? "YOUR_API_KEY";
static async Task<string> CallApiWithRetry(string url, int maxRetries = 3) {
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {ApiKey}");
for (int attempt = 0; attempt < maxRetries; attempt++) {
try {
var response = await client.GetAsync(url);
if ((int)response.StatusCode == 429) {
Console.WriteLine("Rate limited. Waiting...");
await Task.Delay(60000);
continue;
}
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
} catch (Exception e) {
Console.WriteLine($"Attempt {attempt + 1} failed: {e.Message}");
if (attempt == maxRetries - 1) throw;
await Task.Delay((int)Math.Pow(2, attempt) * 1000);
}
}
throw new Exception("Max retries exceeded");
}
static async Task Main() {
var result = await CallApiWithRetry("https://api.sendgrid.com/v1/resources");
Console.WriteLine(result);
}
}
Advanced Usage
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
public class SendgridClient {
private readonly string _apiKey;
private readonly string _baseUrl;
private readonly HttpClient _httpClient;
public SendgridClient(string apiKey, string baseUrl = "https://api.sendgrid.com") {
_apiKey = apiKey;
_baseUrl = baseUrl.TrimEnd('/');
_httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
_httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
_httpClient.DefaultRequestHeaders.Add("User-Agent", "SendGrid API/1.0");
}
public async Task<string> ListResourcesAsync() {
var response = await _httpClient.GetAsync($"{_baseUrl}/v1/resources");
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
public async Task<string> CreateResourceAsync(object data) {
var json = JsonSerializer.Serialize(data);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync($"{_baseUrl}/v1/resources", content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
public async Task<string> GetResourceAsync(string id) {
var response = await _httpClient.GetAsync($"{_baseUrl}/v1/resources/{id}");
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
class Program {
static async Task Main() {
var client = new SendgridClient(Environment.GetEnvironmentVariable("API_KEY")!);
var resources = await client.ListResourcesAsync();
Console.WriteLine(resources);
}
}
Best Practices
- Store your API key in an environment variable, never in source code
- Implement retry logic with exponential backoff for 429 and 5xx errors
- Set reasonable timeouts (10-30 seconds) for all API calls
- Log request IDs from response headers for debugging
- Cache responses where appropriate to reduce API calls