0


【AWS】API Gateway创建Rest API--从S3下载文件

一、背景

在不给AK,SK的前提下,用户查看s3上文件(从s3下载文件)

二、创建API

1、打开API Gateway,点击创建API,选择REST API

REST API和HTTP API区别:(来自AWS官网)

REST API 和 HTTP API 都是 RESTful API 产品。REST API 支持的功能比 HTTP API 多,而 HTTP API 在设计时功能就极少,因此能够以更低的价格提供。如果您需要如 API 密钥、每客户端节流、请求验证、AWS WAF 集成或私有 API 端点等功能,请选择 REST API。如果您不需要 REST API 中包含的功能,请选择 HTTP API。

2、 设置API名称,选择终端节点类型

终端节点类型:(来自AWS官网)

  1. 区域性(REGIONAL):适用于同一区域中的客户端。当在 EC2 实例上运行的客户端调用同一区域中的 API,或 API 用于为具有高需求的少数客户端提供服务时,区域 API 可以降低连接开销。
  2. 还有边缘优化(EDGE):最适合地理位置分散的客户端。API 请求将路由到最近的 CloudFront 接入点 (POP)。这是 API Gateway REST API 的默认终端节点类型。
  3. 私有(PRIVATE):是一个只能使用接口 VPC 终端节点从 Amazon Virtual Private Cloud (VPC) 访问的 API 终端节点,该接口是您在 VPC 中创建的终端节点网络接口 (ENI)

三、配置API

1、进入刚创建好的API,点击资源页,创建资源及方法

1.1创建资源, / 代表根目录,右击选择创建资源

1.2创建方法,上传文件到s3,所以选择GET方法

1.3点击刚创建的方法,进入集成请求

1.3配置:

集成类型:AWS 服务

AWS区域:(选择相应的区域)

AWS服务:S3

AWS子域:(不用填)

HTTP方法:GET

操作类型:路径覆盖

路径覆盖(可选):{bucket}/{object}

执行角色:(填写有执行API角色的ARN)

路径覆盖也可以把路径某部分hard code

在下方URL路径参数中填写路径参数映射关系

2、配置设置

翻到最下面,修改二进制媒体类型为 /

Content-Encoding可以根据需要修改

默认上传文件大小不超过10M

三、添加授权方

1、新建Lambda函数,来验证授权方,运行时选择 Node.js 16.x

代码如下:当header中account和password匹配上,则allow,否则deny

  1. exports.handler = function(event, context, callback) {
  2. console.log('Received event:', JSON.stringify(event, null, 2));
  3. // A simple request-based authorizer example to demonstrate how to use request
  4. // parameters to allow or deny a request. In this example, a request is
  5. // authorized if the client-supplied headerauth1 header, QueryString1
  6. // query parameter, and stage variable of StageVar1 all match
  7. // specified values of 'headerValue1', 'queryValue1', and 'stageValue1',
  8. // respectively.
  9. // Retrieve request parameters from the Lambda function input:
  10. var headers = event.headers;
  11. var queryStringParameters = event.queryStringParameters;
  12. var pathParameters = event.pathParameters;
  13. var stageVariables = event.stageVariables;
  14. // Parse the input for the parameter values
  15. var tmp = event.methodArn.split(':');
  16. var apiGatewayArnTmp = tmp[5].split('/');
  17. var awsAccountId = tmp[4];
  18. var region = tmp[3];
  19. var restApiId = apiGatewayArnTmp[0];
  20. var stage = apiGatewayArnTmp[1];
  21. var method = apiGatewayArnTmp[2];
  22. var resource = '/'; // root resource
  23. if (apiGatewayArnTmp[3]) {
  24. resource += apiGatewayArnTmp[3];
  25. }
  26. // Perform authorization to return the Allow policy for correct parameters and
  27. // the 'Unauthorized' error, otherwise.
  28. var authResponse = {};
  29. var condition = {};
  30. condition.IpAddress = {};
  31. if (headers.account === ""
  32. && headers.password === "") {
  33. callback(null, generateAllow('me', event.methodArn));
  34. }else {
  35. callback("Unauthorized");
  36. }
  37. }
  38. // Help function to generate an IAM policy
  39. var generatePolicy = function(principalId, effect, resource) {
  40. // Required output:
  41. var authResponse = {};
  42. authResponse.principalId = principalId;
  43. if (effect && resource) {
  44. var policyDocument = {};
  45. policyDocument.Version = '2012-10-17'; // default version
  46. policyDocument.Statement = [];
  47. var statementOne = {};
  48. statementOne.Action = 'execute-api:Invoke'; // default action
  49. statementOne.Effect = effect;
  50. statementOne.Resource = resource;
  51. policyDocument.Statement[0] = statementOne;
  52. authResponse.policyDocument = policyDocument;
  53. }
  54. // Optional output with custom properties of the String, Number or Boolean type.
  55. authResponse.context = {
  56. "account": '',
  57. "password": '',
  58. "booleanKey": true
  59. };
  60. return authResponse;
  61. }
  62. var generateAllow = function(principalId, resource) {
  63. return generatePolicy(principalId, 'Allow', resource);
  64. }
  65. var generateDeny = function(principalId, resource) {
  66. return generatePolicy(principalId, 'Deny', resource);
  67. }

