benchling-integration

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Benchling Integration

Benchling集成

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是面向生命科学研发的云平台。可通过Python SDK和REST API以编程方式访问注册实体(DNA、RNA、蛋白质)、库存、电子实验记录本和工作流。

When to Use This Skill

何时使用此技能

This skill should be used when:
  • Working with Benchling's Python SDK or REST API
  • Managing biological sequences (DNA, RNA, proteins) and registry entities
  • Automating inventory operations (samples, containers, locations, transfers)
  • Creating or querying electronic lab notebook entries
  • Building workflow automations or Benchling Apps
  • Syncing data between Benchling and external systems
  • Querying the Benchling Data Warehouse for analytics
  • Setting up event-driven integrations with AWS EventBridge
在以下场景中应使用此技能:
  • 使用Benchling的Python SDK或REST API时
  • 管理生物序列(DNA、RNA、蛋白质)和注册实体时
  • 自动化库存操作(样本、容器、位置、转移)时
  • 创建或查询电子实验记录本条目时
  • 构建工作流自动化或Benchling应用时
  • 在Benchling与外部系统之间同步数据时
  • 查询Benchling数据仓库以进行分析时
  • 设置与AWS EventBridge的事件驱动集成时

Core Capabilities

核心功能

1. Authentication & Setup

1. 身份验证与设置

Python SDK Installation:
python
undefined
Python SDK安装:
python
undefined

Stable release

Stable release

uv pip install benchling-sdk
uv pip install benchling-sdk

or with Poetry

or with Poetry

poetry add benchling-sdk

**Authentication Methods:**

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")
)
OAuth Client Credentials (for apps):
python
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
)
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
For detailed authentication information including OIDC and security best practices, refer to
references/authentication.md
.
poetry add benchling-sdk

**身份验证方法:**

