Cloud Function Invocation Methods
CloudBase cloud function supports multiple invocation methods to meet the needs of different scenarios and platforms. You can choose the most suitable invocation method based on your actual situation.
Overview of Invocation Methods
| Invocation Methods | Applicable Scenarios | Features |
|---|---|---|
| SDK Invocation | Mini Programs, Web applications, mobile applications | Simple and easy to use, automatically handles authentication |
| HTTP API | Cross-language invocation, third-party system integration | Standard REST API, supports all programming languages |
| Web Client | Browser environments, frontend applications | Supports CORS, direct HTTP access |
| Mini Program Invocation | WeChat Mini Programs | Native support, no additional configuration required |
- SDK Invocation
- HTTP API Invocation
- Web Client Invocation
- Mini Program Invocation
SDK Invocation
Invoking cloud functions via CloudBase SDK is the simplest approach. The SDK automatically handles authentication and request encapsulation.
Web SDK Invocation
import tcb from '@cloudbase/js-sdk';
// Initialize it.
const app = tcb.init({
env: 'your-env-id'
});
// Invoke a cloud function
async function callFunction() {
try {
const result = await app.callFunction({
name: 'hello-world',
data: {
name: 'CloudBase',
message: 'Hello from Web'
}
});
console.log('Invoked successfully:', result);
return result.result;
} catch (error) {
console.error('Invocation failed:', error);
throw error;
}
}
// Usage example
callFunction().then(result => {
console.log('Function returned:', result);
});
Node.js SDK Invocation
const tcb = require('@cloudbase/node-sdk');
// Initialize it.
const app = tcb.init({
env: 'your-env-id',
secretId: 'your-secret-id',
secretKey: 'your-secret-key'
});
// Invoke a cloud function
async function callFunction() {
try {
const result = await app.callFunction({
name: 'hello-world',
data: {
name: 'CloudBase',
message: 'Hello from Node.js'
}
});
return result.result;
} catch (error) {
console.error('Invocation failed:', error);
throw error;
}
}
Mini Program SDK Invocation
// Invoke cloud function in Mini Program
wx.cloud.callFunction({
name: 'hello-world',
data: {
name: 'CloudBase',
message: 'Hello from MiniProgram'
},
success: res => {
console.log('Invoked successfully:', res.result);
},
fail: err => {
console.error('Invocation failed:', err);
}
});
// Use the Promise approach
async function callFunction() {
try {
const result = await wx.cloud.callFunction({
name: 'hello-world',
data: { message: 'Hello' }
});
return result.result;
} catch (error) {
console.error('Invocation failed:', error);
throw error;
}
}
Advantages of SDK Invocation
- Automatic Authentication - The SDK automatically handles user authentication and permission verification
- Error Handling - Unified error handling and retry mechanisms
- Type Safety - TypeScript support with complete type definitions
- Simple and Easy to Use - Encapsulates the underlying HTTP request details
HTTP API Invocation
Invoking cloud functions via HTTP API supports cross-language access and is suitable for third-party system integration.
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
# 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"
}'
JavaScript
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);
});
Python
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
# Usage sample
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)
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 invoking HTTP cloud functions |
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 |
Web Client Invocation
HTTP cloud function supports standard HTTP invocation via custom domains, suitable for browser environments and frontend applications.
Prerequisites
- Created an HTTP cloud function
- Configured the HTTP Access Service and custom domain
- Obtained the function's access URL
Configuring the HTTP Access Service
- Create an HTTP cloud function: In the TCB console, create a new HTTP cloud function.
- Go to Function Details: After the function is created successfully, click the function name to go to the details page.
- Configure the access path: On the function configuration page, locate the "HTTP Access Service Path" option and click "Go to Settings".
- Set the domain and path: On the HTTP Access Service page, configure the custom domain and access path.
💡 Note: For detailed HTTP Access Service configuration methods, see the HTTP Access Service documentation.
Client Invocation Example
Fetch API
// GET request
async function callFunction() {
try {
const response = await fetch('https://your-domain.com/your-function-path', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include', // Includes cookies
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
console.log('Function returned result:', result);
return result;
} catch (error) {
console.error('Request failed:', error);
throw error;
}
}
// POST request
async function postToFunction(data) {
try {
const response = await fetch('https://your-domain.com/your-function-path', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
credentials: 'include',
});
const result = await response.json();
return result;
} catch (error) {
console.error('POST request failed:', error);
throw error;
}
}
Axios
import axios from 'axios';
// Configure axios instance
const api = axios.create({
baseURL: 'https://your-domain.com',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
withCredentials: true,
});
// Request interceptor
api.interceptors.request.use(
(config) => {
// You can add the authentication token here
// config.headers.Authorization = `Bearer ${getToken()}`;
return config;
},
(error) => {
return Promise.reject(error);
}
);
// Response interceptor
api.interceptors.response.use(
(response) => {
return response.data;
},
(error) => {
console.error('API request failed:', error.response?.data || error.message);
return Promise.reject(error);
}
);
// GET request
async function getFunctionData() {
try {
const result = await api.get('/your-function-path');
console.log('Data fetched successfully:', result);
return result;
} catch (error) {
console.error('Failed to obtain data:', error);
throw error;
}
}
// POST request
async function postFunctionData(data) {
try {
const result = await api.post('/your-function-path', data);
console.log('Data submitted successfully:', result);
return result;
} catch (error) {
console.error('Failed to submit data:', error);
throw error;
}
}
Error Handling
Common HTTP Status Codes
| Status Code | Description | Handling Suggestions |
|---|---|---|
200 | Request successful | Process the response data normally |
400 | Invalid request parameters | Check the request parameter format |
401 | Unauthorized | Check authentication credentials |
404 | Function not found | Check the URL path |
500 | Internal Server Error | Check the function code logic |
502 | Bad Gateway | Check whether the function is running properly |
504 | Gateway Timeout | Optimize function execution time |
Error Handling Best Practices
async function callFunctionSafely(url, options = {}) {
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
...options,
});
// Check the response status
if (!response.ok) {
const errorData = await response.text();
throw new Error(`HTTP ${response.status}: ${errorData}`);
}
const result = await response.json();
return { success: true, data: result };
} catch (error) {
console.error('Function invocation failed:', error);
// Handle differently based on error types
if (error.name === 'TypeError') {
return { success: false, error: 'Network connection failed' };
} else if (error.message.includes('404')) {
return { success: false, error: 'Function not found' };
} else {
return { success: false, error: error.message };
}
}
}
Mini Program Invocation
WeChat Mini Programs can directly use the wx.cloud.callFunction API to call cloud functions without additional configuration.
Basic Invocation
// Basic invocation method
wx.cloud.callFunction({
name: 'hello-world',
data: {
name: 'CloudBase',
message: 'Hello from MiniProgram'
},
success: res => {
console.log('Invoked successfully:', res.result);
},
fail: err => {
console.error('Invocation failed:', err);
}
});
Promise-style Invocation
// Use the Promise approach
async function callFunction() {
try {
const result = await wx.cloud.callFunction({
name: 'hello-world',
data: {
message: 'Hello from Promise'
}
});
console.log('Invoked successfully:', result.result);
return result.result;
} catch (error) {
console.error('Invocation failed:', error);
throw error;
}
}
// Usage example
callFunction().then(result => {
console.log('Function returned:', result);
});
Usage in the Page
// pages/index/index.js
Page({
data: {
result: null,
loading: false
},
// Invoke a cloud function
async callCloudFunction() {
this.setData({ loading: true });
try {
const result = await wx.cloud.callFunction({
name: 'getUserInfo',
data: {
userId: wx.getStorageSync('userId')
}
});
this.setData({
result: result.result,
loading: false
});
wx.showToast({
title: 'Obtain Succeeded',
icon: 'success'
});
} catch (error) {
console.error('Invocation failed:', error);
this.setData({ loading: false });
wx.showToast({
title: 'Obtain Failed',
icon: 'error'
});
}
},
onLoad() {
// Call on page load
this.callCloudFunction();
}
});
Error Handling
// Complete error handling example
async function callFunctionWithErrorHandling(functionName, data) {
try {
const result = await wx.cloud.callFunction({
name: functionName,
data: data
});
// Check for business logic errors
if (result.result.code !== 0) {
throw new Error(result.result.message || 'Business processing failed');
}
return result.result.data;
} catch (error) {
console.error('Cloud function invocation failed:', error);
// Display different prompts based on error types
let errorMessage = 'Operation failed';
if (error.errCode === -1) {
errorMessage = 'Network connection failed, please check your network';
} else if (error.errCode === -404001) {
errorMessage = 'Cloud function does not exist';
} else if (error.message) {
errorMessage = error.message;
}
wx.showToast({
title: errorMessage,
icon: 'error'
});
throw error;
}
}
Batch Invocation
// Batch invoke multiple cloud functions
async function batchCallFunctions() {
const functions = [
{ name: 'getUserInfo', data: { userId: 'user1' } },
{ name: 'getOrderList', data: { status: 'pending' } },
{ name: 'getNotifications', data: { unread: true } }
];
try {
const results = await Promise.all(
functions.map(func =>
wx.cloud.callFunction({
name: func.name,
data: func.data
})
)
);
const [userInfo, orderList, notifications] = results.map(r => r.result);
return {
userInfo,
orderList,
notifications
};
} catch (error) {
console.error('Batch invocation failed:', error);
throw error;
}
}
Advantages of Mini Program Invocation
- Native Support - WeChat Mini Program natively supports cloud function invocation
- Automatic Authentication - Automatically carries user identity information
- Simple and Easy to Use - The API is concise and easy to use
- Performance Optimization - Network requests optimized for the mini-program environment
Choosing an Invocation Method
Select Based on Scenarios
- Mini Program development → use Mini Program SDK invocation
- Web Application Development → use Web SDK invocation
- Server-side development → Use Node.js SDK invocation
- Third-party system integration - Use HTTP API invocation
- Direct frontend access → Use Web client invocation
Performance Comparison
| Invocation Methods | Performance | Ease of Use | Feature Completeness |
|---|---|---|---|
| SDK Invocation | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| HTTP API | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ |
| Web Client | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ |
| Mini Program Invocation | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
Related Documentation
📄️ HTTP API Authentication
Learn how to obtain and use access tokens
📄️ HTTP Access Service
Configure custom domain and access path