接入教程
1. 获取已部署API的端点URL
2. 在SDK中显式配置该端点
3. 调用管理API进行运行时操作
4. 监控API状态和性能
5. 根据需求调整配置参数
使用Python SDK向连接发送消息
import boto3
from botocore.config import Config
# 配置客户端,指向您部署的API网关管理端点
# 请将YOUR_API_ENDPOINT替换为您的实际端点
client = boto3.client(
'apigatewaymanagementapi',
endpoint_url='https://api-id.execute-api.region.amazonaws.com/stage',
region_name='region',
config=Config(signature_version='v4')
)
# 向特定连接发送消息
response = client.post_to_connection(
Data=b'Hello from the server!',
ConnectionId='YOUR_CONNECTION_ID'
)
print(f'Message sent: {response}')
使用PHP SDK获取连接信息
<?php
require 'vendor/autoload.php';
use Aws\ApiGatewayManagementApi\ApiGatewayManagementApiClient;
use Aws\Exception\AwsException;
// 创建客户端,配置端点
// 请将YOUR_API_ENDPOINT替换为您的实际端点
$client = new ApiGatewayManagementApiClient([
'version' => 'latest',
'region' => 'region',
'endpoint' => 'https://api-id.execute-api.region.amazonaws.com/stage'
]);
try {
// 获取连接信息
$result = $client->getConnection([
'ConnectionId' => 'YOUR_CONNECTION_ID'
]);
echo "Connection info: " . print_r($result['ConnectionInfo'], true);
} catch (AwsException $e) {
echo "Error: " . $e->getAwsErrorMessage();
}
?>
使用JavaScript SDK断开连接
const { ApiGatewayManagementApiClient, DeleteConnectionCommand } = require('@aws-sdk/client-apigatewaymanagementapi');
// 配置客户端,指向您部署的API网关管理端点
// 请将YOUR_API_ENDPOINT替换为您的实际端点
const client = new ApiGatewayManagementApiClient({
region: 'region',
endpoint: 'https://api-id.execute-api.region.amazonaws.com/stage'
});
async function disconnectClient(connectionId) {
const command = new DeleteConnectionCommand({
ConnectionId: connectionId
});
try {
const response = await client.send(command);
console.log(`Connection ${connectionId} disconnected successfully.`);
return response;
} catch (error) {
console.error(`Error disconnecting ${connectionId}:`, error);
throw error;
}
}
// 使用示例
// disconnectClient('YOUR_CONNECTION_ID');
常见问题
如何获取API网关管理API的端点URL?
端点URL基于您部署的API Gateway REST API。格式为:https://{api-id}.execute-api.{region}.amazonaws.com/{stage}。您需要从API Gateway控制台或AWS CLI获取具体的api-id、region和stage值。
使用此API需要哪些权限?
您的IAM角色或用户需要具有执行apigateway:management API操作的权限,例如执行PostToConnection、GetConnection、DeleteConnection等操作的权限。通常需要附加如'execute-api:ManageConnections'之类的策略。
此API的主要用途是什么?
Amazon API Gateway 管理API主要用于实时通信场景,如WebSocket API或HTTP API的持久连接。它允许后端服务直接向特定客户端连接发送消息、获取连接状态或主动断开连接,无需经过常规的API Gateway请求/响应流程。
Aitishiku.com