APIs
APIs 提供了一种灵活的方式来调用 V2 版本的 APIs 连接器。V2 版本的 APIs 创建方式请参考说明文档
提示
v3 版本在调用通用 APIs 时,使用的是 HTTP API 的开放能力。
APIs 使用参考
interface apis {
[apisLabel: string]: {
[
method: "request" | "post" | "get" | "head" | "patch" | "delete" | "put"
]: (
callApiOptions: ICallApiOptions,
opts?: IRequestOptions
) => Promise<ResponseObject["data"]>;
};
}
APIs 模块支持以下 HTTP 方法:
| 方法名 | 描述 | 示例 |
|---|---|---|
| get | GET 请求 | apis["apisLabel"].get(callApiOptions) |
| post | POST 请求 | apis["apisLabel"].post(callApiOptions) |
| put | PUT 请求 | apis["apisLabel"].put(callApiOptions) |
| delete | DELETE 请求 | apis["apisLabel"].delete(callApiOptions) |
| head | HEAD 请求 | apis["apisLabel"].head(callApiOptions) |
| patch | PATCH 请求 | apis["apisLabel"].patch(callApiOptions) |
| request | 自定义方法请求 | apis["apisLabel"].request(callApiOptions) |
提示
apisLabel 是 APIs 标识,在创建 V2 版本的 APIs 连接器时生成,可以在连接器的基本信息中查看
参数
callApiOptions
ICallApiOptions
opts
IRequestOptions
请求对象参数,一般不用传入,包含url、method、headers、body,作为定制化需求的补充,会覆盖 callApiOptions 中的同名参数
返回
res
ResponseObject['data']
HTTP 接口返回的 data 内容
示例
import cloudbase from "@cloudbase/js-sdk";
// 初始化 CloudBase 应用
const app = cloudbase.init({
env: "your-env-id", // 替换为您的环境ID
region: "ap-shanghai", // 地域,默认为上海
accessKey: "", // 填入生成的 Publishable Key,
});
// 获取 apis 实例
const apis = app.apis;
// 调用名为 "apisLabel" APIs 连接器 的 methodLabel 方法,使用 POST 调用
async function getUserProfile(userId: string) {
try {
const result = await apis["apisLabel"].post({
path: "methodLabel",
body: { userId },
});
console.log("调用成功:", result);
return result;
} catch (error) {
console.error("调用失败:", error);
throw error;
}
}
// 调用名为 "apisLabel" APIs 连接器 的 methodLabel 方法,使用 GET 调用
async function getProductList(category: string) {
try {
const result = await apis["apisLabel"].get({
path: "methodLabel",
body: { category },
});
return result;
} catch (error) {
console.error("调用失败:", error);
throw error;
}
}
// 自定义请求配置
async function customApiCall() {
const result = await apis["apisLabel"].request({
method: "PUT", // 指定 HTTP 方法
path: "methodLabel", // API 路径
headers: {
"X-Custom-Header": "value",
},
body: {
data: "custom data",
},
});
return result;
}
// 使用不同的 HTTP 方法
async function multiMethodExample() {
// POST 请求
const createResult = await apis["apisLabel"].post({
path: "methodLabel",
body: { name: "New Item" },
});
// GET 请求
const getResult = await apis["apisLabel"].get({
path: "methodLabel",
});
// DELETE 请求
const deleteResult = await apis["apisLabel"].delete({
path: "methodLabel",
});
}
async function safeApiCall() {
try {
const result = await apis["apisLabel"].post({
path: 'methodLabel'
body: { data: "test" },
});
return result;
} catch (error) {
// 处理 API 调用错误
if (error.code === "INVALID_PARAMS") {
console.error("参数错误:", error.msg);
} else {
console.error("API 调用失败:", error);
}
throw error;
}
}