You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过HTTP调用API Gateway WebSocket API并实现请求签名

使用Python Requests调用AWS WebSocket API管理接口

AWS WebSocket API的post_to_connection、delete_connection、get_connection这类操作属于API Gateway的管理型接口,必须通过AWS Signature Version 4签名才能发起HTTP请求,因为这类接口受IAM权限管控。以下是具体实现步骤:

核心前提

  1. 拥有具备对应权限的AWS凭证(Access Key/Secret Key,或IAM角色临时凭证)
  2. 获取目标WebSocket API的基础信息:API ID、部署阶段(Stage)、所属区域、目标连接ID(从$connect事件的上下文参数中获取)

实现步骤

1. 安装依赖

用requests-aws4auth库简化AWS V4签名流程,避免手动编写复杂的签名逻辑:

pip install requests requests-aws4auth

2. 编写请求代码

以下是三种接口的调用示例:

import requests
from requests_aws4auth import AWS4Auth

# 替换为你的实际参数
AWS_ACCESS_KEY = "your-access-key"
AWS_SECRET_KEY = "your-secret-key"
REGION = "us-east-1"
API_ID = "your-api-id"
STAGE = "prod"
CONNECTION_ID = "target-connection-id"

# 初始化AWS V4认证器
aws_auth = AWS4Auth(AWS_ACCESS_KEY, AWS_SECRET_KEY, REGION, "execute-api")

# 调用post_to_connection(发送消息到指定连接)
post_url = f"https://{API_ID}.execute-api.{REGION}.amazonaws.com/{STAGE}/@connections/{CONNECTION_ID}"
payload = {"content": "Hello via requests!"}
post_response = requests.post(post_url, json=payload, auth=aws_auth)
print(f"POST Status Code: {post_response.status_code}")

# 调用get_connection(获取连接的元数据)
get_url = f"https://{API_ID}.execute-api.{REGION}.amazonaws.com/{STAGE}/@connections/{CONNECTION_ID}"
get_response = requests.get(get_url, auth=aws_auth)
print(f"GET Response: {get_response.json()}")

# 调用delete_connection(断开指定连接)
delete_url = f"https://{API_ID}.execute-api.{REGION}.amazonaws.com/{STAGE}/@connections/{CONNECTION_ID}"
delete_response = requests.delete(delete_url, auth=aws_auth)
print(f"DELETE Status Code: {delete_response.status_code}")

3. 配置IAM权限

确保你的AWS身份(用户/角色)拥有execute-api:Invoke权限,示例IAM策略如下:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "execute-api:Invoke",
            "Resource": [
                "arn:aws:execute-api:${REGION}:${ACCOUNT_ID}:${API_ID}/${STAGE}/POST/@connections/*",
                "arn:aws:execute-api:${REGION}:${ACCOUNT_ID}:${API_ID}/${STAGE}/GET/@connections/*",
                "arn:aws:execute-api:${REGION}:${ACCOUNT_ID}:${API_ID}/${STAGE}/DELETE/@connections/*"
            ]
        }
    ]
}

注意事项

  • 在AWS内部服务(如Lambda、EC2)中运行时,无需硬编码凭证,可通过boto3.Session().get_credentials()获取临时IAM凭证传入AWS4Auth
  • 手动实现AWS V4签名极易出错,强烈依赖成熟的签名库来处理请求头、签名串等细节

内容的提问来源于stack exchange,提问作者DilLip_Chowdary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 04:06:13