Back to SDKs
Javav1.3.0
Java SDK
The official Pharmako SDK for Java applications. Requires Java 11+.
Installation
Maven:
<dependency>
<groupId>com.pharmako</groupId>
<artifactId>pharmako-java</artifactId>
<version>1.3.0</version>
</dependency>Gradle:
implementation 'com.pharmako:pharmako-java:1.3.0'Quick Start
import com.pharmako.Pharmako;
import com.pharmako.model.Patient;
import com.pharmako.model.LabResult;
public class Example {
public static void main(String[] args) {
// Initialize the client
Pharmako client = Pharmako.builder()
.apiKey(System.getenv("PHARMAKO_API_KEY"))
.build();
// Fetch a patient
Patient patient = client.patients().get("patient_123");
System.out.println(patient.getName());
// List lab results
List<LabResult> labs = client.labs().list(
LabListParams.builder()
.patientId("patient_123")
.limit(10)
.build()
);
for (LabResult lab : labs) {
System.out.printf("%s: %s%n", lab.getTestName(), lab.getResult());
}
}
}Configuration
Customize the client with builder pattern configuration.
import com.pharmako.Pharmako;
import java.time.Duration;
// Full configuration
Pharmako client = Pharmako.builder()
.apiKey(System.getenv("PHARMAKO_API_KEY"))
.baseUrl("https://api.pharmako.dev/v1")
.timeout(Duration.ofSeconds(30))
.maxRetries(3)
.build();
// Sandbox environment
Pharmako sandboxClient = Pharmako.builder()
.apiKey(System.getenv("PHARMAKO_SANDBOX_KEY"))
.baseUrl("https://sandbox.pharmako.dev/v1")
.build();Patient Management
Complete patient lifecycle management with type-safe builders.
import com.pharmako.model.*;
import com.pharmako.params.*;
// Create a patient
PatientCreateParams createParams = PatientCreateParams.builder()
.firstName("John")
.lastName("Doe")
.dateOfBirth("1990-01-15")
.gender(Gender.MALE)
.email("john.doe@example.com")
.phone("+15555551234")
.build();
Patient patient = client.patients().create(createParams);
// Get a patient
Patient retrieved = client.patients().get("patient_123");
// Update a patient
PatientUpdateParams updateParams = PatientUpdateParams.builder()
.email("newemail@example.com")
.phone("+15555559999")
.build();
Patient updated = client.patients().update("patient_123", updateParams);
// List patients with pagination
PatientListParams listParams = PatientListParams.builder()
.limit(20)
.offset(0)
.build();
PagedList<Patient> patients = client.patients().list(listParams);
for (Patient p : patients.getData()) {
System.out.printf("%s %s%n", p.getFirstName(), p.getLastName());
}
// Delete a patient
client.patients().delete("patient_123");Async Support
Use CompletableFuture for non-blocking operations.
import java.util.concurrent.CompletableFuture;
// Async client
PharmakoAsync asyncClient = Pharmako.builderAsync()
.apiKey(System.getenv("PHARMAKO_API_KEY"))
.build();
// Non-blocking patient fetch
CompletableFuture<Patient> patientFuture =
asyncClient.patients().getAsync("patient_123");
// Chain async operations
patientFuture
.thenApply(patient -> {
System.out.println("Fetched: " + patient.getName());
return patient.getId();
})
.thenCompose(patientId ->
asyncClient.labs().listAsync(
LabListParams.builder()
.patientId(patientId)
.limit(10)
.build()
)
)
.thenAccept(labs -> {
labs.getData().forEach(lab ->
System.out.printf("%s: %s%n", lab.getTestName(), lab.getResult())
);
})
.exceptionally(ex -> {
System.err.println("Error: " + ex.getMessage());
return null;
});Error Handling
Structured exception handling with typed exceptions.
import com.pharmako.exception.*;
try {
Patient patient = client.patients().get("invalid_id");
} catch (NotFoundException e) {
System.err.printf("Patient not found: %s%n", e.getMessage());
} catch (AuthenticationException e) {
System.err.printf("Authentication failed: %s%n", e.getMessage());
} catch (ValidationException e) {
System.err.printf("Validation failed: %s%n", e.getMessage());
e.getErrors().forEach((field, messages) ->
System.err.printf(" %s: %s%n", field, String.join(", ", messages))
);
} catch (RateLimitException e) {
System.err.printf("Rate limited. Retry after %d seconds%n",
e.getRetryAfter());
} catch (ApiException e) {
System.err.printf("API error (%d): %s%n",
e.getStatusCode(), e.getMessage());
System.err.printf("Request ID: %s%n", e.getRequestId());
}Spring Boot Integration
Seamless integration with Spring Boot applications.
// application.properties
pharmako.api-key=${PHARMAKO_API_KEY}
pharmako.base-url=https://api.pharmako.dev/v1
pharmako.timeout=30s
// PharmakoConfig.java
@Configuration
public class PharmakoConfig {
@Value("${pharmako.api-key}")
private String apiKey;
@Value("${pharmako.base-url}")
private String baseUrl;
@Bean
public Pharmako pharmakoClient() {
return Pharmako.builder()
.apiKey(apiKey)
.baseUrl(baseUrl)
.build();
}
}
// PatientService.java
@Service
public class PatientService {
private final Pharmako pharmako;
@Autowired
public PatientService(Pharmako pharmako) {
this.pharmako = pharmako;
}
public Patient createPatient(PatientDTO dto) {
return pharmako.patients().create(
PatientCreateParams.builder()
.firstName(dto.getFirstName())
.lastName(dto.getLastName())
.dateOfBirth(dto.getDateOfBirth())
.build()
);
}
}Webhooks
Subscribe to real-time events with webhook endpoints.
import com.pharmako.model.Webhook;
import com.pharmako.params.WebhookCreateParams;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
// Create a webhook
WebhookCreateParams params = WebhookCreateParams.builder()
.url("https://your-app.com/webhooks/pharmako")
.events(List.of("patient.created", "patient.updated", "lab.completed"))
.secret("your_webhook_secret")
.build();
Webhook webhook = client.webhooks().create(params);
// List webhooks
List<Webhook> webhooks = client.webhooks().list();
// Verify webhook signature
public boolean verifyWebhookSignature(
String secret,
String signature,
String payload
) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
mac.init(secretKey);
byte[] hash = mac.doFinal(payload.getBytes());
String expectedSignature = bytesToHex(hash);
return MessageDigest.isEqual(
signature.getBytes(),
expectedSignature.getBytes()
);
}
// Handle webhook endpoint (Spring Boot)
@PostMapping("/webhooks/pharmako")
public ResponseEntity<Void> handleWebhook(
@RequestHeader("X-Pharmako-Signature") String signature,
@RequestBody String payload
) {
if (!verifyWebhookSignature(webhookSecret, signature, payload)) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
WebhookEvent event = objectMapper.readValue(payload, WebhookEvent.class);
switch (event.getType()) {
case "patient.created":
String patientId = event.getData().get("id").toString();
log.info("New patient: {}", patientId);
break;
case "lab.completed":
String orderId = event.getData().get("order_id").toString();
// Process lab results
break;
}
return ResponseEntity.ok().build();
}
// Delete a webhook
client.webhooks().delete("webhook_abc123");Document Management
Upload and manage patient documents with builder patterns.
import com.pharmako.model.Document;
import com.pharmako.params.DocumentCreateParams;
import java.io.File;
import java.nio.file.Files;
// Upload a document
File file = new File("lab_report.pdf");
DocumentCreateParams params = DocumentCreateParams.builder()
.patientId("patient_123")
.file(file)
.type("lab_report")
.description("Blood test results from 2024-11-30")
.build();
Document document = client.documents().create(params);
// Upload with metadata
Map<String, Object> metadata = new HashMap<>();
metadata.put("provider", "Dr. Smith");
metadata.put("date", "2024-11-30");
metadata.put("prescriptions", List.of("Medication A", "Medication B"));
DocumentCreateParams paramsWithMetadata = DocumentCreateParams.builder()
.patientId("patient_123")
.file(new File("prescription.pdf"))
.type("prescription")
.metadata(metadata)
.build();
Document prescriptionDoc = client.documents().create(paramsWithMetadata);
// List documents
DocumentListParams listParams = DocumentListParams.builder()
.patientId("patient_123")
.type("lab_report")
.limit(20)
.build();
PagedList<Document> documents = client.documents().list(listParams);
for (Document doc : documents.getData()) {
System.out.printf("%s: %s%n", doc.getType(), doc.getDescription());
System.out.printf(" Uploaded: %s%n", doc.getCreatedAt());
System.out.printf(" Size: %d bytes%n", doc.getSizeBytes());
}
// Retrieve a document
Document doc = client.documents().get("doc_xyz789");
// Download document content
byte[] content = client.documents().download("doc_xyz789");
Files.write(new File("downloaded_report.pdf").toPath(), content);
// Delete a document
client.documents().delete("doc_xyz789");