API密钥身份验证(推荐用于脚本):
```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")
)
OAuth客户端凭据(用于应用):
python
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
)
关键点:
  • API密钥可从Benchling的个人资料设置中获取
  • 安全存储凭据(使用环境变量或密码管理器)
  • 所有API请求均需使用HTTPS
  • 身份验证权限与UI中的用户权限一致
如需包含OIDC和安全最佳实践的详细身份验证信息,请参考
references/authentication.md

2. Registry & Entity Management

2. 注册库与实体管理

Registry entities include DNA sequences, RNA sequences, AA sequences, custom entities, and mixtures. The SDK provides typed classes for creating and managing these entities.
Creating DNA Sequences:
python
from benchling_sdk.models import DnaSequenceCreate

sequence = benchling.dna_sequences.create(
    DnaSequenceCreate(
        name="My Plasmid",
        bases="ATCGATCG",
        is_circular=True,
        folder_id="fld_abc123",
        schema_id="ts_abc123",  # optional
        fields=benchling.models.fields({"gene_name": "GFP"})
    )
)
Registry Registration:
To register an entity directly upon creation:
python
sequence = benchling.dna_sequences.create(
    DnaSequenceCreate(
        name="My Plasmid",
        bases="ATCGATCG",
        is_circular=True,
        folder_id="fld_abc123",
        entity_registry_id="src_abc123",  # Registry to register in
        naming_strategy="NEW_IDS"  # or "IDS_FROM_NAMES"
    )
)
Important: Use either
entity_registry_id
OR
naming_strategy
, never both.
Updating Entities:
python
from benchling_sdk.models import DnaSequenceUpdate

updated = benchling.dna_sequences.update(
    sequence_id="seq_abc123",
    dna_sequence=DnaSequenceUpdate(
        name="Updated Plasmid Name",
        fields=benchling.models.fields({"gene_name": "mCherry"})
    )
)
Unspecified fields remain unchanged, allowing partial updates.
Listing and Pagination:
python
undefined
注册实体包括DNA序列、RNA序列、氨基酸(AA)序列、自定义实体和混合物。SDK提供了用于创建和管理这些实体的类型化类。
创建DNA序列:
python
from benchling_sdk.models import DnaSequenceCreate

sequence = benchling.dna_sequences.create(
    DnaSequenceCreate(
        name="My Plasmid",
        bases="ATCGATCG",
        is_circular=True,
        folder_id="fld_abc123",
        schema_id="ts_abc123",  # optional
        fields=benchling.models.fields({"gene_name": "GFP"})
    )
)
注册库注册:
要在创建实体时直接将其注册到注册库:
python
sequence = benchling.dna_sequences.create(
    DnaSequenceCreate(
        name="My Plasmid",
        bases="ATCGATCG",
        is_circular=True,
        folder_id="fld_abc123",
        entity_registry_id="src_abc123",  # 要注册到的注册库
        naming_strategy="NEW_IDS"  # 或 "IDS_FROM_NAMES"
    )
)
注意: 请使用
entity_registry_id
naming_strategy
中的一个,切勿同时使用两者。
更新实体:
python
from benchling_sdk.models import DnaSequenceUpdate

updated = benchling.dna_sequences.update(
    sequence_id="seq_abc123",
    dna_sequence=DnaSequenceUpdate(
        name="Updated Plasmid Name",
        fields=benchling.models.fields({"gene_name": "mCherry"})
    )
)
未指定的字段将保持不变,支持部分更新。
列表与分页:
python
undefined

List all DNA sequences (returns a generator)

列出所有DNA序列(返回生成器)

sequences = benchling.dna_sequences.list() for page in sequences: for seq in page: print(f"{seq.name} ({seq.id})")
sequences = benchling.dna_sequences.list() for page in sequences: for seq in page: print(f"{seq.name} ({seq.id})")

Check total count

查看总数

total = sequences.estimated_count()

**Key Operations:**
- Create: `benchling.<entity_type>.create()`
- Read: `benchling.<entity_type>.get(id)` or `.list()`
- Update: `benchling.<entity_type>.update(id, update_object)`
- Archive: `benchling.<entity_type>.archive(id)`

Entity types: `dna_sequences`, `rna_sequences`, `aa_sequences`, `custom_entities`, `mixtures`

For comprehensive SDK reference and advanced patterns, refer to `references/sdk_reference.md`.
total = sequences.estimated_count()

**核心操作:**
- 创建:`benchling.<entity_type>.create()`
- 读取:`benchling.<entity_type>.get(id)` 或 `.list()`
- 更新:`benchling.<entity_type>.update(id, update_object)`
- 归档:`benchling.<entity_type>.archive(id)`

实体类型包括:`dna_sequences`, `rna_sequences`, `aa_sequences`, `custom_entities`, `mixtures`

如需完整的SDK参考和高级模式,请参考`references/sdk_reference.md`。

3. Inventory Management

3. 库存管理

Manage physical samples, containers, boxes, and locations within the Benchling inventory system.
Creating Containers:
python
from benchling_sdk.models import ContainerCreate

container = benchling.containers.create(
    ContainerCreate(
        name="Sample Tube 001",
        schema_id="cont_schema_abc123",
        parent_storage_id="box_abc123",  # optional
        fields=benchling.models.fields({"concentration": "100 ng/μL"})
    )
)
Managing Boxes:
python
from benchling_sdk.models import BoxCreate

box = benchling.boxes.create(
    BoxCreate(
        name="Freezer Box A1",
        schema_id="box_schema_abc123",
        parent_storage_id="loc_abc123"
    )
)
Transferring Items:
python
undefined
在Benchling库存系统中管理物理样本、容器、盒子和位置。
创建容器:
python
from benchling_sdk.models import ContainerCreate

container = benchling.containers.create(
    ContainerCreate(
        name="Sample Tube 001",
        schema_id="cont_schema_abc123",
        parent_storage_id="box_abc123",  # optional
        fields=benchling.models.fields({"concentration": "100 ng/μL"})
    )
)
管理盒子:
python
from benchling_sdk.models import BoxCreate

box = benchling.boxes.create(
    BoxCreate(
        name="Freezer Box A1",
        schema_id="box_schema_abc123",
        parent_storage_id="loc_abc123"
    )
)
转移物品:
python
undefined

Transfer a container to a new location

将容器转移到新位置

transfer = benchling.containers.transfer( container_id="cont_abc123", destination_id="box_xyz789" )

**Key Inventory Operations:**
- Create containers, boxes, locations, plates
- Update inventory item properties
- Transfer items between locations
- Check in/out items
- Batch operations for bulk transfers
transfer = benchling.containers.transfer( container_id="cont_abc123", destination_id="box_xyz789" )

**核心库存操作:**
- 创建容器、盒子、位置、板
- 更新库存物品属性
- 在不同位置之间转移物品
- 物品的借出与归还
- 批量转移的批量操作

4. Notebook & Documentation

4. 实验记录本与文档

Interact with electronic lab notebook (ELN) entries, protocols, and templates.
Creating Notebook Entries:
python
from benchling_sdk.models import EntryCreate

entry = benchling.entries.create(
    EntryCreate(
        name="Experiment 2025-10-20",
        folder_id="fld_abc123",
        schema_id="entry_schema_abc123",
        fields=benchling.models.fields({"objective": "Test gene expression"})
    )
)
Linking Entities to Entries:
python
undefined
与电子实验记录本(ELN)条目、实验方案和模板进行交互。
创建实验记录本条目:
python
from benchling_sdk.models import EntryCreate

entry = benchling.entries.create(
    EntryCreate(
        name="Experiment 2025-10-20",
        folder_id="fld_abc123",
        schema_id="entry_schema_abc123",
        fields=benchling.models.fields({"objective": "Test gene expression"})
    )
)
将实体链接到条目:
python
undefined

Add references to entities in an entry

在条目中添加实体引用

entry_link = benchling.entry_links.create( entry_id="entry_abc123", entity_id="seq_xyz789" )

**Key Notebook Operations:**
- Create and update lab notebook entries
- Manage entry templates
- Link entities and results to entries
- Export entries for documentation
entry_link = benchling.entry_links.create( entry_id="entry_abc123", entity_id="seq_xyz789" )

**核心实验记录本操作:**
- 创建和更新实验记录本条目
- 管理条目模板
- 将实体和结果链接到条目
- 导出条目用于文档记录

5. Workflows & Automation

5. 工作流与自动化

Automate laboratory processes using Benchling's workflow system.
Creating Workflow Tasks:
python
from benchling_sdk.models import WorkflowTaskCreate

task = benchling.workflow_tasks.create(
    WorkflowTaskCreate(
        name="PCR Amplification",
        workflow_id="wf_abc123",
        assignee_id="user_abc123",
        fields=benchling.models.fields({"template": "seq_abc123"})
    )
)
Updating Task Status:
python
from benchling_sdk.models import WorkflowTaskUpdate

updated_task = benchling.workflow_tasks.update(
    task_id="task_abc123",
    workflow_task=WorkflowTaskUpdate(
        status_id="status_complete_abc123"
    )
)
Asynchronous Operations:
Some operations are asynchronous and return tasks:
python
undefined
使用Benchling的工作流系统自动化实验室流程。
创建工作流任务:
python
from benchling_sdk.models import WorkflowTaskCreate

task = benchling.workflow_tasks.create(
    WorkflowTaskCreate(
        name="PCR Amplification",
        workflow_id="wf_abc123",
        assignee_id="user_abc123",
        fields=benchling.models.fields({"template": "seq_abc123"})
    )
)
更新任务状态:
python
from benchling_sdk.models import WorkflowTaskUpdate

updated_task = benchling.workflow_tasks.update(
    task_id="task_abc123",
    workflow_task=WorkflowTaskUpdate(
        status_id="status_complete_abc123"
    )
)
异步操作:
部分操作为异步操作,会返回任务:
python
undefined

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 )

**Key Workflow Operations:**
- Create and manage workflow tasks
- Update task statuses and assignments
- Execute bulk operations asynchronously
- Monitor task progress
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 )

**核心工作流操作:**
- 创建和管理工作流任务
- 更新任务状态和分配
- 异步执行批量操作
- 监控任务进度

6. Events & Integration

6. 事件与集成

Subscribe to Benchling events for real-time integrations using AWS EventBridge.
Event Types:
  • Entity creation, update, archive
  • Inventory transfers
  • Workflow task status changes
  • Entry creation and updates
  • Results registration
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
Use Cases:
  • Sync Benchling data to external databases
  • Trigger downstream processes on workflow completion
  • Send notifications on entity changes
  • Audit trail logging
Refer to Benchling's event documentation for event schemas and configuration.
使用AWS EventBridge订阅Benchling事件以实现实时集成。
事件类型:
  • 实体创建、更新、归档
  • 库存转移
  • 工作流任务状态变更
  • 条目创建与更新
  • 结果注册
集成模式:
  1. 在Benchling设置中配置事件路由到AWS EventBridge
  2. 创建EventBridge规则以过滤事件
  3. 将事件路由到Lambda函数或其他目标
  4. 处理事件并更新外部系统
使用场景:
  • 将Benchling数据同步到外部数据库
  • 在工作流完成时触发下游流程
  • 在实体变更时发送通知
  • 审计追踪日志
如需事件架构和配置信息,请参考Benchling的事件文档。

7. Data Warehouse & Analytics

7. 数据仓库与分析

Query historical Benchling data using SQL through the Data Warehouse.
Access Method: The Benchling Data Warehouse provides SQL access to Benchling data for analytics and reporting. Connect using standard SQL clients with provided credentials.
Common Queries:
  • Aggregate experimental results
  • Analyze inventory trends
  • Generate compliance reports
  • Export data for external analysis
Integration with Analysis Tools:
  • Jupyter notebooks for interactive analysis
  • BI tools (Tableau, Looker, PowerBI)
  • Custom dashboards
通过数据仓库使用SQL查询历史Benchling数据。
访问方式: Benchling数据仓库提供对Benchling数据的SQL访问,用于分析和报告。使用提供的凭据通过标准SQL客户端连接。
常见查询:
  • 汇总实验结果
  • 分析库存趋势
  • 生成合规报告
  • 导出数据用于外部分析
与分析工具集成:
  • Jupyter笔记本用于交互式分析
  • BI工具(Tableau、Looker、PowerBI)
  • 自定义仪表板

Best Practices

最佳实践

Error Handling

错误处理

The SDK automatically retries failed requests:
python
undefined
SDK会自动重试失败的请求:
python
undefined

Automatic retry for 429, 502, 503, 504 status codes

自动重试429、502、503、504状态码

Up to 5 retries with exponential backoff

最多重试5次,使用指数退避策略

Customize retry behavior if needed

如有需要可自定义重试行为

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) )
undefined
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) )
undefined

Pagination Efficiency

分页效率

Use generators for memory-efficient pagination:
python
undefined
使用生成器实现内存高效的分页:
python
undefined

Generator-based iteration

基于生成器的迭代

for page in benchling.dna_sequences.list(): for sequence in page: process(sequence)
for page in benchling.dna_sequences.list(): for sequence in page: process(sequence)

Check estimated count without loading all pages

在不加载所有页面的情况下查看预估总数

total = benchling.dna_sequences.list().estimated_count()
undefined
total = benchling.dna_sequences.list().estimated_count()
undefined

Schema Fields Helper

架构字段助手

Use the
fields()
helper for custom schema fields:
python
undefined
使用
fields()
助手处理自定义架构字段:
python
undefined

Convert dict to Fields object

将字典转换为Fields对象

custom_fields = benchling.models.fields({ "concentration": "100 ng/μL", "date_prepared": "2025-10-20", "notes": "High quality prep" })
undefined
custom_fields = benchling.models.fields({ "concentration": "100 ng/μL", "date_prepared": "2025-10-20", "notes": "High quality prep" })
undefined

Forward Compatibility

向前兼容性

The SDK handles unknown enum values and types gracefully:
  • Unknown enum values are preserved
  • Unrecognized polymorphic types return
    UnknownType
  • Allows working with newer API versions
SDK可优雅处理未知枚举值和类型:
  • 保留未知枚举值
  • 无法识别的多态类型返回
    UnknownType
  • 支持与较新版本的API协同工作

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
  • 切勿将API密钥提交到版本控制系统
  • 使用环境变量存储凭据
  • 若密钥泄露请立即轮换
  • 为应用授予最小必要权限
  • 在多用户场景下使用OAuth

Resources

资源

references/

references/

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
Load these references as needed for specific integration requirements.
包含详细参考文档,用于深入了解相关信息:
  • authentication.md - 包含OIDC、安全最佳实践和凭据管理的全面身份验证指南
  • sdk_reference.md - 详细的Python SDK参考,包含高级模式、示例和所有实体类型
  • api_endpoints.md - REST API端点参考,用于不使用SDK的直接HTTP调用
可根据特定集成需求加载这些参考文档。

scripts/

scripts/

This skill currently includes example scripts that can be removed or replaced with custom automation scripts for your specific Benchling workflows.
此技能目前包含示例脚本,可根据您的特定Benchling工作流将其移除或替换为自定义自动化脚本。

Common Use Cases

常见使用场景

1. Bulk Entity Import:
python
undefined
1. 批量实体导入:
python
undefined

Import multiple sequences from FASTA file

从FASTA文件导入多个序列

from Bio import SeqIO
for record in SeqIO.parse("sequences.fasta", "fasta"): benchling.dna_sequences.create( DnaSequenceCreate( name=record.id, bases=str(record.seq), is_circular=False, folder_id="fld_abc123" ) )

**2. Inventory Audit:**
```python
from Bio import SeqIO
for record in SeqIO.parse("sequences.fasta", "fasta"): benchling.dna_sequences.create( DnaSequenceCreate( name=record.id, bases=str(record.seq), is_circular=False, folder_id="fld_abc123" ) )