2、创建授权方

授权方名称

类型:选择Lambda

Lambda函数:填写刚创建好的Lambda函数名称

Lambda调用角色:填写调用Lambda函数的角色

Lambda事件负载:选择请求

身份来源:选择标头,添加account和password

授权缓存:取消启用

三、配置授权方

选择 添加授权方的路径资源方法中的方法请求

授权选择配置好的授权方名称

请求验证程序:无

需要API密钥:否

HTTP请求标头:将account和password配置进来

四、部署API

API配置完成后,右击根目录,部署API, 选择部署阶段,点击部署

注意:每次对API进行更改后要重新部署一下

五、测试API

测试通过两种方式:①Postman ②python代码

获取URL链接

1、Postman

进入Postman,添加PUT请求,复制URL链接,在其后添加要下载文件的S3的路径,点击send,即可在下方看到请求结果

2、python代码

  1. import json
  2. import requests
  3. def call_get_api(_url,_headers):
  4. res = requests.get(url=_url, headers=_headers)
  5. return res
  6. def download_s3(bucket,key,local_file):
  7. # api gateway call url
  8. url_ip = ""
  9. # generate the url
  10. url = url_ip + bucket + key
  11. # headers
  12. headers = {"account": "", "password": ""}
  13. # call the api2s3 method
  14. res = call_get_api(url, headers)
  15. res.encoding = 'utf-8'
  16. data = res.text
  17. if res.status_code == 200:
  18. print(res.status_code)
  19. print(data)
  20. with open(local_file, 'wb') as f:
  21. # str通过encode()方法可以转换为bytes
  22. f.write(data.encode())
  23. else:
  24. print(res)
  25. if __name__ == '__main__':
  26. # s3 file
  27. bucket = ''
  28. key = ''
  29. # local file name
  30. local_file = ''
  31. download_s3(bucket, key, local_file)

六、通过CloudFormation新建API

