Back to SDKs
Gov1.8.0
Go SDK
The official Pharmako SDK for Go applications. Requires Go 1.18+.
Installation
go get github.com/pharmako/pharmako-goQuick Start
package main
import (
"context"
"fmt"
"os"
"github.com/pharmako/pharmako-go"
)
func main() {
// Initialize the client
client := pharmako.NewClient(os.Getenv("PHARMAKO_API_KEY"))
ctx := context.Background()
// Fetch a patient
patient, err := client.Patients.Get(ctx, "patient_123")
if err != nil {
panic(err)
}
fmt.Println(patient.Name)
// List lab results
labs, err := client.Labs.List(ctx, &pharmako.LabListParams{
PatientID: "patient_123",
Limit: 10,
})
if err != nil {
panic(err)
}
for _, lab := range labs.Data {
fmt.Printf("%s: %s\n", lab.TestName, lab.Result)
}
}Configuration
Customize the client with various configuration options.
import (
"time"
"github.com/pharmako/pharmako-go"
)
// Basic configuration
client := pharmako.NewClient(
os.Getenv("PHARMAKO_API_KEY"),
pharmako.WithBaseURL("https://api.pharmako.dev/v1"),
pharmako.WithTimeout(30 * time.Second),
pharmako.WithMaxRetries(3),
)
// Custom HTTP client
httpClient := &http.Client{
Timeout: 60 * time.Second,
}
client := pharmako.NewClient(
apiKey,
pharmako.WithHTTPClient(httpClient),
)Patient Management
Full CRUD operations for patient records with type safety.
// Create a patient
patient, err := client.Patients.Create(ctx, &pharmako.PatientCreateParams{
FirstName: "John",
LastName: "Doe",
DateOfBirth: "1990-01-15",
Gender: "male",
Email: "john.doe@example.com",
Phone: "+15555551234",
})
if err != nil {
log.Fatal(err)
}
// Get a patient
patient, err := client.Patients.Get(ctx, "patient_123")
// Update a patient
updated, err := client.Patients.Update(ctx, "patient_123", &pharmako.PatientUpdateParams{
Email: pharmako.String("newemail@example.com"),
Phone: pharmako.String("+15555559999"),
})
// List patients with pagination
patients, err := client.Patients.List(ctx, &pharmako.PatientListParams{
Limit: 20,
Offset: 0,
})
for _, patient := range patients.Data {
fmt.Printf("%s %s\n", patient.FirstName, patient.LastName)
}
// Delete a patient
err := client.Patients.Delete(ctx, "patient_123")Context & Cancellation
All SDK methods support context for timeouts and cancellation.
import (
"context"
"time"
)
// Request with timeout
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
patient, err := client.Patients.Get(ctx, "patient_123")
if err != nil {
if ctx.Err() == context.DeadlineExceeded {
log.Println("Request timed out")
}
return err
}
// Cancellable request
ctx, cancel := context.WithCancel(context.Background())
// Cancel in goroutine
go func() {
time.Sleep(2 * time.Second)
cancel()
}()
_, err := client.Labs.List(ctx, &pharmako.LabListParams{
Limit: 100,
})Error Handling
Robust error handling with typed error responses.
import "github.com/pharmako/pharmako-go/errors"
patient, err := client.Patients.Get(ctx, "invalid_id")
if err != nil {
switch e := err.(type) {
case *errors.NotFoundError:
log.Printf("Patient not found: %s", e.Message)
case *errors.AuthenticationError:
log.Printf("Auth failed: %s", e.Message)
case *errors.ValidationError:
log.Printf("Validation failed: %s", e.Message)
for field, messages := range e.Errors {
log.Printf(" %s: %v", field, messages)
}
case *errors.RateLimitError:
log.Printf("Rate limited. Retry after %d seconds", e.RetryAfter)
case *errors.APIError:
log.Printf("API error (%d): %s", e.StatusCode, e.Message)
log.Printf("Request ID: %s", e.RequestID)
default:
log.Printf("Unexpected error: %v", err)
}
return err
}Concurrency
The client is safe for concurrent use from multiple goroutines.
import "sync"
// Process multiple patients concurrently
patientIDs := []string{"patient_1", "patient_2", "patient_3"}
var wg sync.WaitGroup
results := make(chan *pharmako.Patient, len(patientIDs))
errors := make(chan error, len(patientIDs))
for _, id := range patientIDs {
wg.Add(1)
go func(patientID string) {
defer wg.Done()
patient, err := client.Patients.Get(ctx, patientID)
if err != nil {
errors <- err
return
}
results <- patient
}(id)
}
wg.Wait()
close(results)
close(errors)
// Process results
for patient := range results {
fmt.Printf("Fetched: %s %s\n", patient.FirstName, patient.LastName)
}
for err := range errors {
log.Printf("Error: %v", err)
}Webhooks
Subscribe to real-time events with webhook support.
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"io"
"net/http"
)
// Create a webhook
webhook, err := client.Webhooks.Create(ctx, &pharmako.WebhookCreateParams{
URL: "https://your-app.com/webhooks/pharmako",
Events: []string{
"patient.created",
"patient.updated",
"lab.completed",
},
Secret: "your_webhook_secret",
})
// List webhooks
webhooks, err := client.Webhooks.List(ctx, nil)
// Verify webhook signature
func verifyWebhookSignature(secret, signature string, payload []byte) bool {
mac := hmac.New(sha256.New, []byte(secret))
mac.Write(payload)
expectedSignature := hex.EncodeToString(mac.Sum(nil))
return hmac.Equal([]byte(signature), []byte(expectedSignature))
}
// Handle webhook endpoint
func handleWebhook(w http.ResponseWriter, r *http.Request) {
signature := r.Header.Get("X-Pharmako-Signature")
payload, _ := io.ReadAll(r.Body)
if !verifyWebhookSignature(webhookSecret, signature, payload) {
http.Error(w, "Invalid signature", http.StatusUnauthorized)
return
}
var event pharmako.WebhookEvent
json.Unmarshal(payload, &event)
switch event.Type {
case "patient.created":
patientID := event.Data["id"].(string)
log.Printf("New patient: %s", patientID)
case "lab.completed":
orderID := event.Data["order_id"].(string)
// Process lab results
}
w.WriteHeader(http.StatusOK)
}
// Delete a webhook
err := client.Webhooks.Delete(ctx, "webhook_abc123")Document Management
Upload and manage patient documents with full type safety.
import "os"
// Upload a document
file, err := os.Open("lab_report.pdf")
if err != nil {
log.Fatal(err)
}
defer file.Close()
document, err := client.Documents.Create(ctx, &pharmako.DocumentCreateParams{
PatientID: "patient_123",
File: file,
Type: "lab_report",
Description: "Blood test results from 2024-11-30",
})
// Upload with metadata
metadata := map[string]interface{}{
"provider": "Dr. Smith",
"date": "2024-11-30",
"prescriptions": []string{"Medication A", "Medication B"},
}
document, err := client.Documents.Create(ctx, &pharmako.DocumentCreateParams{
PatientID: "patient_123",
File: prescriptionFile,
Type: "prescription",
Metadata: metadata,
})
// List documents
documents, err := client.Documents.List(ctx, &pharmako.DocumentListParams{
PatientID: "patient_123",
Type: "lab_report",
Limit: 20,
})
for _, doc := range documents.Data {
fmt.Printf("%s: %s\n", doc.Type, doc.Description)
fmt.Printf(" Uploaded: %s\n", doc.CreatedAt)
fmt.Printf(" Size: %d bytes\n", doc.SizeBytes)
}
// Retrieve a document
document, err := client.Documents.Get(ctx, "doc_xyz789")
// Download document content
content, err := client.Documents.Download(ctx, "doc_xyz789")
if err != nil {
log.Fatal(err)
}
err = os.WriteFile("downloaded_report.pdf", content, 0644)
// Delete a document
err := client.Documents.Delete(ctx, "doc_xyz789")