参考资料
区别和比较,https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-vs-rest.html
- REST APIs,In API Gateway REST APIs, the frontend is encapsulated by method requests and method responses. The API interfaces with the backend by means of integration requests and integration responses. You can configure the integration response to map required response parameters from integration to method
- HTTP APIs,lower latency and lower cost. use HTTP APIs to send requests to AWS Lambda functions or to any publicly routable HTTP endpoint
- WebSocket APIs,the client and the server can both send messages to each other at any time. Can integrated with lambda kinesis and HTTP endpoint.
apigateway的restapi用来集成后端http服务,lambda函数和其他aws服务,将这些服务通过资源和方法暴露出去
例如,/incomes使资源,而其上的GET/POST/PUT等操作即方法
总体的请求逻辑可以分为以下两个阶段
方法请求和方法响应,应用程序和apigateway之间的通信
集成请求和集成响应,apigateway和后端之间的通信
由于以上两个阶段的请求格式和处理逻辑不同,因此需要apigateway将方法请求转换为集成请求,将集成响应转换为方法响应(通过定义schema和model实现)
创建lambda函数,使用nodejs16运行时,保留默认代码即可
export const handler = async (event) => {const response = {statusCode: 200,body: JSON.stringify('Hello World!'),};return response;
};
创建httpapi,相比restapi功能少,费用低
这里需要注意,lambda集成的负载格式分为v1和v2
https://docs.amazonaws.cn/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html
保留贪婪匹配,直接下一步自动部署
在lambda函数界面可以看到自动添加基于资源的策略
{"Version": "2012-10-17","Id": "default","Statement": [{"Sid": "a2bb716b-d866-538b-b02d-db66f38db633","Effect": "Allow","Principal": {"Service": "apigateway.amazonaws.com"},"Action": "lambda:InvokeFunction","Resource": "arn:aws-cn:lambda:cn-north-1:xxxxxxxxxxx:function:my-function","Condition": {"ArnLike": {"AWS:SourceArn": "arn:aws-cn:execute-api:cn-north-1:xxxxxxxxxxx:8qpcm7sc5d/*/*/my-function"}}}]
}
同样在apigateway控制台能看到相应的添加权限操作
尝试访问生成的终端节点
$ curl https://8qpcm7sc5d.execute-api.cn-north-1.amazonaws.com.cn/my-function
{"message":"Forbidden"}
逻辑上我们已经对外提供了接口,但是访问报错,这可能是由于两个因素导致的
因此,这里我们使用iam授权
https://docs.amazonaws.cn/apigateway/latest/developerguide/http-api-access-control-iam.html
注意,httpapi不支持基于资源的策略,因此请求方需要sigv4签名,并且具有execute-api权限
aws apigatewayv2 update-route \--api-id 8qpcm7sc5d \--route-id 9f5s6fh \--authorization-type AWS_IAM
这里的routeid有点隐蔽
我们在之前的文章中讨论过鉴权的问题,当时是使用postman工具,这里用awscurl替代下,用来快速测试apigateway很是方便
https://github.com/okigan/awscurl
使用默认凭证访问apigateway
$ awscurl --service execute-api -X POST -d @request.json https://.execute-api.us-east-1.amazonaws.com/
$ awscurl --service execute-api -X GET https://8qpcm7sc5d.execute-api.cn-north-1.amazonaws.com.cn/my-function --region cn-north-1
"Hello from Lambda!"