Writing HTTP Cloud Functions
"HTTP Cloud Functions" are a type of cloud function specifically designed for web service scenarios, providing native HTTP support, real-time communication capabilities, and multi-function routing features.
💡 About Basic Capabilities: This article focuses on the unique capabilities of HTTP cloud functions (HTTP handling, SSE, WebSocket, function routing, etc.). For general capabilities of cloud functions (dependency installation, environment variables, timezone handling, etc.), please refer to Writing Regular Cloud Functions.
Quick Start
- Node.js Guide
- Python Guide
Step 1: Create Function Entry File
Create index.js as the HTTP function entry file:
exports.main = function (event, context) {
return `Hello world!`;
};
Step 2: Create Bootstrap Script (Required)
Create a scf_bootstrap file (no file extension) in the project root directory with the command to start the project:
#!/bin/bash
node index.js
For details about the bootstrap script, please refer to: Bootstrap File Guide
Project Structure
The complete project directory structure is as follows:
my-web-function/
├── scf_bootstrap # Bootstrap script (required, no extension)
├── package.json # Project configuration
├── index.js # Function entry file
└── node_modules/ # Dependencies (generated after npm install)
Step 1: Create Function Entry File
Create main.py as the HTTP function entry file:
from http.server import HTTPServer, BaseHTTPRequestHandler
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-Type', 'text/plain')
self.end_headers()
self.wfile.write(b'Hello World!')
if __name__ == '__main__':
server = HTTPServer(('0.0.0.0', 9000), Handler)
print('Server listening at http://localhost:9000')
server.serve_forever()
Step 2: Create Bootstrap Script (Required)
Create a scf_bootstrap file (no file extension) in the project root directory with the command to start the project:
#!/bin/bash
/var/lang/python3/bin/python3 main.py
For details about the bootstrap script, please refer to: Bootstrap File Guide
Project Structure
The complete project directory structure is as follows:
python-http-function/
├── scf_bootstrap # Bootstrap script (required, no extension)
└── main.py # Function entry file
Reference Resources:
- More examples: Example Code Repository
- Template code: JavaScript Template | TypeScript Template
- Complete quick start tutorial: Functions Framework Quick Start
💡 Tip: HTTP cloud functions support the "Function Routing" feature, allowing multiple sub-functions to run on the same instance. See HTTP Cloud Function Routing for details.
Function Structure and Parameters
HTTP cloud functions support direct development using web frameworks, such as: Express, Koa, NestJS in the Node.js environment, or Flask, Django in the Python environment, or web frameworks in other languages.
Function Routing
HTTP cloud functions support web frameworks, so you can implement multi-routing through the corresponding web framework.
You can also implement it based on the @cloudbase/functions-framework. It supports splitting a large function into multiple sub-functions and routing different requests to different handler functions based on the request path.
Please refer to: HTTP Cloud Function Routing
Real-Time Communication Capabilities
HTTP cloud functions provide two real-time communication methods: "SSE (Server-Sent Events)" and "WebSocket".
SSE (Server-Sent Events)
"SSE" is an HTTP-based server push technology that supports unidirectional real-time data streaming (server → client).
Key Features:
- Based on HTTP protocol, good compatibility, supported by default with no configuration needed
- Automatic client reconnection
- Simple implementation, low resource usage
- Suitable for AI conversation streaming output, real-time logs, progress updates, and similar scenarios
Detailed Documentation: For complete SSE usage guide, message format specifications, and common problem solutions, please refer to SSE Protocol Support.
WebSocket
"WebSocket" is a full-duplex communication protocol that supports bidirectional real-time communication (server ↔ client).
Key Features:
- Bidirectional real-time communication, persistent connection, low latency
- Requires enabling WebSocket protocol support in the console
- Server must listen on port 9000
- Suitable for real-time chat, collaborative editing, game servers, and similar scenarios
Detailed Documentation: For complete WebSocket usage guide, console configuration steps, usage limits, and common problem solutions, please refer to WebSocket Protocol Support.
Technology Comparison
| Feature | SSE | WebSocket |
|---|---|---|
| Communication | Unidirectional (server → client) | Bidirectional (server ↔ client) |
| Protocol | HTTP | WebSocket protocol |
| Implementation Complexity | Simple | Relatively complex |
| Configuration Requirements | No configuration needed | Requires console enablement |
| Auto Reconnection | Yes | No (manual implementation needed) |
| Use Cases | Unidirectional data push | Real-time bidirectional communication |
Selection Guide:
- Only need server-side data push (e.g., AI conversations, logs, progress) → Choose SSE
- Need bidirectional real-time communication (e.g., chat, collaboration, games) → Choose WebSocket
Writing Function Code with TypeScript
Installing Type Definitions
npm install @cloudbase/functions-typings@v-1
Basic Type Definitions
import { TcbEventFunction } from '@cloudbase/functions-typings';
TcbEventFunction is a generic type:
TcbEventFunction<EventT = unknown, ResultT extends ReturnT = void>
EventT: Defines theeventparameter typeResultT: Defines the function return value type
Defining event Parameter Type
JSON Request Body:
type JsonEvent = { a: number; b: string; c: boolean };
export const main: TcbEventFunction<JsonEvent> = function (event, context) {
event.a; // number
event.b; // string
};
FormData File Upload:
import { TcbEventFunction, File } from '@cloudbase/functions-typings';
type FormEvent = { str: string; file: File };
export const main: TcbEventFunction<FormEvent> = function (event, context) {
event.str;
event.file.filepath;
};
Defining Return Value Type
Regular Response:
export const main: TcbEventFunction<void, string> = function (event, context) {
return 'done.';
};
Integration Response:
import { TcbEventFunction, IntegrationResponse } from '@cloudbase/functions-typings';
export const main: TcbEventFunction<void, IntegrationResponse<string>> = function (event, context) {
return {
statusCode: 200,
headers: {},
body: 'Hello world',
};
};
Async Function:
export const main: TcbEventFunction<void, Promise<string>> = async function (event, context) {
return new Promise((resolve) => {
setImmediate(() => {
resolve('done.');
});
});
};
Complete Examples
import { TcbEventFunction, File, IntegrationResponse } from '@cloudbase/functions-typings';
// GET with no request body
export const main: TcbEventFunction = function (event, context) {};
// JSON request body
type JsonEvent = { a: number; b: string };
export const main: TcbEventFunction<JsonEvent> = function (event, context) {
event.a;
event.b;
};
// FormData upload
type FormEvent = { str: string; file: File };
export const main: TcbEventFunction<FormEvent> = function (event, context) {
event.str;
event.file.filepath;
};
// Binary stream
export const main: TcbEventFunction<Buffer> = function (event, context) {
event.byteLength;
};
// Accessing Context information
export const main: TcbEventFunction<void, void> = function (event, context) {
context.extendedContext?.envId;
context.extendedContext?.userId;
};
// Regular response
export const main: TcbEventFunction<void, string> = function (event, context) {
return 'done.';
};
// Integration response
export const main: TcbEventFunction<void, IntegrationResponse<string>> = function (event, context) {
return {
statusCode: 200,
headers: {},
body: '',
};
};
// Async function
export const main: TcbEventFunction<void, Promise<string>> = async function (event, context) {
return new Promise((resolve) => {
setImmediate(() => {
resolve('done.');
});
});
};
// SSE
export const main: TcbEventFunction<void, Promise<string>> = async function (event, context) {
const sse = context.sse?.();
if (sse && !sse.closed) {
sse.on('close', () => {
console.log('sse closed');
});
sse.send({ data: 'hello from sse function' });
sse.send([{ data: 'This is the first message.' }, { data: 'This is the second message.' }]);
}
return '';
};
// WebSocket
export const main: TcbEventFunction = async function (event, context) {
if (context.ws) {
context.ws.on('open', (msg) => {
console.log('open: ', msg);
});
context.ws.on('error', (msg) => {
console.log('error: ', msg);
});
context.ws.on('close', (msg) => {
console.log('close: ', msg);
});
context.ws.on('message', (msg) => {
console.log('message: ', msg);
});
context.ws.send('hello from websocket function');
}
};
main.handleUpgrade = async function (context) {
return {
allowWebSocket: true,
};
};
Project Organization Structure
TypeScript-Based Multi-Function Project
.
├── README.md
├── Dockerfile
├── src/
│ ├── func-a/
│ │ ├── built/ # Compiled code
│ │ ├── src/ # TypeScript source code
│ │ ├── package.json
│ │ ├── cloudbase-functions.json
│ │ └── tsconfig.json
│ └── func-b/
│ ├── built/
│ ├── src/
│ ├── package.json
│ └── tsconfig.json
├── package.json
└── tsconfig.json
Project structure reference: TypeScript Template Project
Single Function Project
.
├── README.md
├── built/ # Compiled code
├── src/ # TypeScript source code
├── Dockerfile
├── package.json
├── cloudbase-functions.json
└── tsconfig.json
💡 Tip: JavaScript projects do not require the
src,built,tsconfig.jsondirectories and files.