API 参考已发布
RAILWISE-OS SDK 使用指南
RAILWISE-OS 官方 SDK 的安装、配置与使用说明,支持 TypeScript/JavaScript 和 Python
API 参考
RAILWISE-OS SDK 使用指南
Section titled “RAILWISE-OS SDK 使用指南”AI语义标签:
#SDK#TypeScript#Python#API客户端#开发者工具#快速接入
1. SDK 概述
Section titled “1. SDK 概述”RAILWISE-OS 官方 SDK 封装了 REST API 的调用细节,提供类型安全、自动重试、错误处理等能力,帮助开发者快速集成。
1.1 支持的 SDK
Section titled “1.1 支持的 SDK”| SDK | 语言 | 版本 | 包管理器 | 适用场景 |
|---|---|---|---|---|
@railwise/os-sdk |
TypeScript/JavaScript | 1.5.2 | npm/yarn/pnpm | Web 应用、Node.js 服务 |
railwise-os |
Python | 1.5.2 | pip | 数据分析、自动化脚本 |
1.2 SDK 特性
Section titled “1.2 SDK 特性”- 类型安全:完整的 TypeScript 类型定义
- 自动重试:内置指数退避重试机制
- 请求签名:自动处理 API Key / JWT 认证
- 错误处理:统一的错误类型与分类
- 分页助手:自动处理分页列表
- 文件上传:支持大文件分片上传
- Webhook 验证:内置签名验证工具
2. TypeScript/JavaScript SDK
Section titled “2. TypeScript/JavaScript SDK”2.1 安装
Section titled “2.1 安装”# npmnpm install @railwise/os-sdk
# yarnyarn add @railwise/os-sdk
# pnpmpnpm add @railwise/os-sdk2.2 初始化
Section titled “2.2 初始化”import { RailWiseOSClient } from '@railwise/os-sdk';
// 方式1:API Key 认证const client = new RailWiseOSClient({ apiKey: 'rwsk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', baseURL: 'https://api.os.railwise.cn/v3', // 可选配置 timeout: 30000, // 请求超时(毫秒) maxRetries: 3, // 最大重试次数 retryDelay: 1000, // 初始重试延迟(毫秒)});
// 方式2:JWT Token 认证const client = new RailWiseOSClient({ accessToken: 'eyJhbGciOiJSUzI1NiIs...', baseURL: 'https://api.os.railwise.cn/v3',});2.3 项目操作
Section titled “2.3 项目操作”// 获取项目列表const projects = await client.projects.list({ status: 'active', page: 1, pageSize: 20,});
console.log(`共 ${projects.pagination.total} 个项目`);projects.items.forEach(p => { console.log(`${p.code}: ${p.name}`);});
// 获取项目详情const project = await client.projects.get('proj_abc123');console.log(project.name, project.status);
// 创建项目const newProject = await client.projects.create({ name: '宁波绕城高速管廊监测项目', type: 'track', contractAmount: 1200000, startDate: '2026-07-01', endDate: '2027-06-30', managerId: 'user_002', clientId: 'client_003', location: { province: '浙江省', city: '宁波市', address: '鄞州区某路段', },});
// 更新项目await client.projects.update('proj_abc123', { name: '更新后的项目名称',});
// 删除项目await client.projects.delete('proj_abc123');2.4 任务操作
Section titled “2.4 任务操作”// 创建任务const task = await client.tasks.create({ projectId: 'proj_abc123', name: '3号线K12+350断面自动化监测', type: 'data_collection', priority: 'high', assigneeIds: ['user_003', 'user_004'], dueDate: '2026-07-15',});
// 更新任务状态await client.tasks.updateStatus('task_001', { status: 'completed', remark: '监测数据已上传,无异常',});
// 获取任务统计const stats = await client.tasks.getStatistics();console.log(`完成率: ${stats.completionRate}%`);2.5 数据操作
Section titled “2.5 数据操作”// 获取监测数据const data = await client.data.getMonitoring({ projectId: 'proj_abc123', sensorType: 'total_station', startTime: '2026-07-01T00:00:00Z', endTime: '2026-07-08T23:59:59Z', pageSize: 100,});
// 批量写入数据const result = await client.data.batchUpload({ projectId: 'proj_abc123', records: [ { pointId: 'point_k12_350_01', sensorType: 'total_station', measuredAt: '2026-07-08T08:00:00+08:00', values: { x: 395123.456, y: 2812345.678, z: 15.234, }, }, ],});
// 获取数据趋势const trends = await client.data.getTrends({ projectId: 'proj_abc123', pointIds: ['point_k12_350_01', 'point_k12_350_02'], metric: 'settlement', interval: 'day', startTime: '2026-07-01T00:00:00Z', endTime: '2026-07-08T23:59:59Z',});2.6 报告操作
Section titled “2.6 报告操作”// 生成报告const reportJob = await client.reports.generate({ projectId: 'proj_abc123', templateId: 'tpl_foundation_daily', name: '2026年7月8日监测日报', period: { startDate: '2026-07-08', endDate: '2026-07-08', }, options: { includeCharts: true, format: 'pdf', },});
// 轮询报告状态let status;do { await new Promise(r => setTimeout(r, 5000)); // 等待 5 秒 status = await client.reports.getStatus(reportJob.reportId);} while (status.status === 'generating');
if (status.status === 'completed') { console.log('报告下载地址:', status.downloadUrl);}2.7 错误处理
Section titled “2.7 错误处理”import { RailWiseAPIError, RailWiseAuthError, RailWiseRateLimitError } from '@railwise/os-sdk';
try { const project = await client.projects.get('proj_abc123');} catch (error) { if (error instanceof RailWiseAuthError) { console.error('认证失败:', error.message); // 刷新 Token 或重新登录 } else if (error instanceof RailWiseRateLimitError) { console.error('请求过于频繁,请等待:', error.retryAfter, '秒'); await new Promise(r => setTimeout(r, error.retryAfter * 1000)); } else if (error instanceof RailWiseAPIError) { console.error('API 错误:', error.code, error.message); console.error('请求ID:', error.requestId); } else { console.error('未知错误:', error); }}2.8 Webhook 验证
Section titled “2.8 Webhook 验证”import { verifyWebhookSignature } from '@railwise/os-sdk';
app.post('/webhook/railwise', express.raw({ type: 'application/json' }), (req, res) => { const isValid = verifyWebhookSignature({ payload: req.body.toString(), signature: req.headers['x-railwise-signature'] as string, timestamp: req.headers['x-railwise-timestamp'] as string, secret: 'whsk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', });
if (!isValid) { return res.status(401).json({ error: '签名验证失败' }); }
const event = JSON.parse(req.body.toString()); // 处理事件...
res.status(200).json({ received: true });});3. Python SDK
Section titled “3. Python SDK”3.1 安装
Section titled “3.1 安装”pip install railwise-os3.2 初始化
Section titled “3.2 初始化”from railwise_os import RailWiseOSClient
# API Key 认证client = RailWiseOSClient( api_key="rwsk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", base_url="https://api.os.railwise.cn/v3", timeout=30, max_retries=3,)
# JWT Token 认证client = RailWiseOSClient( access_token="eyJhbGciOiJSUzI1NiIs...", base_url="https://api.os.railwise.cn/v3",)3.3 项目操作
Section titled “3.3 项目操作”# 获取项目列表projects = client.projects.list(status="active", page=1, page_size=20)print(f"共 {projects.pagination.total} 个项目")
for p in projects.items: print(f"{p.code}: {p.name}")
# 获取项目详情project = client.projects.get("proj_abc123")print(project.name)
# 创建项目new_project = client.projects.create( name="宁波绕城高速管廊监测项目", type="track", contract_amount=1200000, start_date="2026-07-01", end_date="2027-06-30", manager_id="user_002", client_id="client_003", location={ "province": "浙江省", "city": "宁波市", "address": "鄞州区某路段", },)print(f"创建成功: {new_project.id}")3.4 数据操作
Section titled “3.4 数据操作”# 获取监测数据data = client.data.get_monitoring( project_id="proj_abc123", sensor_type="total_station", start_time="2026-07-01T00:00:00Z", end_time="2026-07-08T23:59:59Z",)
# 批量写入数据result = client.data.batch_upload( project_id="proj_abc123", records=[ { "point_id": "point_k12_350_01", "sensor_type": "total_station", "measured_at": "2026-07-08T08:00:00+08:00", "values": { "x": 395123.456, "y": 2812345.678, "z": 15.234, }, }, ],)print(f"成功: {result.success}/{result.total}")
# 获取数据趋势trends = client.data.get_trends( project_id="proj_abc123", point_ids=["point_k12_350_01", "point_k12_350_02"], metric="settlement", interval="day",)3.5 报告操作
Section titled “3.5 报告操作”import time
# 生成报告report_job = client.reports.generate( project_id="proj_abc123", template_id="tpl_foundation_daily", name="2026年7月8日监测日报", period={ "start_date": "2026-07-08", "end_date": "2026-07-08", },)
# 轮询报告状态while True: status = client.reports.get_status(report_job.report_id) if status.status == "completed": print(f"报告下载地址: {status.download_url}") break elif status.status == "failed": print("报告生成失败") break time.sleep(5)3.6 错误处理
Section titled “3.6 错误处理”from railwise_os import RailWiseAPIError, RailWiseAuthError, RailWiseRateLimitError
try: project = client.projects.get("proj_abc123")except RailWiseAuthError as e: print(f"认证失败: {e.message}")except RailWiseRateLimitError as e: print(f"请求过于频繁,请等待 {e.retry_after} 秒") time.sleep(e.retry_after)except RailWiseAPIError as e: print(f"API 错误 [{e.code}]: {e.message}") print(f"请求ID: {e.request_id}")except Exception as e: print(f"未知错误: {e}")4. SDK 配置选项
Section titled “4. SDK 配置选项”4.1 完整配置
Section titled “4.1 完整配置”interface RailWiseOSConfig { // 认证(二选一) apiKey?: string; accessToken?: string;
// 基础配置 baseURL: string; timeout?: number; // 默认 30000ms
// 重试配置 maxRetries?: number; // 默认 3 retryDelay?: number; // 默认 1000ms retryCondition?: (error: any) => boolean;
// 请求配置 headers?: Record<string, string>;
// 高级配置 requestInterceptor?: (config: any) => any; responseInterceptor?: (response: any) => any; errorHandler?: (error: any) => void;}4.2 自定义 HTTP 客户端
Section titled “4.2 自定义 HTTP 客户端”import axios from 'axios';
const httpClient = axios.create({ timeout: 60000, // 自定义配置...});
const client = new RailWiseOSClient({ apiKey: 'rwsk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', baseURL: 'https://api.os.railwise.cn/v3', httpClient, // 使用自定义 HTTP 客户端});5. 相关文档
Section titled “5. 相关文档”文档版本: v3.2.0 | SDK版本: 1.5.2 | 最后更新: 2026-07-08
