Access Cloud Functions via HTTP
Through the HTTP access service, you can configure cloud functions as standard HTTP interfaces and call them via HTTP requests without an SDK. This document explains how to configure HTTP access for cloud functions and how to handle requests and responses.
Prerequisites
- CloudBase environment created
- At least one cloud function deployed
Configure HTTP Access
Step 1: Create Domain Association
- Go to CloudBase Console - HTTP Access Service
- Click the "New" button in the "Domain Associated Resources" section
- Configure the following information:
| Configuration Item | Description | Example |
|---|---|---|
| Associated Resource Type | Select "Cloud Function", then choose target cloud function | hello-world |
| Domain | Select default domain, custom domain, or * (matches all domains) | Default domain |
| Trigger Path | Set HTTP access path, supports / or custom path | /api/hello |
💡 Tip: For production environments, it's recommended to bind a filed custom domain to get full service capabilities. Please refer to Custom Domain Configuration for configuration methods.

Step 2: Test Access
After configuration, access domain + trigger path to invoke the cloud function:
# Example: Access cloud function via default domain
curl https://your-env-id.service.tcloudbase.com/api/hello
Make HTTP Requests
After configuration, you can use any HTTP client to access cloud functions.
- curl
- JavaScript
- Python
# GET request
curl https://your-domain/your-function-path
# POST request
curl -X POST https://your-domain/your-function-path \
-H "Content-Type: application/json" \
-d '{"name": "CloudBase", "version": "1.0"}'
// Using fetch API
const response = await fetch('https://your-domain/your-function-path', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'CloudBase', version: '1.0' })
});
const data = await response.json();
console.log(data);
import requests
# POST request
response = requests.post(
'https://your-domain/your-function-path',
json={'name': 'CloudBase', 'version': '1.0'}
)
data = response.json()
print(data)
Handle HTTP Requests in Cloud Functions
Receive Request Information
When accessing a cloud function via HTTP, the function's event parameter will contain complete HTTP request information:
exports.main = async (event, context) => {
// event object structure
const {
path, // HTTP request path, e.g. /api/hello
httpMethod, // HTTP request method, e.g. GET, POST, PUT, DELETE
headers, // HTTP request headers object
queryStringParameters, // URL query parameters object, e.g. ?name=value
body, // HTTP request body content (string format)
isBase64Encoded, // Whether body is Base64 encoded
requestContext // CloudBase environment related information
} = event;
// Return response
return { message: 'success' };
};
Example: Handle Different Types of Requests
- GET Request
- POST Request
- RESTful API
exports.main = async (event) => {
const { queryStringParameters } = event;
// Get query parameters
const name = queryStringParameters?.name || 'Guest';
return {
statusCode: 200,
body: JSON.stringify({
message: `Hello, ${name}!`,
timestamp: Date.now()
})
};
};
Access Example:
curl "https://your-domain/greet?name=CloudBase"
# Response: {"message":"Hello, CloudBase!","timestamp":1699999999999}
exports.main = async (event) => {
const { body } = event;
// Parse JSON request body
const data = JSON.parse(body);
return {
statusCode: 200,
body: JSON.stringify({
received: data,
processed: true
})
};
};
Access Example:
curl -X POST https://your-domain/process \
-H "Content-Type: application/json" \
-d '{"userId": 123, "action": "update"}'
exports.main = async (event) => {
const { httpMethod, path, queryStringParameters, body } = event;
// Route handling
if (path === '/users' && httpMethod === 'GET') {
// Get user list
return {
statusCode: 200,
body: JSON.stringify([{ id: 1, name: 'User1' }])
};
}
if (path.startsWith('/users/') && httpMethod === 'GET') {
// Get single user
const userId = path.split('/')[2];
return {
statusCode: 200,
body: JSON.stringify({ id: userId, name: 'User' })
};
}
// 404
return {
statusCode: 404,
body: JSON.stringify({ error: 'Not Found' })
};
};
Return HTTP Response
Cloud functions support two response methods: simple response and integrated response. The system automatically recognizes the response type based on the return value format.
Simple Response
Directly return data, and the system automatically generates a standard HTTP response.
- Return String
- Return JSON
exports.main = async () => {
return "Hello CloudBase";
};
HTTP Response:
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Hello CloudBase
exports.main = async () => {
return {
success: true,
data: { id: 123, name: "CloudBase" },
timestamp: Date.now()
};
};
HTTP Response:
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{"success":true,"data":{"id":123,"name":"CloudBase"},"timestamp":1699999999999}
Integrated Response (Advanced)
When you need to precisely control HTTP status codes, response headers, etc., use the integrated response format:
{
statusCode: number, // HTTP status code (required)
headers: { // HTTP response headers (optional)
"headerName": "headerValue"
},
body: string, // Response body content (optional)
isBase64Encoded: boolean // Whether body is Base64 encoded (optional)
}
💡 Recognition Rule: When the return value contains the
statusCodefield, the system will recognize it as an integrated response.
Integrated Response Examples
- Return HTML Page
- Page Redirect
- Return Image
- Error Response
- Return JavaScript
exports.main = async () => {
return {
statusCode: 200,
headers: {
"Content-Type": "text/html; charset=utf-8"
},
body: `
<!DOCTYPE html>
<html>
<head><title>CloudBase</title></head>
<body>
<h1>Welcome to CloudBase</h1>
<p>This is an HTML page returned via cloud function</p>
</body>
</html>
`
};
};
The browser will render this HTML page directly when accessed.
exports.main = async (event) => {
const { path } = event;
return {
statusCode: 302,
headers: {
"Location": `https://docs.cloudbase.net${path}`
}
};
};
Accessing the cloud function will automatically redirect to the specified URL.
const fs = require('fs');
const path = require('path');
exports.main = async () => {
// Read image file and convert to Base64
const imagePath = path.join(__dirname, 'image.png');
const imageBuffer = fs.readFileSync(imagePath);
const base64Image = imageBuffer.toString('base64');
return {
statusCode: 200,
headers: {
"Content-Type": "image/png"
},
body: base64Image,
isBase64Encoded: true
};
};
⚠️ Note: Binary files (images, audio/video, etc.) must set
isBase64Encoded: true.
exports.main = async (event) => {
const { queryStringParameters } = event;
// Parameter validation
if (!queryStringParameters?.userId) {
return {
statusCode: 400,
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
error: "Bad Request",
message: "userId parameter cannot be empty"
})
};
}
// Business logic
const userId = queryStringParameters.userId;
try {
// ... Process business logic
return {
statusCode: 200,
body: JSON.stringify({ success: true })
};
} catch (error) {
return {
statusCode: 500,
body: JSON.stringify({
error: "Internal Server Error",
message: error.message
})
};
}
};
exports.main = async () => {
return {
statusCode: 200,
headers: {
"Content-Type": "application/javascript"
},
body: `
console.log("Hello from CloudBase!");
window.cloudbaseConfig = {
envId: "your-env-id",
region: "ap-shanghai"
};
`
};
};
Can be used to dynamically generate JavaScript configuration files.
Related Documentation
- HTTP Access Service Overview - Understand the core features and advantages of HTTP access service
- Quick Start - Quick start guide
- Route Configuration - Configure flexible routing rules
- Custom Domain Configuration - Bind custom domains
- Cloud Function Development Guide - Cloud function development tutorial