HTTP API 调用(跨语言)
HTTP API 访问
通过 云函数 HTTP API 访问云函数,您需要先获取访问令牌(Token),然后使用该令牌进行 API 调用。
获取访问令牌
访问令牌的获取方式请参考 AccessToken 文档。
API 调用格式
请求 URL:
POST https://{env-id}.api.tcloudbasegateway.com/v1/functions/{function-name}
请求头:
Authorization: Bearer {access_token}
Content-Type: application/json
多语言调用示例
- cURL
- JavaScript
- Python
- PHP
- Go
# 基础调用
curl -L 'https://your-env-id.api.tcloudbasegateway.com/v1/functions/your-function-name' \
-H 'Accept: application/json' \
-H 'Authorization: Bearer your-access-token' \
-H 'Content-Type: application/json' \
-d '{
"message": "Hello CloudBase",
"timestamp": 1640995200000
}'
# HTTP 云函数
curl -L 'https://your-env-id.api.tcloudbasegateway.com/v1/functions/your-web-function?webfn=true' \
-H 'Accept: application/json' \
-H 'Authorization: Bearer your-access-token' \
-H 'Content-Type: application/json' \
-d '{
"path": "/api/users",
"method": "GET"
}'
// 使用 Fetch API
async function callCloudFunction(functionName, data, token) {
try {
const response = await fetch(
`https://your-env-id.api.tcloudbasegateway.com/v1/functions/${functionName}`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(data)
}
);
if (!response.ok) {
const errorData = await response.json();
throw new Error(`HTTP ${response.status}: ${errorData.message}`);
}
const result = await response.json();
return result;
} catch (error) {
console.error('云函数调用失败:', error);
throw error;
}
}
// 使用示例
const token = 'your-access-token';
callCloudFunction('hello-world', { name: 'CloudBase' }, token)
.then(result => {
console.log('调用成功:', result);
})
.catch(error => {
console.error('调用失败:', error);
});
import requests
import json
def call_cloud_function(env_id, function_name, data, access_token):
"""调用云函数"""
url = f"https://{env_id}.api.tcloudbasegateway.com/v1/functions/{function_name}"
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json',
'Accept': 'application/json'
}
try:
response = requests.post(url, headers=headers, json=data, timeout=30)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")
raise
except json.JSONDecodeError as e:
print(f"响应解析失败: {e}")
raise
# 使用示例
if __name__ == "__main__":
env_id = "your-env-id"
function_name = "hello-world"
data = {"message": "Hello from Python"}
token = "your-access-token"
try:
result = call_cloud_function(env_id, function_name, data, token)
print("调用成功:", result)
except Exception as e:
print("调用失败:", e)
<?php
function callCloudFunction($envId, $functionName, $data, $accessToken) {
$url = "https://{$envId}.api.tcloudbasegateway.com/v1/functions/{$functionName}";
$headers = [
'Authorization: Bearer ' . $accessToken,
'Content-Type: application/json',
'Accept: application/json'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($response === false) {
throw new Exception('cURL 请求失败');
}
$result = json_decode($response, true);
if ($httpCode !== 200) {
throw new Exception("HTTP {$httpCode}: " . ($result['message'] ?? '未知错误'));
}
return $result;
}
// 使用示例
try {
$envId = 'your-env-id';
$functionName = 'hello-world';
$data = ['message' => 'Hello from PHP'];
$token = 'your-access-token';
$result = callCloudFunction($envId, $functionName, $data, $token);
echo "调用成功: " . json_encode($result, JSON_UNESCAPED_UNICODE) . "\n";
} catch (Exception $e) {
echo "调用失败: " . $e->getMessage() . "\n";
}
?>
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
type CloudFunctionRequest struct {
Message string `json:"message"`
Timestamp int64 `json:"timestamp"`
}
type CloudFunctionResponse struct {
Code string `json:"code,omitempty"`
Message string `json:"message,omitempty"`
RequestId string `json:"requestId,omitempty"`
Result interface{} `json:"result,omitempty"`
}
func callCloudFunction(envId, functionName string, data interface{}, accessToken string) (*CloudFunctionResponse, error) {
url := fmt.Sprintf("https://%s.api.tcloudbasegateway.com/v1/functions/%s", envId, functionName)
// 序列化请求数据
jsonData, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("序列化请求数据失败: %v", err)
}
// 创建请求
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return nil, fmt.Errorf("创建请求失败: %v", err)
}
// 设置请求头
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
// 发送请求
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("发送请求失败: %v", err)
}
defer resp.Body.Close()
// 读取响应
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("读取响应失败: %v", err)
}
// 解析响应
var result CloudFunctionResponse
if err := json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("解析响应失败: %v", err)
}
// 检查 HTTP 状态码
if resp.StatusCode != 200 {
return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, result.Message)
}
return &result, nil
}
func main() {
envId := "your-env-id"
functionName := "hello-world"
data := CloudFunctionRequest{
Message: "Hello from Go",
Timestamp: time.Now().Unix(),
}
token := "your-access-token"
result, err := callCloudFunction(envId, functionName, data, token)
if err != nil {
fmt.Printf("调用失败: %v\n", err)
return
}
fmt.Printf("调用成功: %+v\n", result)
}
HTTP API 参数说明
路径参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
env-id | string | 是 | 环境 ID |
function-name | string | 是 | 函数名称 |
查询参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
webfn | string | 否 | 调用 HTTP 云函数时设置为 true |
请求头参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
Authorization | string | 是 | Bearer Token 认证 |
Content-Type | string | 是 | 请求内容类型,通常为 application/json |
X-Qualifier | string | 否 | 指定调用函数的版本 |
X-Tcb-Webfn | string | 否 | 调用 HTTP 云函数时设置为 true |