docs: update SKILL.md and related references for Benchling integration

- Enhanced the description of the Benchling integration to clarify the use of the Python SDK and REST API for various registry entities and workflows.
- Updated the license to MIT and added allowed tools for better clarity on usage.
- Incremented the version number to 1.2 and improved installation instructions, including environment variable handling and authentication methods.
- Revised API endpoint references and authentication documentation to reflect best practices and ensure consistency across the integration guide.
This commit is contained in:
Timothy Kassis committed 2026-05-27 15:40:19 -07:00
1 parent e9fceed955
commit 761e83ddca
5 files changed
+417 -99

No files matched your search

+115 -61
View File
@@ -1,10 +1,11 @@
---
name: benchling-integration
description: Benchling R&D platform integration. Access registry (DNA, proteins), inventory, ELN entries, workflows via API, build Benchling Apps, query Data Warehouse, for lab data management automation.
license: Unknown
compatibility: Requires a Benchling account and API key
description: Benchling Python SDK and REST API integration for registry entities, inventory, ELN entries, workflows, Benchling Apps, and Data Warehouse queries. Use when automating lab data with benchling-sdk or the v2 API.
license: MIT
allowed-tools: Read Write Edit Bash
compatibility: Requires a Benchling account, tenant URL, and API key or OAuth app credentials. Install benchling-sdk with uv pip install.
metadata:
version: "1.0"
version: "1.2"
skill-author: K-Dense Inc.
---
@@ -12,7 +13,9 @@ metadata:
## Overview
Benchling is a cloud platform for life sciences R&D. Access registry entities (DNA, proteins), inventory, electronic lab notebooks, and workflows programmatically via Python SDK and REST API.
Benchling is a cloud platform for life sciences R&D. Access registry entities (DNA, RNA, proteins), inventory, electronic lab notebooks, and workflows programmatically via the Python SDK and REST API.
**Version note:** Examples target **benchling-sdk 1.25.0** (latest stable on PyPI). Docs: [benchling.com/sdk-docs](https://benchling.com/sdk-docs/). Platform guide: [docs.benchling.com](https://docs.benchling.com/).
## When to Use This Skill
@@ -30,46 +33,67 @@ This skill should be used when:
### 1. Authentication & Setup
**Python SDK Installation:**
```python
# Stable release
uv pip install benchling-sdk
# or with Poetry
poetry add benchling-sdk
**Python SDK installation:**
```bash
uv pip install "benchling-sdk==1.25.0"
```
**Authentication Methods:**
Preview builds (alpha; not for production):
```bash
uv pip install "benchling-sdk" --prerelease allow
```
**Environment variables (scoped reads only):**
Read only the named keys you need — never dump or iterate over the full environment:
```python
import os
tenant_url = os.environ.get("BENCHLING_TENANT_URL") # e.g. https://your-tenant.benchling.com
api_key = os.environ.get("BENCHLING_API_KEY")
if not tenant_url or not api_key:
raise ValueError("Set BENCHLING_TENANT_URL and BENCHLING_API_KEY")
```
Obtain an API key from **Profile Settings** in Benchling. For OAuth apps, use the [Developer Console](https://docs.benchling.com/docs/getting-started-benchling-apps) and store `BENCHLING_CLIENT_ID` / `BENCHLING_CLIENT_SECRET` separately.
**Authentication methods:**
API key (scripts and personal automation):
API Key Authentication (recommended for scripts):
```python
from benchling_sdk.benchling import Benchling
from benchling_sdk.auth.api_key_auth import ApiKeyAuth
benchling = Benchling(
url="https://your-tenant.benchling.com",
auth_method=ApiKeyAuth("your_api_key")
url=tenant_url,
auth_method=ApiKeyAuth(api_key),
)
```
OAuth Client Credentials (for apps):
OAuth client credentials (multi-user apps and production integrations):
```python
from benchling_sdk.benchling import Benchling
from benchling_sdk.auth.client_credentials_oauth2 import ClientCredentialsOAuth2
auth_method = ClientCredentialsOAuth2(
client_id="your_client_id",
client_secret="your_client_secret"
)
benchling = Benchling(
url="https://your-tenant.benchling.com",
auth_method=auth_method
url=tenant_url,
auth_method=ClientCredentialsOAuth2(
client_id=os.environ["BENCHLING_CLIENT_ID"],
client_secret=os.environ["BENCHLING_CLIENT_SECRET"],
),
)
```
**Key Points:**
- API keys are obtained from Profile Settings in Benchling
- Store credentials securely (use environment variables or password managers)
- All API requests require HTTPS
- Authentication permissions mirror user permissions in the UI
**Key points:**
- All API requests require HTTPS; network calls must target your tenant URL only
- Authentication permissions mirror UI permissions
- Verify credentials with `benchling.users.get_me()` before bulk operations
For detailed authentication information including OIDC and security best practices, refer to `references/authentication.md`.
@@ -140,7 +164,7 @@ total = sequences.estimated_count()
**Key Operations:**
- Create: `benchling.<entity_type>.create()`
- Read: `benchling.<entity_type>.get(id)` or `.list()`
- Read: `benchling.<entity_type>.get_by_id(id)` or `.list()`
- Update: `benchling.<entity_type>.update(id, update_object)`
- Archive: `benchling.<entity_type>.archive(id)`
@@ -260,16 +284,16 @@ updated_task = benchling.workflow_tasks.update(
**Asynchronous Operations:**
Some operations are asynchronous and return tasks:
Some operations are asynchronous and return tasks. The SDK default `max_wait_seconds` for polling is **600 seconds** (since SDK 1.11.0):
```python
# Wait for task completion
from benchling_sdk.helpers.tasks import wait_for_task
result = wait_for_task(
benchling,
task_id="task_abc123",
interval_wait_seconds=2,
max_wait_seconds=300
max_wait_seconds=300, # override for long-running serverless handlers
)
```
@@ -281,28 +305,61 @@ result = wait_for_task(
### 6. Events & Integration
Subscribe to Benchling events for real-time integrations using AWS EventBridge.
Subscribe to Benchling changes via **AWS EventBridge** (customer-owned bus) or **Webhooks** (recommended for new Benchling Apps). EventBridge delivers hydrated v2 API objects; webhooks use thinner payloads.
**Event Types:**
- Entity creation, update, archive
- Inventory transfers
- Workflow task status changes
- Entry creation and updates
- Results registration
**Common EventBridge `detail-type` values:**
- `v2.dnaSequence.created`, `v2.dnaSequence.updated`
- `v2.entity.registered`
- `v2.entry.created`, `v2.entry.updated`
- `v2.workflowTask.updated.status`
- `v2.request.created`
**Integration Pattern:**
1. Configure event routing to AWS EventBridge in Benchling settings
2. Create EventBridge rules to filter events
3. Route events to Lambda functions or other targets
4. Process events and update external systems
**Minimal EventBridge rule** (filter request creation by schema name):
**Use Cases:**
- Sync Benchling data to external databases
- Trigger downstream processes on workflow completion
- Send notifications on entity changes
- Audit trail logging
```json
{
"detail-type": ["v2.request.created"],
"detail": {
"schema": {
"name": ["Validated Request"]
}
}
}
```
Refer to Benchling's event documentation for event schemas and configuration.
**Lambda handler skeleton:**
```python
def handler(event, context):
detail_type = event["detail-type"]
detail = event["detail"]
if detail.get("deprecated"):
# Alert — migrate before Benchling removes this event type
pass
if detail.get("excludedProperties"):
# Payload exceeded 256 KB; re-fetch via detail["request"]["apiURL"]
pass
if detail_type == "v2.request.created":
request_id = (detail.get("request") or {}).get("id")
# Re-fetch authoritative state — events can be late or out of order
# request = benchling.requests.get_by_id(request_id)
return {"request_id": request_id}
return {"status": "ignored", "detail_type": detail_type}
```
**Setup flow:**
1. Tenant admin creates a subscription at `https://your-tenant.benchling.com/event-subscriptions`
2. Associate the AWS partner event source with a dedicated event bus immediately (within ~12 days)
3. Create rules + targets (Lambda, SQS, SNS) and grant invoke permissions
4. Validate with a CloudWatch Logs rule, then trigger a matching Benchling action
**Recovery:** EventBridge deliveries are not replayed. Use the [List Events API](https://benchling.com/api/reference#/Events/listEvents) for events up to ~2 weeks old after outages.
For payload schema, CloudFormation templates, SDK list/recovery examples, and validation steps, see `references/eventbridge.md`.
### 7. Data Warehouse & Analytics
@@ -334,9 +391,9 @@ The SDK automatically retries failed requests:
from benchling_sdk.retry import RetryStrategy
benchling = Benchling(
url="https://your-tenant.benchling.com",
auth_method=ApiKeyAuth("your_api_key"),
retry_strategy=RetryStrategy(max_retries=3)
url=tenant_url,
auth_method=ApiKeyAuth(api_key),
retry_strategy=RetryStrategy(max_retries=3),
)
```
@@ -374,11 +431,11 @@ The SDK handles unknown enum values and types gracefully:
### Security Considerations
- Never commit API keys to version control
- Use environment variables for credentials
- Rotate keys if compromised
- Grant minimal necessary permissions for apps
- Use OAuth for multi-user scenarios
- Never commit API keys or OAuth secrets to version control
- Read only named environment variables (`BENCHLING_TENANT_URL`, `BENCHLING_API_KEY`, etc.)
- Route network calls exclusively to your tenant URL
- Rotate keys if compromised; use OAuth for multi-user production apps
- Grant minimal necessary permissions for apps in the Developer Console
## Resources
@@ -389,13 +446,10 @@ Detailed reference documentation for in-depth information:
- **authentication.md** - Comprehensive authentication guide including OIDC, security best practices, and credential management
- **sdk_reference.md** - Detailed Python SDK reference with advanced patterns, examples, and all entity types
- **api_endpoints.md** - REST API endpoint reference for direct HTTP calls without the SDK
- **eventbridge.md** - EventBridge setup, event payload schema, rule examples, Lambda handler, validation, and recovery
Load these references as needed for specific integration requirements.
### scripts/
This skill currently includes example scripts that can be removed or replaced with custom automation scripts for your specific Benchling workflows.
## Common Use Cases
**1. Bulk Entity Import:**
@@ -11,9 +11,9 @@ Replace `{tenant}` with your Benchling tenant name.
## API Versioning
Current API version: `v2` (2025-10-07)
Current API version: `v2`
The API version is specified in the URL path. Benchling maintains backward compatibility within a major version.
The API version is specified in the URL path. Stable endpoints follow [Benchling stability guidelines](https://docs.benchling.com/docs/stability); `alpha` and `beta` endpoints may change with shorter notice.
## Authentication
@@ -173,18 +173,26 @@ curl -X GET \
- Share credentials via email or chat
- Store credentials in plain text files
**Example with Environment Variables:**
**Example with scoped environment variables:**
```python
import os
from dotenv import load_dotenv # python-dotenv package
from benchling_sdk.benchling import Benchling
from benchling_sdk.auth.api_key_auth import ApiKeyAuth
# Load from .env file (add .env to .gitignore!)
load_dotenv()
api_key = os.environ.get("BENCHLING_API_KEY")
tenant_url = os.environ.get("BENCHLING_TENANT_URL")
api_key = os.environ["BENCHLING_API_KEY"]
tenant = os.environ["BENCHLING_TENANT_URL"]
if not api_key or not tenant_url:
raise ValueError("Set BENCHLING_API_KEY and BENCHLING_TENANT_URL")
benchling = Benchling(
url=tenant_url,
auth_method=ApiKeyAuth(api_key),
)
```
Do not call `load_dotenv()` without filtering, and never iterate over `os.environ` to collect secrets.
### Credential Rotation
**API Key Rotation:**
@@ -323,30 +331,33 @@ except Exception as e:
## Multi-Tenant Considerations
If working with multiple Benchling tenants:
If working with multiple Benchling tenants, use separate named keys per tenant (for example `BENCHLING_PROD_API_KEY` and `BENCHLING_STAGING_API_KEY`) rather than reading the entire environment:
```python
# Configuration for multiple tenants
import os
from benchling_sdk.benchling import Benchling
from benchling_sdk.auth.api_key_auth import ApiKeyAuth
tenants = {
"production": {
"url": "https://prod.benchling.com",
"api_key": os.environ["PROD_API_KEY"]
"url": os.environ.get("BENCHLING_PROD_TENANT_URL"),
"api_key": os.environ.get("BENCHLING_PROD_API_KEY"),
},
"staging": {
"url": "https://staging.benchling.com",
"api_key": os.environ["STAGING_API_KEY"]
}
"url": os.environ.get("BENCHLING_STAGING_TENANT_URL"),
"api_key": os.environ.get("BENCHLING_STAGING_API_KEY"),
},
}
# Initialize clients
clients = {}
for name, config in tenants.items():
if not config["url"] or not config["api_key"]:
raise ValueError(f"Missing credentials for {name} tenant")
clients[name] = Benchling(
url=config["url"],
auth_method=ApiKeyAuth(config["api_key"])
auth_method=ApiKeyAuth(config["api_key"]),
)
# Use specific client
prod_sequences = clients["production"].dna_sequences.list()
```
@@ -0,0 +1,255 @@
# Benchling Events via AWS EventBridge
Real-time integrations that react to Benchling changes (entity registration, inventory transfers, workflow updates, and more).
**Official docs:**
- [Getting Started with Events](https://docs.benchling.com/docs/events-getting-started)
- [Events Reference (payloads and event types)](https://docs.benchling.com/docs/events-reference)
- [Events FAQs](https://docs.benchling.com/docs/events-faqs)
- [List Events API](https://benchling.com/api/reference#/Events/listEvents)
**Delivery methods:** Benchling supports **Webhooks** (recommended for new apps) and **AWS EventBridge** (customer-owned event bus). EventBridge payloads are **hydrated** (full v2 API objects in `detail`); webhooks use thinner payloads. See the getting-started guide for trade-offs.
---
## Setup checklist
1. **Tenant admin** enables Developer Platform access and opens [Event Subscriptions](https://your-tenant.benchling.com/event-subscriptions) (Feature settings → Developer Console → Events).
2. Create a subscription with:
- AWS account ID and region
- Event bus name (e.g. `benchling-integrations`)
- Event types to receive (see [Events Reference](https://docs.benchling.com/docs/events-reference))
3. **Immediately** associate the partner event source with a new EventBridge bus in AWS (within ~12 days or the source expires).
4. Create EventBridge rules with `detail-type` / `detail` filters and targets (Lambda, SQS, SNS, CloudWatch Logs).
5. Grant invoke permissions (`AWS::Lambda::Permission`, queue policies, etc.).
6. Validate with a CloudWatch Logs rule on the bus `source`, then trigger a test action in Benchling.
Subscription statuses: `Pending` (needs bus association), `Active`, `Expired` (resubscribe in Benchling).
---
## EventBridge event envelope
All EventBridge deliveries share this top-level shape. The resource body lives under `detail` under a key that varies by event (for example `entry`, `assayRun`, `dnaSequence`).
```json
{
"version": "0",
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"detail-type": "v2.dnaSequence.created",
"source": "aws.partner/benchling.com/your-tenant/your-subscription-name",
"account": "123456789012",
"time": "2025-10-20T14:30:00.000000+00:00",
"region": "us-west-2",
"resources": [],
"detail": {
"id": "evt_abc123",
"eventType": "v2.dnaSequence.created",
"createdAt": "2025-10-20T14:30:00.000000+00:00",
"deprecated": false,
"excludedProperties": [],
"schema": {
"id": "ts_abc123",
"name": "Plasmid"
},
"dnaSequence": {
"id": "seq_xyz789",
"name": "My Plasmid",
"apiURL": "https://your-tenant.benchling.com/api/v2/dna-sequences/seq_xyz789"
}
}
}
```
**Naming:** `detail-type` and `detail.eventType` follow `<version>.<resource>.<action>` (for example `v2.request.created`, `v2.workflowTask.updated.status`).
**Do not treat payloads as authoritative.** Events may arrive late or out of order. Re-fetch objects with the SDK/API when you need current state.
**Oversized events (>256 KB):** Dropped fields appear in `detail.excludedProperties`. Use `apiURL` on the resource object to fetch the full record.
---
## Minimal EventBridge rule (CloudFormation)
Route `v2.request.created` events for a specific request schema to a Lambda:
```yaml
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: Benchling request.created → Lambda
Parameters:
BenchlingEventBusName:
Type: String
Description: Partner event bus name from Benchling subscription
Resources:
RequestCreatedRule:
Type: AWS::Events::Rule
Properties:
Name: benchling-request-created
EventBusName: !Ref BenchlingEventBusName
State: ENABLED
EventPattern:
detail-type:
- v2.request.created
detail:
schema:
name:
- Validated Request
Targets:
- Id: HandleRequestCreated
Arn: !GetAtt HandleEventLambda.Arn
HandleEventLambda:
Type: AWS::Serverless::Function
Properties:
Handler: app.handler
Runtime: python3.12
CodeUri: src/
Timeout: 30
AllowEventBridgeInvoke:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !Ref HandleEventLambda
Principal: events.amazonaws.com
SourceArn: !GetAtt RequestCreatedRule.Arn
```
**Other filter examples** (from Benchling docs):
```json
{
"detail-type": ["v2.assayRun.updated"],
"detail": {
"updates": ["my_field"]
}
}
```
```json
{
"detail-type": ["v2.entity.registered"],
"detail": {
"entity": {
"schema": {
"id": ["ts_MySchemaId"]
}
}
}
}
```
---
## Lambda handler skeleton (Python)
```python
import json
import logging
import os
import boto3
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# Optional: re-fetch via SDK when payload may be stale or truncated
# from benchling_sdk.benchling import Benchling
# from benchling_sdk.auth.api_key_auth import ApiKeyAuth
#
# benchling = Benchling(
# url=os.environ["BENCHLING_TENANT_URL"],
# auth_method=ApiKeyAuth(os.environ["BENCHLING_API_KEY"]),
# )
def handler(event, context):
"""Process a single Benchling EventBridge delivery."""
detail_type = event.get("detail-type")
detail = event.get("detail") or {}
logger.info(
"benchling_event",
extra={
"detail_type": detail_type,
"event_id": detail.get("id"),
"benchling_event_type": detail.get("eventType"),
},
)
if detail.get("deprecated"):
logger.warning("deprecated_event_type: %s", detail_type)
if detail.get("excludedProperties"):
logger.warning(
"truncated_payload excluded=%s", detail.get("excludedProperties")
)
if detail_type == "v2.dnaSequence.created":
sequence = detail.get("dnaSequence") or {}
sequence_id = sequence.get("id")
if not sequence_id:
raise ValueError("missing dnaSequence.id in event detail")
# Prefer API lookup for authoritative data:
# seq = benchling.dna_sequences.get_by_id(sequence_id)
return {"status": "ok", "sequence_id": sequence_id}
if detail_type == "v2.workflowTask.updated.status":
task = detail.get("workflowTask") or {}
return {"status": "ok", "task_id": task.get("id")}
logger.info("no_handler_for_detail_type: %s", detail_type)
return {"status": "ignored", "detail_type": detail_type}
```
For serverless timeouts: SDK `wait_for_task` defaults to 600s — keep Lambda timeouts and EventBridge retry/DLQ settings aligned with expected processing time.
---
## Validation steps
1. **Subscription active:** In Benchling, subscription status is `Active` (not `Pending` or `Expired`).
2. **Partner source associated:** In AWS EventBridge → Partner event sources, source is associated with your bus.
3. **Log all events:** Add a catch-all rule targeting a CloudWatch log group, filtering on your bus `source` (shown in Benchling subscription UI).
4. **Trigger a test event:** Create or update an object matching your rule filter (for example register a DNA sequence).
5. **Inspect logs:** Confirm `detail-type`, `detail.id`, and resource IDs match expectations.
6. **Re-fetch check:** Call the SDK/API for the resource ID and confirm it matches your integration logic.
---
## Recovering missed events
Benchling does **not** replay EventBridge deliveries. After an outage:
1. Get the affected time window from Benchling support.
2. List historical events with the [List Events API](https://benchling.com/api/reference#/Events/listEvents) (retained ~2 weeks).
3. Re-route recovered events through your own infrastructure.
SDK example (ISO 8601 timestamp; see API reference for filters):
```python
events = benchling.events.list(
created_atgte="2025-10-20T00:00:00+00:00",
event_types="v2.dnaSequence.created",
)
for page in events:
for evt in page:
print(evt.event_type, evt.id)
```
---
## EventBridge vs Webhooks
| | EventBridge | Webhooks |
|---|-------------|----------|
| Setup | Benchling console + AWS bus/rules | Benchling App configuration |
| Payload | Hydrated v2 API objects | Thin IDs + metadata |
| Filtering | EventBridge `EventPattern` | App code |
| Permissions | Not permissioned at delivery | Inherited from app |
For new Benchling Apps, Benchling recommends **webhooks** unless you already standardize on EventBridge in AWS. See [Getting Started with Webhooks](https://docs.benchling.com/docs/getting-started-with-webhooks).
@@ -5,30 +5,28 @@
### Installation
```bash
# Stable release
pip install benchling-sdk
# Stable release (recommended)
uv pip install "benchling-sdk==1.25.0"
# With Poetry
poetry add benchling-sdk
# Pre-release/preview versions (not recommended for production)
pip install benchling-sdk --pre
poetry add benchling-sdk --allow-prereleases
# Preview builds — alpha functionality, not for production
uv pip install "benchling-sdk" --prerelease allow
```
### Requirements
- Python 3.7 or higher
- Python 3.9+ (3.12 supported since SDK 1.11.0; repo recommends 3.11+)
- API access enabled on your Benchling tenant
- Developer Platform access from your tenant admin (for apps and events)
### Basic Initialization
```python
import os
from benchling_sdk.benchling import Benchling
from benchling_sdk.auth.api_key_auth import ApiKeyAuth
benchling = Benchling(
url="https://your-tenant.benchling.com",
auth_method=ApiKeyAuth("your_api_key")
url=os.environ["BENCHLING_TENANT_URL"],
auth_method=ApiKeyAuth(os.environ["BENCHLING_API_KEY"]),
)
```
@@ -67,7 +65,7 @@ All resources follow a consistent CRUD pattern:
resource.create(CreateModel(...))
# Read (single)
resource.get(id="resource_id")
resource.get_by_id("resource_id")
# Read (list)
resource.list(optional_filters...)
@@ -106,7 +104,7 @@ sequence = benchling.dna_sequences.create(
**Read:**
```python
# Get by ID
seq = benchling.dna_sequences.get(sequence_id="seq_abc123")
seq = benchling.dna_sequences.get_by_id("seq_abc123")
print(f"{seq.name}: {len(seq.bases)} bp")
# List with filters
@@ -541,7 +539,7 @@ from benchling_sdk.errors import (
)
try:
sequence = benchling.dna_sequences.get(sequence_id="seq_invalid")
sequence = benchling.dna_sequences.get_by_id("seq_invalid")
except NotFoundError:
print("Sequence not found")
except UnauthorizedError:
@@ -663,7 +661,7 @@ The SDK handles unknown API values gracefully:
```python
# Unknown enum values are preserved
entity = benchling.dna_sequences.get("seq_abc")
entity = benchling.dna_sequences.get_by_id("seq_abc")
# Even if API returns new enum value not in SDK, it's preserved
# Unknown polymorphic types return UnknownType
@@ -733,13 +731,13 @@ for page in sequences:
### Common Issues
**Import Errors:**
**Import paths:**
```python
# Wrong
from benchling_sdk import Benchling # ImportError
# Correct
# Preferred (documented in getting started guide)
from benchling_sdk.benchling import Benchling
# Also valid in benchling-sdk 1.25+
from benchling_sdk import Benchling
```
**Field Validation:**