Cloud Function Call Methods
CloudBase cloud functions support multiple call methods to meet the needs of different scenarios and platforms. You can choose the most suitable call method based on your actual situation.
Call Methods Overview
| Call Method | Applicable Scenarios | Features |
|---|---|---|
| HTTP API | Cross-language calls, third-party system integration | Standard REST API, supports all languages |
| Web Client | Browser environment, frontend applications | Supports CORS, direct HTTP access |
| SDK Calls (Coming Soon) | Mini-programs, Web apps, mobile apps | Simple and easy to use, automatic authentication |
| Mini-Program Calls (Coming Soon) | WeChat Mini Programs | Native support, no additional configuration |
- HTTP API Call
- HTTP Access Service Call
Calling cloud functions through HTTP API supports cross-language access, suitable for third-party system integration.
Getting Access Token
For how to get access tokens, please refer to AccessToken Documentation.
API Call Format
Request URL:
POST https://{env-id}.api.tcloudbasegateway.com/v1/functions/{function-name}?webfn=true
⚠️ Note: When calling HTTP cloud functions, you must add the
webfn=trueparameter to the request URL.
Request Headers:
Authorization: Bearer {access_token}
Content-Type: application/json
Multi-Language Call Examples
cURL
# Call regular cloud function
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
}'
# Call 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"
}'
API Parameter 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 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 | Specify the version of the function to call |
HTTP cloud functions support standard HTTP calls through custom domains, suitable for browser environments and frontend applications.
Prerequisites
- Created an HTTP cloud function
- Configured HTTP access service and custom domain
- Obtained the function's access URL
Configure HTTP Access Service
- Create HTTP Cloud Function: Create a new HTTP cloud function in the CloudBase console
- Enter Function Details: After the function is created successfully, click the function name to enter the details page
- Configure Access Path: Find the "HTTP Access Service Path" option on the function configuration page and click "Go to Settings"
- Set Domain and Path: Configure custom domain and access path on the HTTP access service page
💡 Tip: For detailed HTTP access service configuration methods, please refer to HTTP Access Service Documentation.
Client Call Examples
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', // Include cookies
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
console.log('Function return 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 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 retrieved successfully:', result);
return result;
} catch (error) {
console.error('Failed to retrieve 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 response data normally |
400 | Request parameter error | Check request parameter format |
401 | Unauthorized | Check authentication information |
404 | Function does not exist | Check URL path |
500 | Internal server error | Check function code logic |
502 | Gateway error | Check if function is running properly |
504 | Request 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 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 call failed:', error);
// Handle different error types
if (error.name === 'TypeError') {
return { success: false, error: 'Network connection failed' };
} else if (error.message.includes('404')) {
return { success: false, error: 'Function does not exist' };
} else {
return { success: false, error: error.message };
}
}
}
Related Documentation
📄️ HTTP API Authentication
Learn how to get and use access tokens
📄️ HTTP Access Service
Configure custom domains and access paths