Files
PlantAI-dev/docs/API_USAGE.md
T
2026-08-03 18:42:47 +08:00

317 lines
6.8 KiB
Markdown
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# bbav20311 API 使用文档
> 版本: 1.0
> 日期: 2026-03-12
> 功能: 多数据库 API 查询(参考 ClawBio gwas-lookup 模式)
---
## 📚 目录
1. [快速开始](#快速开始)
2. [支持的 API](#支持的-api)
3. [基础使用](#基础使用)
4. [高级用法](#高级用法)
5. [配置管理](#配置管理)
6. [常见问题](#常见问题)
---
## 快速开始
### 1. 导入模块
```python
from gfa_core.api_clients import (
MultiAPIQuery,
PlantCAREClient,
PfamClient,
NCBIClient,
EnsemblPlantsClient,
)
```
### 2. 简单查询示例
```python
# 创建查询管理器
query = MultiAPIQuery()
# 查询基因信息
results = query.query_all('gene', {
'gene_symbol': 'SPL',
'organism': 'Arabidopsis'
})
# 生成统一报告
report = query.generate_unified_report(results, 'gene', 'SPL')
print(report)
```
---
## 支持的 API
### 植物数据库
| API | 功能 | 需要 API Key |
|-----|------|-------------|
| **PlantCARE** | 启动子顺式元件分析 | ❌ 否 |
| **Pfam** | 蛋白质家族查询 | ❌ 否 |
| **NCBI** | 基因/序列查询 | ⚠️ 可选 |
| **Ensembl Plants** | 植物基因组/表达 | ❌ 否 |
| **Phytozome** | 比较基因组学 | ⚠️ 可选 |
| **TAIR** | 拟南芥数据库 | ⚠️ 需要 |
| **PlantTFDB** | 转录因子数据库 | ❌ 否 |
### API Key 申请地址
- **NCBI**: https://www.ncbi.nlm.nih.gov/account/
- **Phytozome**: https://phytozome-next.jgi.doe.gov/
- **TAIR**: https://www.arabidopsis.org/
---
## 基础使用
### 1. 启动子分析(PlantCARE)
```python
from gfa_core.api_clients import PlantCAREClient
# 创建客户端
client = PlantCAREClient()
# 分析启动子序列
promoter_seq = "ATGCGATCGATCGATCG..."
result = client.analyze_promoter(promoter_seq)
# 查看结果
print(f"发现 {result['total_elements']} 个顺式元件")
print(f"分类: {result['categories']}")
# 查看具体元件
for category, elements in result['elements_by_category'].items():
print(f"\n{category}:")
for elem in elements:
print(f" - {elem.name}: {elem.sequence}")
```
### 2. 蛋白质家族查询(Pfam)
```python
from gfa_core.api_clients import PfamClient
# 创建客户端
client = PfamClient()
# 搜索蛋白质结构域
domains = client.search_protein("Q9C5U0") # UniProt ID
for domain in domains:
print(f"{domain.accession}: {domain.name}")
print(f" {domain.description}")
# 获取家族详细信息
family_info = client.get_family_info("PF03110") # SBP family
print(f"蛋白质数量: {family_info['protein_count']}")
```
### 3. NCBI 基因查询
```python
from gfa_core.api_clients import NCBIClient
# 创建客户端(可选传入 API key)
client = NCBIClient(api_key="your_api_key_here")
# 搜索基因
genes = client.search_gene("SPL", "Arabidopsis")
for gene in genes:
print(f"{gene.symbol}: {gene.description}")
print(f" 染色体: {gene.chromosome}")
print(f" 位置: {gene.location}")
# 获取序列
sequence = client.get_sequence("nuccore", "NM_001318947.1")
print(sequence[:200]) # 前200bp
```
### 4. 多 API 并行查询
```python
from gfa_core.api_clients import MultiAPIQuery
# 创建查询管理器
query = MultiAPIQuery(max_workers=5, timeout=30)
# 查询类型和参数
query_type = 'protein' # 'gene', 'protein', 'promoter', 'domain'
params = {
'protein_id': 'Q9C5U0',
'gene_symbol': 'SPL1',
}
# 执行并行查询
results = query.query_all(query_type, params)
# 生成统一报告
report = query.generate_unified_report(results, query_type, 'SPL1')
# 查看结果摘要
print(f"成功: {report['summary']['successful']}")
print(f"失败: {report['summary']['failed']}")
# 查看合并数据
print(report['merged_data'])
```
---
## 高级用法
### 1. 自定义查询配置
```python
from gfa_core.api_config import get_api_config
# 获取 NCBI 配置
config = get_api_config('ncbi')
print(f"Rate limit: {config.rate_limit}s")
print(f"Timeout: {config.timeout}s")
# 创建带自定义配置的客户端
from gfa_core.api_clients import NCBIClient
client = NCBIClient(
api_key="your_key",
rate_limit=0.1 # 10 requests/second
)
```
### 2. 批量查询
```python
from gfa_core.api_clients import MultiAPIQuery
query = MultiAPIQuery()
gene_list = ['SPL1', 'SPL2', 'SPL3', 'SPL4', 'SPL5']
for gene in gene_list:
results = query.query_all('gene', {
'gene_symbol': gene,
'organism': 'Arabidopsis'
})
report = query.generate_unified_report(results, 'gene', gene)
print(f"{gene}: {report['summary']}")
```
### 3. 错误处理
```python
from gfa_core.api_clients import MultiAPIQuery, APIResult
query = MultiAPIQuery()
results = query.query_all('gene', {'gene_symbol': 'UNKNOWN_GENE'})
for api_name, result in results.items():
if result.status == 'success':
print(f"✅ {api_name}: 成功")
elif result.status == 'error':
print(f"❌ {api_name}: 错误 - {result.error_message}")
elif result.status == 'timeout':
print(f"⏱️ {api_name}: 超时")
```
---
## 配置管理
### 配置文件位置
```
config/api_config.yaml
```
### 配置示例
```yaml
# NCBI API
ncbi:
api_key: "your_ncbi_api_key_here"
rate_limit: 0.1 # 有 key 时 10 req/s
# 通用设置
settings:
default_rate_limit: 1.0
request_timeout: 30
max_retries: 3
max_workers: 5
```
### 环境变量
也可以通过环境变量设置 API key:
```bash
export NCBI_API_KEY="your_key_here"
export PHYTOZOME_API_KEY="your_key_here"
export TAIR_API_KEY="your_key_here"
```
---
## 常见问题
### Q1: 为什么某些 API 查询很慢?
**A**: 可能原因:
1. 网络延迟(API 服务器在国外)
2. 速率限制(特别是 NCBI 无 API key 时 3 req/s)
3. 查询复杂度高
**解决**:
- 申请 API key 提高速率
- 使用 `MultiAPIQuery` 并行查询
- 增加超时时间:`timeout=60`
### Q2: PlantCARE 为什么无法连接?
**A**: PlantCARE 网页版没有公开 REST API,当前实现使用:
1. 本地元件模式匹配
2. 已知元件数据库(G-box, ABRE, W-box 等)
**解决**:如需完整功能,建议本地部署 PlantCARE 数据库。
### Q3: 如何添加新的 API?
**A**: 步骤:
1. 在 `gfa_core/api_clients/` 创建新客户端
2. 继承基类模式(参考 `ncbi_client.py`)
3. 在 `__init__.py` 导出
4. 在 `multi_api_query.py` 添加查询逻辑
### Q4: API key 安全吗?
**A**:
- ✅ 存储在本地配置文件
- ✅ 支持环境变量(推荐用于服务器)
- ✅ 不会上传到代码仓库(.gitignore)
- ⚠️ 不要硬编码在代码中
---
## 参考
- **ClawBio gwas-lookup**: https://github.com/ClawBio/ClawBio/tree/main/skills/gwas-lookup
- **NCBI E-utilities**: https://www.ncbi.nlm.nih.gov/books/NBK25501/
- **Ensembl REST API**: https://rest.ensembl.org/
- **Pfam**: https://pfam.xfam.org/
---
*文档版本: 1.0*
*最后更新: 2026-03-12*