Back to SDKs
.NETv1.2.0
.NET SDK
The official Pharmako SDK for .NET applications. Supports .NET 6.0+.
Installation
dotnet add package Pharmako.SDKOr via Package Manager:
Install-Package Pharmako.SDKQuick Start
using Pharmako;
using Pharmako.Models;
// Initialize the client
var client = new PharmakoClient(
Environment.GetEnvironmentVariable("PHARMAKO_API_KEY")
);
// Fetch a patient
var patient = await client.Patients.GetAsync("patient_123");
Console.WriteLine(patient.Name);
// List lab results
var labs = await client.Labs.ListAsync(new LabListParams
{
PatientId = "patient_123",
Limit = 10
});
foreach (var lab in labs.Data)
{
Console.WriteLine($"{lab.TestName}: {lab.Result}");
}
// Create a webhook
var webhook = await client.Webhooks.CreateAsync(new WebhookCreateParams
{
Url = "https://your-app.com/webhooks",
Events = new[] { "patient.updated", "lab.completed" }
});Configuration
Configure the SDK with various options.
using Pharmako;
// Basic configuration
var client = new PharmakoClient(
apiKey: Environment.GetEnvironmentVariable("PHARMAKO_API_KEY"),
baseUrl: "https://api.pharmako.dev/v1",
timeout: TimeSpan.FromSeconds(30),
maxRetries: 3
);
// Configure HttpClient
var httpClient = new HttpClient
{
Timeout = TimeSpan.FromSeconds(60)
};
var clientWithHttpClient = new PharmakoClient(
apiKey: apiKey,
httpClient: httpClient
);Patient Management
Complete CRUD operations with async/await support.
using Pharmako.Models;
using Pharmako.Params;
// Create a patient
var createParams = new PatientCreateParams
{
FirstName = "John",
LastName = "Doe",
DateOfBirth = "1990-01-15",
Gender = Gender.Male,
Email = "john.doe@example.com",
Phone = "+15555551234"
};
var patient = await client.Patients.CreateAsync(createParams);
// Get a patient
var retrieved = await client.Patients.GetAsync("patient_123");
// Update a patient
var updateParams = new PatientUpdateParams
{
Email = "newemail@example.com",
Phone = "+15555559999"
};
var updated = await client.Patients.UpdateAsync("patient_123", updateParams);
// List patients with pagination
var listParams = new PatientListParams
{
Limit = 20,
Offset = 0
};
var patients = await client.Patients.ListAsync(listParams);
foreach (var p in patients.Data)
{
Console.WriteLine($"{p.FirstName} {p.LastName}");
}
// Delete a patient
await client.Patients.DeleteAsync("patient_123");ASP.NET Core Integration
The SDK integrates seamlessly with ASP.NET Core dependency injection.
// appsettings.json
{
"Pharmako": {
"ApiKey": "your_api_key_here",
"BaseUrl": "https://api.pharmako.dev/v1"
}
}
// Program.cs
builder.Services.AddPharmako(options =>
{
options.ApiKey = builder.Configuration["Pharmako:ApiKey"];
options.BaseUrl = builder.Configuration["Pharmako:BaseUrl"];
});
// PatientController.cs
[ApiController]
[Route("api/[controller]")]
public class PatientsController : ControllerBase
{
private readonly IPharmakoClient _pharmako;
public PatientsController(IPharmakoClient pharmako)
{
_pharmako = pharmako;
}
[HttpGet("{id}")]
public async Task<IActionResult> GetPatient(string id)
{
try
{
var patient = await _pharmako.Patients.GetAsync(id);
return Ok(patient);
}
catch (NotFoundException ex)
{
return NotFound(ex.Message);
}
}
}Error Handling
Comprehensive exception handling with typed exceptions.
using Pharmako.Exceptions;
try
{
var patient = await client.Patients.GetAsync("invalid_id");
}
catch (NotFoundException ex)
{
Console.WriteLine($"Patient not found: {ex.Message}");
}
catch (AuthenticationException ex)
{
Console.WriteLine($"Authentication failed: {ex.Message}");
}
catch (ValidationException ex)
{
Console.WriteLine($"Validation failed: {ex.Message}");
foreach (var error in ex.Errors)
{
Console.WriteLine($" {error.Key}: {string.Join(", ", error.Value)}");
}
}
catch (RateLimitException ex)
{
Console.WriteLine($"Rate limited. Retry after {ex.RetryAfter} seconds");
}
catch (ApiException ex)
{
Console.WriteLine($"API error ({ex.StatusCode}): {ex.Message}");
Console.WriteLine($"Request ID: {ex.RequestId}");
}Cancellation Support
All async methods support CancellationToken for graceful cancellation.
using System.Threading;
// Use cancellation token
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
try
{
var patient = await client.Patients.GetAsync(
"patient_123",
cancellationToken: cts.Token
);
}
catch (OperationCanceledException)
{
Console.WriteLine("Request was cancelled");
}
// Request timeout example
var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
var labs = await client.Labs.ListAsync(
new LabListParams { Limit = 100 },
cancellationToken: timeoutCts.Token
);Webhooks
Subscribe to real-time events with webhook endpoints.
using Pharmako.Models;
using Pharmako.Params;
using System.Security.Cryptography;
using System.Text;
// Create a webhook
var webhookParams = new WebhookCreateParams
{
Url = "https://your-app.com/webhooks/pharmako",
Events = new[] { "patient.created", "patient.updated", "lab.completed" },
Secret = "your_webhook_secret"
};
var webhook = await client.Webhooks.CreateAsync(webhookParams);
// List webhooks
var webhooks = await client.Webhooks.ListAsync();
// Verify webhook signature
public static bool VerifyWebhookSignature(
string secret,
string signature,
string payload
)
{
using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret));
var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(payload));
var expectedSignature = Convert.ToHexString(hash).ToLower();
return signature.Equals(expectedSignature, StringComparison.OrdinalIgnoreCase);
}
// Handle webhook endpoint (ASP.NET Core)
[HttpPost("webhooks/pharmako")]
public async Task<IActionResult> HandleWebhook()
{
var signature = Request.Headers["X-Pharmako-Signature"].FirstOrDefault();
using var reader = new StreamReader(Request.Body);
var payload = await reader.ReadToEndAsync();
if (!VerifyWebhookSignature(webhookSecret, signature, payload))
{
return Unauthorized();
}
var webhookEvent = JsonSerializer.Deserialize<WebhookEvent>(payload);
switch (webhookEvent.Type)
{
case "patient.created":
var patientId = webhookEvent.Data["id"].ToString();
_logger.LogInformation("New patient: {PatientId}", patientId);
break;
case "lab.completed":
var orderId = webhookEvent.Data["order_id"].ToString();
// Process lab results
break;
}
return Ok();
}
// Delete a webhook
await client.Webhooks.DeleteAsync("webhook_abc123");Document Management
Upload and manage patient documents with async/await.
using Pharmako.Models;
using Pharmako.Params;
using System.IO;
// Upload a document
using var fileStream = File.OpenRead("lab_report.pdf");
var documentParams = new DocumentCreateParams
{
PatientId = "patient_123",
File = fileStream,
Type = "lab_report",
Description = "Blood test results from 2024-11-30"
};
var document = await client.Documents.CreateAsync(documentParams);
// Upload with metadata
var metadata = new Dictionary<string, object>
{
["provider"] = "Dr. Smith",
["date"] = "2024-11-30",
["prescriptions"] = new[] { "Medication A", "Medication B" }
};
using var prescriptionStream = File.OpenRead("prescription.pdf");
var docWithMetadata = new DocumentCreateParams
{
PatientId = "patient_123",
File = prescriptionStream,
Type = "prescription",
Metadata = metadata
};
var prescriptionDoc = await client.Documents.CreateAsync(docWithMetadata);
// List documents
var listParams = new DocumentListParams
{
PatientId = "patient_123",
Type = "lab_report",
Limit = 20
};
var documents = await client.Documents.ListAsync(listParams);
foreach (var doc in documents.Data)
{
Console.WriteLine($"{doc.Type}: {doc.Description}");
Console.WriteLine($" Uploaded: {doc.CreatedAt}");
Console.WriteLine($" Size: {doc.SizeBytes} bytes");
}
// Retrieve a document
var retrievedDoc = await client.Documents.GetAsync("doc_xyz789");
// Download document content
var content = await client.Documents.DownloadAsync("doc_xyz789");
await File.WriteAllBytesAsync("downloaded_report.pdf", content);
// Delete a document
await client.Documents.DeleteAsync("doc_xyz789");