yaml文件代码如下

  1. AWSTemplateFormatVersion: '2010-09-09'
  2. Description : Template to provision ETL Workflow for api gateway
  3. Parameters:
  4. Region:
  5. Description: 'Specify the Region for resource.'
  6. Type: String
  7. Default: ase1
  8. Iteration:
  9. Type: String
  10. Description: 'Specify the Iteration for Lambda.'
  11. Default: '001'
  12. S3Iteration:
  13. Type: String
  14. Description: 'Specify the Iteration for S3'
  15. Default: '001'
  16. IAMIteration:
  17. Type: String
  18. Description: 'Specify the Iteration for IAM roles.'
  19. Default: '001'
  20. Resources:
  21. ApigatewayRestAPI:
  22. Type: AWS::ApiGateway::RestApi
  23. Properties:
  24. Name: api-downloads3-${Iteration}
  25. BinaryMediaTypes:
  26. - "*/*"
  27. Description: create api to download file from s3
  28. Mode: overwrite
  29. EndpointConfiguration:
  30. Types:
  31. - REGIONAL
  32. ApigatewayAuthorizer:
  33. Type: AWS::ApiGateway::Authorizer
  34. Properties:
  35. AuthorizerCredentials: "arn:aws:iam::${AWS::AccountId}:role/iamr-replication-${IAMIteration}"
  36. AuthorizerResultTtlInSeconds : 0
  37. AuthorizerUri: "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:lamb-apigw-authorizer-${S3Iteration}/invocations"
  38. Type : REQUEST
  39. AuthType: custom
  40. RestApiId:
  41. !Ref ApigatewayRestAPI
  42. Name: auth-request
  43. IdentitySource : method.request.header.account,method.request.header.password
  44. ApigatewayResourceFolder:
  45. Type: AWS::ApiGateway::Resource
  46. Properties:
  47. RestApiId:
  48. !Ref ApigatewayRestAPI
  49. PathPart: "{folder}"
  50. ParentId: !GetAtt
  51. - ApigatewayRestAPI
  52. - RootResourceId
  53. ApigatewayMethodFolder:
  54. Type: AWS::ApiGateway::Method
  55. Properties:
  56. AuthorizerId:
  57. !Ref ApigatewayAuthorizer
  58. AuthorizationType: custom
  59. RequestParameters: {
  60. "method.request.path.folder": true,
  61. "method.request.header.account": true,
  62. "method.request.header.password": true
  63. }
  64. HttpMethod: GET
  65. MethodResponses:
  66. - StatusCode: 200
  67. ResponseModels:
  68. application/json: Empty
  69. RestApiId:
  70. !Ref ApigatewayRestAPI
  71. ResourceId: !GetAtt
  72. - ApigatewayResourceFolder
  73. - ResourceId
  74. Integration:
  75. Type: AWS
  76. Credentials: "arn:aws:iam::${AWS::AccountId}:role/iamr-replication-${IAMIteration}"
  77. IntegrationHttpMethod: GET
  78. IntegrationResponses:
  79. - StatusCode: 200
  80. PassthroughBehavior: when_no_match
  81. Uri: "arn:aws:apigateway:${AWS::Region}:s3:path/{folder}"
  82. RequestParameters: {
  83. "integration.request.path.folder" : "method.request.path.folder"
  84. }
  85. ApigatewayResourceTablename:
  86. Type: AWS::ApiGateway::Resource
  87. Properties:
  88. RestApiId:
  89. !Ref ApigatewayRestAPI
  90. PathPart: "{tablename}"
  91. ParentId:
  92. !Ref ApigatewayResourceFolder
  93. ApigatewayMethodTablename:
  94. Type: AWS::ApiGateway::Method
  95. Properties:
  96. AuthorizerId:
  97. !Ref ApigatewayAuthorizer
  98. AuthorizationType: custom
  99. RequestParameters: {
  100. "method.request.path.folder": true,
  101. "method.request.path.tablename": true,
  102. "method.request.header.account": true,
  103. "method.request.header.password": true
  104. }
  105. HttpMethod: GET
  106. MethodResponses:
  107. - StatusCode: 200
  108. ResponseModels:
  109. application/json: Empty
  110. RestApiId:
  111. !Ref ApigatewayRestAPI
  112. ResourceId: !GetAtt
  113. - ApigatewayResourceTablename
  114. - ResourceId
  115. Integration:
  116. Type: AWS
  117. Credentials: "arn:aws:iam::${AWS::AccountId}:role/iamr-replication-${IAMIteration}"
  118. IntegrationHttpMethod: GET
  119. IntegrationResponses:
  120. - StatusCode: 200
  121. PassthroughBehavior: when_no_match
  122. Uri: "arn:aws:apigateway:${AWS::Region}:s3:path/{folder}/{tablename}"
  123. RequestParameters: {
  124. "integration.request.path.folder" : "method.request.path.folder",
  125. "integration.request.path.tablename" : "method.request.path.tablename"
  126. }
  127. ApigatewayResourcePartition:
  128. Type: AWS::ApiGateway::Resource
  129. Properties:
  130. RestApiId:
  131. !Ref ApigatewayRestAPI
  132. PathPart: "{partition}"
  133. ParentId:
  134. !Ref ApigatewayResourceTablename
  135. ApigatewayMethodPartition:
  136. Type: AWS::ApiGateway::Method
  137. Properties:
  138. AuthorizerId:
  139. !Ref ApigatewayAuthorizer
  140. AuthorizationType: custom
  141. RequestParameters: {
  142. "method.request.path.folder": true,
  143. "method.request.path.tablename": true,
  144. "method.request.path.partition": true,
  145. "method.request.header.account": true,
  146. "method.request.header.password": true
  147. }
  148. HttpMethod: GET
  149. MethodResponses:
  150. - StatusCode: 200
  151. ResponseModels:
  152. application/json: Empty
  153. RestApiId:
  154. !Ref ApigatewayRestAPI
  155. ResourceId: !GetAtt
  156. - ApigatewayResourcePartition
  157. - ResourceId
  158. Integration:
  159. Type: AWS
  160. Credentials: "arn:aws:iam::${AWS::AccountId}:role/iamr-replication-${IAMIteration}"
  161. IntegrationHttpMethod: GET
  162. IntegrationResponses:
  163. - StatusCode: 200
  164. PassthroughBehavior: when_no_match
  165. Uri: "arn:aws:apigateway:${AWS::Region}:s3:path/{folder}/{tablename}/{partition}"
  166. RequestParameters: {
  167. "integration.request.path.partition" : "method.request.path.partition",
  168. "integration.request.path.folder" : "method.request.path.folder",
  169. "integration.request.path.tablename" : "method.request.path.tablename"
  170. }
  171. ApigatewayResourceFilename:
  172. Type: AWS::ApiGateway::Resource
  173. Properties:
  174. RestApiId:
  175. !Ref ApigatewayRestAPI
  176. PathPart: "{filename}"
  177. ParentId:
  178. !Ref ApigatewayResourcePartition
  179. ApigatewayMethodFilename:
  180. Type: AWS::ApiGateway::Method
  181. Properties:
  182. AuthorizerId:
  183. !Ref ApigatewayAuthorizer
  184. AuthorizationType: custom
  185. RequestParameters: {
  186. "method.request.path.folder": true,
  187. "method.request.path.tablename": true,
  188. "method.request.path.partition": true,
  189. "method.request.path.filename": true,
  190. "method.request.header.account": true,
  191. "method.request.header.password": true
  192. }
  193. HttpMethod: GET
  194. MethodResponses:
  195. - StatusCode: 200
  196. ResponseModels:
  197. application/json: Empty
  198. RestApiId:
  199. !Ref ApigatewayRestAPI
  200. ResourceId: !GetAtt
  201. - ApigatewayResourceFilename
  202. - ResourceId
  203. Integration:
  204. Type: AWS
  205. Credentials: "arn:aws:iam::${AWS::AccountId}:role/iamr-replication-${IAMIteration}"
  206. IntegrationHttpMethod: GET
  207. IntegrationResponses:
  208. - StatusCode: 200
  209. PassthroughBehavior: when_no_match
  210. Uri: "arn:aws:apigateway:${AWS::Region}:s3:path/{folder}/{tablename}/{partition}/{filename}"
  211. RequestParameters: {
  212. "integration.request.path.partition" : "method.request.path.partition",
  213. "integration.request.path.filename" : "method.request.path.filename",
  214. "integration.request.path.folder" : "method.request.path.folder",
  215. "integration.request.path.tablename" : "method.request.path.tablename"
  216. }
  217. ApigatewayDeploymentv1:
  218. DependsOn: ApigatewayMethodFilename
  219. Type: AWS::ApiGateway::Deployment
  220. Properties:
  221. RestApiId:
  222. !Ref ApigatewayRestAPI
  223. StageName : v1
  224. PermissionToInvokeLambda:
  225. Type: AWS::Lambda::Permission
  226. Properties:
  227. FunctionName: lamb-apigw-authorizer-${Iteration}
  228. Action: "lambda:InvokeFunction"
  229. Principal: "apigateway.amazonaws.com"
  230. SourceArn: !Sub
  231. - "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${APiId}/authorizers/${AuthorizerId}"
  232. - APiId:
  233. !Ref ApigatewayRestAPI
  234. AuthorizerId:
  235. !Ref ApigatewayAuthorizer
  236. Outputs:
  237. RootResourceId:
  238. Value: !GetAtt ApigatewayRestAPI.RootResourceId
  239. AuthorizerId:
  240. Value: !GetAtt ApigatewayAuthorizer.AuthorizerId
标签: aws gateway 云计算

本文转载自: https://blog.csdn.net/weixin_41758646/article/details/128456737
版权归原作者 某可儿同学的博客 所有, 如有侵权,请联系我们删除。

“【AWS】API Gateway创建Rest API--从S3下载文件”的评论:

还没有评论