Skip to main content

Access Cloud Functions via HTTP

HTTP cloud functions support configuring custom domains via the HTTP Access Service, enabling standard HTTP API invocation.

Prerequisites

Before you begin, make sure you have:

  • Created an HTTP cloud function
  • Configured the HTTP Access Service and custom domain
  • Obtained the function's access URL

Configuring the HTTP Access Service

Step Instructions

  1. Create an HTTP cloud function: In the TCB console, create a new HTTP cloud function.
  2. Go to Function Details: After the function is created successfully, click the function name to go to the details page.
  3. Configure the access path: On the function configuration page, locate the "HTTP Access Service Path" option and click "Go to Settings".
  4. 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.

HTTP Client Invocation Example

Below are complete examples of invoking HTTP cloud functions using different methods:

# GET Request Example
curl -X GET "https://your-domain.com/your-function-path" \
-H "Content-Type: application/json"

# POST Request Example
curl -X POST "https://your-domain.com/your-function-path" \
-H "Content-Type: application/json" \
-d '{
"name": "CloudBase",
"type": "serverless"
}'

# Authenticated Request
curl -X POST "https://your-domain.com/your-function-path" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-token" \
-d '{"data": "example"}'

Request Parameters Description

URL Format

https://{custom-domain}/{service-path}
  • Custom Domain: The domain name configured in the HTTP Access Service
  • Service Path: The access path of the function, which can be set in the function configuration.

Common Request Headers

HeaderDescriptionExample Value
Content-TypeRequest content typeapplication/json
AuthorizationAuthenticationBearer your-token
User-AgentClientMyApp/1.0

Error Handling

Common HTTP Status Codes

Status CodeDescriptionHandling Suggestions
200Request successfulProcess the response data normally
400Invalid request parametersCheck the request parameter format
401UnauthorizedCheck authentication credentials
404Function not foundCheck the URL path
500Internal Server ErrorCheck the function code logic
502Bad GatewayCheck whether the function is running properly
504Gateway TimeoutOptimize 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 };
}
}
}

Performance Optimization Recommendations

1. Connection Reuse

// Use keep-alive connections
const agent = new https.Agent({
keepAlive: true,
maxSockets: 10,
});

fetch(url, {
agent: agent, // Node.js environment
});

2. Request Caching

// Simple in-memory cache implementation
const cache = new Map();

async function cachedFetch(url, options = {}, ttl = 60000) {
const cacheKey = `${url}_${JSON.stringify(options)}`;
const cached = cache.get(cacheKey);

if (cached && Date.now() - cached.timestamp < ttl) {
return cached.data;
}

const result = await fetch(url, options);
cache.set(cacheKey, {
data: result,
timestamp: Date.now(),
});

return result;
}

3. Concurrency Control

// Limit the number of concurrent requests
class RequestQueue {
constructor(maxConcurrent = 5) {
this.maxConcurrent = maxConcurrent;
this.running = 0;
this.queue = [];
}

async add(requestFn) {
return new Promise((resolve, reject) => {
this.queue.push({ requestFn, resolve, reject });
this.process();
});
}

async process() {
if (this.running >= this.maxConcurrent || this.queue.length === 0) {
return;
}

this.running++;
const { requestFn, resolve, reject } = this.queue.shift();

try {
const result = await requestFn();
resolve(result);
} catch (error) {
reject(error);
} finally {
this.running--;
this.process();
}
}
}

// Usage example
const requestQueue = new RequestQueue(3);

requestQueue.add(() => fetch('/api/function1'));
requestQueue.add(() => fetch('/api/function2'));

Security Considerations

1. HTTPS Usage

Security Reminder

Always use the HTTPS protocol in production environments to prevent data interception during transmission.

2. Authentication and Authorization

// Add authentication header
const token = localStorage.getItem('authToken');
fetch(url, {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
});

3. Input Validation

// Client-side parameter validation
function validateInput(data) {
if (!data || typeof data !== 'object') {
throw new Error('Invalid input data');
}

// Add specific validation logic
if (data.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) {
throw new Error('Invalid email format');
}

return true;
}