Skip to main content

Calling CloudBase Resources

In cloud functions, you can conveniently call various CloudBase resources, including databases, cloud storage, and other cloud functions. Node.js cloud functions use @cloudbase/node-sdk, while other languages use HTTP API.

Node.js Cloud Functions

Node.js cloud functions use @cloudbase/node-sdk to call CloudBase resources. In the cloud function environment, no authentication parameters need to be configured, and you can call them directly.

Install SDK

npm install @cloudbase/node-sdk --save

Initialization

Initialize the SDK in cloud functions without configuring authentication parameters such as secretId and secretKey:

const tcb = require('@cloudbase/node-sdk')

const app = tcb.init({
env: tcb.SYMBOL_DEFAULT_ENV // Use the default environment ID of the current cloud function
})

Database Calling Example

const tcb = require('@cloudbase/node-sdk')
const app = tcb.init({
env: tcb.SYMBOL_DEFAULT_ENV
})

exports.main = async (event, context) => {
const db = app.database()

// Query a single record
const user = await db.collection('users')
.doc('user-id-123')
.get()

// Query multiple records
const todos = await db.collection('todos')
.where({
completed: false
})
.orderBy('createdAt''desc')
.limit(10)
.get()

return {
user: user.data,
todos: todos.data
}
}

Other Language Cloud Functions

Cloud functions in other languages (Python, Java, Go, PHP, etc.) need to use the HTTP API to call CloudBase resources.

HTTP API provides an interface to access CloudBase platform functions through HTTP protocol. For detailed API documentation, please refer to HTTP API Documentation

Example: Python Cloud Function Calling MySQL Database

For obtaining access_token, please refer to Get AccessToken

import requests
import os

def main_handler(event, context):
# Get environment variables
env_id = os.environ.get('TCB_ENV')

# Query movies in the film table directed by Christopher Nolan
url = f'https://{env_id}.api.tcloudbasegateway.com/v1/rdb/rest/film'
params = {
'director': 'eq.Christopher Nolan',
'select': 'title,director,release_year,duration'
}

headers = {
'Authorization': 'Bearer <access_token>',
'Content-Type': 'application/json'
}

response = requests.get(url, params=params, headers=headers)

if response.status_code == 200:
return {
'code': 0,
'data': response.json()
}
else:
return {
'code': -1,
'message': response.text
}

💡 Tips:

  • In the cloud function environment, you can obtain the environment ID through the environment variable TCB_ENV, and the access token through TCB_CONTEXT_KEYS
  • For languages such as Python, Java, and Go, it is recommended to use HTTP API to call CloudBase resources
  • For detailed operators and query parameters, please refer to MySQL Database Query Documentation
  • For complete HTTP API interfaces, please refer to HTTP API Documentation

Reference Documentation