HTTP API Invocation (Cross-Language)
HTTP API Access
To access cloud functions via the Cloud Function HTTP API, you need to first obtain an access token (Token), then use this token for API invocation.
Obtain an Access Token
To obtain an access token, see the AccessToken documentation.
API Invocation Format
Request URL:
POST https://{env-id}.api.tcloudbasegateway.com/v1/functions/{function-name}
Request Headers:
Authorization: Bearer {access_token}
Content-Type: application/json
Multi-Language Invocation Sample
- cURL
- JavaScript
- Python
- PHP
- Go
# Basic Invocation
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 Cloud Function
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"
}'
// Use 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('Cloud function invocation failed:', error);
throw error;
}
}
// Usage example
const token = 'your-access-token';
callCloudFunction('hello-world', { name: 'CloudBase' }, token)
.then(result => {
console.log('Invoked successfully:', result);
})
.catch(error => {
console.error('Invocation failed:', error);
});
import requests
import json
def call_cloud_function(env_id, function_name, data, access_token):
"""Invoke cloud function"""
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"Request failed: {e}")
raise
except json.JSONDecodeError as e:
print(f"Response parsing failed: {e}")
raise
# Usage sample
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("Invocation successful:", result)
except Exception as e:
print("Invocation failed:", 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 request failed');
}
$result = json_decode($response, true);
if ($httpCode !== 200) {
throw new Exception("HTTP {$httpCode}: " . ($result['message'] ?? 'Unknown error'));
}
return $result;
}
// Usage example
try {
$envId = 'your-env-id';
$functionName = 'hello-world';
$data = ['message' => 'Hello from PHP'];
$token = 'your-access-token';
$result = callCloudFunction($envId, $functionName, $data, $token);
echo "Invocation successful: " . json_encode($result, JSON_UNESCAPED_UNICODE) . "\n";
} catch (Exception $e) {
echo "Invocation failed: " . $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)
// Serialize request data
jsonData, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("serialize request data failed: %v", err)
}
// Create the request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return nil, fmt.Errorf("create request failed: %v", err)
}
// Set request headers
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
// Send the request.
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("send request failed: %v", err)
}
defer resp.Body.Close()
// Read the response
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read response failed: %v", err)
}
// Parse the response
var result CloudFunctionResponse
if err := json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("parse response failed: %v", err)
}
// Check the HTTP status code
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("call failed: %v\n", err)
return
}
fmt.Printf("call succeeded: %+v\n", result)
}
HTTP API Parameters Description
Path Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
env-id | string | Yes | Environment ID |
function-name | string | Yes | Function name |
Query Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
webfn | string | No | Set to true when calling HTTP cloud function |
Request Header Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
Authorization | string | Yes | Bearer Token authentication |
Content-Type | string | Yes | Request content type, usually application/json |
X-Qualifier | string | No | Specifies the version of the function to invoke |
X-Tcb-Webfn | string | No | Set to true when calling HTTP cloud function |