**2. 库存审计:**
```python

List all containers in a specific location

列出特定位置的所有容器

containers = benchling.containers.list( parent_storage_id="box_abc123" )
for page in containers: for container in page: print(f"{container.name}: {container.barcode}")

**3. Workflow Automation:**
```python
containers = benchling.containers.list( parent_storage_id="box_abc123" )
for page in containers: for container in page: print(f"{container.name}: {container.barcode}")

**3. 工作流自动化:**
```python

Update all pending tasks for a workflow

更新某个工作流的所有待处理任务

tasks = benchling.workflow_tasks.list( workflow_id="wf_abc123", status="pending" )
for page in tasks: for task in page: # Perform automated checks if auto_validate(task): benchling.workflow_tasks.update( task_id=task.id, workflow_task=WorkflowTaskUpdate( status_id="status_complete" ) )

**4. Data Export:**
```python
tasks = benchling.workflow_tasks.list( workflow_id="wf_abc123", status="pending" )
for page in tasks: for task in page: # 执行自动检查 if auto_validate(task): benchling.workflow_tasks.update( task_id=task.id, workflow_task=WorkflowTaskUpdate( status_id="status_complete" ) )

**4. 数据导出:**
```python

Export all sequences with specific properties

导出具有特定属性的所有序列

sequences = benchling.dna_sequences.list() export_data = []
for page in sequences: for seq in page: if seq.schema_id == "target_schema_id": export_data.append({ "id": seq.id, "name": seq.name, "bases": seq.bases, "length": len(seq.bases) })
sequences = benchling.dna_sequences.list() export_data = []
for page in sequences: for seq in page: if seq.schema_id == "target_schema_id": export_data.append({ "id": seq.id, "name": seq.name, "bases": seq.bases, "length": len(seq.bases) })

Save to CSV or database

保存到CSV或数据库

import csv with open("sequences.csv", "w") as f: writer = csv.DictWriter(f, fieldnames=export_data[0].keys()) writer.writeheader() writer.writerows(export_data)
undefined
import csv with open("sequences.csv", "w") as f: writer = csv.DictWriter(f, fieldnames=export_data[0].keys()) writer.writeheader() writer.writerows(export_data)
undefined

Additional Resources

额外资源