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

2023-11-16

 一、背景

在不给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官网)

        区域性(REGIONAL):适用于同一区域中的客户端。当在 EC2 实例上运行的客户端调用同一区域中的 API,或 API 用于为具有高需求的少数客户端提供服务时,区域 API 可以降低连接开销。

        还有边缘优化(EDGE):最适合地理位置分散的客户端。API 请求将路由到最近的 CloudFront 接入点 (POP)。这是 API Gateway REST API 的默认终端节点类型。

        私有(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

exports.handler = function(event, context, callback) {        
    console.log('Received event:', JSON.stringify(event, null, 2));

    // A simple request-based authorizer example to demonstrate how to use request 
    // parameters to allow or deny a request. In this example, a request is  
    // authorized if the client-supplied headerauth1 header, QueryString1
    // query parameter, and stage variable of StageVar1 all match
    // specified values of 'headerValue1', 'queryValue1', and 'stageValue1',
    // respectively.

    // Retrieve request parameters from the Lambda function input:
    var headers = event.headers;
    var queryStringParameters = event.queryStringParameters;
    var pathParameters = event.pathParameters;
    var stageVariables = event.stageVariables;
        
    // Parse the input for the parameter values
    var tmp = event.methodArn.split(':');
    var apiGatewayArnTmp = tmp[5].split('/');
    var awsAccountId = tmp[4];
    var region = tmp[3];
    var restApiId = apiGatewayArnTmp[0];
    var stage = apiGatewayArnTmp[1];
    var method = apiGatewayArnTmp[2];
    var resource = '/'; // root resource
    if (apiGatewayArnTmp[3]) {
        resource += apiGatewayArnTmp[3];
    }
        
    // Perform authorization to return the Allow policy for correct parameters and 
    // the 'Unauthorized' error, otherwise.
    var authResponse = {};
    var condition = {};
    condition.IpAddress = {};
     
    if (headers.account === ""
        && headers.password === "") {
        callback(null, generateAllow('me', event.methodArn));
    }else {
        callback("Unauthorized");
    }
}
     
// Help function to generate an IAM policy
var generatePolicy = function(principalId, effect, resource) {
    // Required output:
    var authResponse = {};
    authResponse.principalId = principalId;
    if (effect && resource) {
        var policyDocument = {};
        policyDocument.Version = '2012-10-17'; // default version
        policyDocument.Statement = [];
        var statementOne = {};
        statementOne.Action = 'execute-api:Invoke'; // default action
        statementOne.Effect = effect;
        statementOne.Resource = resource;
        policyDocument.Statement[0] = statementOne;
        authResponse.policyDocument = policyDocument;
    }
    // Optional output with custom properties of the String, Number or Boolean type.
    authResponse.context = {
        "account": '',
        "password": '',
        "booleanKey": true
    };
    return authResponse;
}
     
var generateAllow = function(principalId, resource) {
    return generatePolicy(principalId, 'Allow', resource);
}
     
var generateDeny = function(principalId, resource) {
    return generatePolicy(principalId, 'Deny', resource);
}

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代码

import json
import requests

def call_get_api(_url,_headers):
    res = requests.get(url=_url, headers=_headers)
    return res

def download_s3(bucket,key,local_file):
    # api gateway call url
    url_ip = ""
    # generate the url
    url = url_ip + bucket + key

    # headers
    headers = {"account": "", "password": ""}

    # call the api2s3 method
    res = call_get_api(url, headers)
    res.encoding = 'utf-8'
    data = res.text
    if res.status_code == 200:
        print(res.status_code)
        print(data)
        with open(local_file, 'wb') as f:
            # str通过encode()方法可以转换为bytes
            f.write(data.encode())
    else:
        print(res)

if __name__ == '__main__':
    # s3 file
    bucket = ''
    key = ''

    # local file name
    local_file = ''
    download_s3(bucket, key, local_file)


六、通过CloudFormation新建API

yaml文件代码如下

AWSTemplateFormatVersion: '2010-09-09'
Description : Template to provision ETL Workflow for api gateway 
Parameters:
  Region:
    Description: 'Specify the Region for resource.'
    Type: String
    Default: ase1
  Iteration:
    Type: String
    Description: 'Specify the Iteration for Lambda.'
    Default: '001'
  S3Iteration:
    Type: String
    Description: 'Specify the Iteration for S3'
    Default: '001'
  IAMIteration:
    Type: String
    Description: 'Specify the Iteration for IAM roles.'
    Default: '001'

Resources: 
  ApigatewayRestAPI:
    Type: AWS::ApiGateway::RestApi
    Properties:
      Name: api-downloads3-${Iteration}
      BinaryMediaTypes:
        - "*/*"
      Description: create api to download file from s3
      Mode: overwrite
      EndpointConfiguration:
        Types:
          - REGIONAL
 
  ApigatewayAuthorizer:
    Type: AWS::ApiGateway::Authorizer
    Properties:
      AuthorizerCredentials: "arn:aws:iam::${AWS::AccountId}:role/iamr-replication-${IAMIteration}"
      AuthorizerResultTtlInSeconds : 0
      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"
      Type : REQUEST
      AuthType: custom
      RestApiId: 
        !Ref  ApigatewayRestAPI
      Name: auth-request
      IdentitySource : method.request.header.account,method.request.header.password

  ApigatewayResourceFolder:
    Type: AWS::ApiGateway::Resource
    Properties:
      RestApiId: 
        !Ref ApigatewayRestAPI
      PathPart: "{folder}"
      ParentId: !GetAtt 
        - ApigatewayRestAPI
        - RootResourceId

  ApigatewayMethodFolder:
    Type: AWS::ApiGateway::Method
    Properties:
      AuthorizerId:
        !Ref ApigatewayAuthorizer
      AuthorizationType: custom
      RequestParameters: {
        "method.request.path.folder": true,
        "method.request.header.account": true,
        "method.request.header.password": true
      }
      HttpMethod: GET
      MethodResponses:
        - StatusCode: 200
          ResponseModels: 
            application/json: Empty
      RestApiId:
        !Ref ApigatewayRestAPI
      ResourceId: !GetAtt 
        - ApigatewayResourceFolder
        - ResourceId 
      Integration:
        Type: AWS
        Credentials: "arn:aws:iam::${AWS::AccountId}:role/iamr-replication-${IAMIteration}"
        IntegrationHttpMethod: GET
        IntegrationResponses:
          - StatusCode: 200
        PassthroughBehavior: when_no_match
        Uri: "arn:aws:apigateway:${AWS::Region}:s3:path/{folder}"
        RequestParameters: {
            "integration.request.path.folder" : "method.request.path.folder"
          }

  ApigatewayResourceTablename:
    Type: AWS::ApiGateway::Resource
    Properties:
      RestApiId: 
        !Ref ApigatewayRestAPI
      PathPart: "{tablename}"
      ParentId:
        !Ref ApigatewayResourceFolder

  ApigatewayMethodTablename:
    Type: AWS::ApiGateway::Method
    Properties:
      AuthorizerId:
        !Ref ApigatewayAuthorizer
      AuthorizationType: custom
      RequestParameters: {
        "method.request.path.folder": true,
        "method.request.path.tablename": true,
        "method.request.header.account": true,
        "method.request.header.password": true
      }
      HttpMethod: GET
      MethodResponses:
        - StatusCode: 200
          ResponseModels: 
            application/json: Empty
      RestApiId:
        !Ref ApigatewayRestAPI
      ResourceId: !GetAtt 
        - ApigatewayResourceTablename
        - ResourceId 
      Integration:
        Type: AWS
        Credentials: "arn:aws:iam::${AWS::AccountId}:role/iamr-replication-${IAMIteration}"
        IntegrationHttpMethod: GET
        IntegrationResponses:
          - StatusCode: 200
        PassthroughBehavior: when_no_match
        Uri: "arn:aws:apigateway:${AWS::Region}:s3:path/{folder}/{tablename}"
        RequestParameters: {
            "integration.request.path.folder" : "method.request.path.folder",
            "integration.request.path.tablename" : "method.request.path.tablename"
          }


  ApigatewayResourcePartition:
    Type: AWS::ApiGateway::Resource
    Properties:
      RestApiId:
        !Ref ApigatewayRestAPI
      PathPart: "{partition}"
      ParentId:
        !Ref ApigatewayResourceTablename

  ApigatewayMethodPartition:
    Type: AWS::ApiGateway::Method
    Properties:
      AuthorizerId:
        !Ref ApigatewayAuthorizer
      AuthorizationType: custom
      RequestParameters: {
        "method.request.path.folder": true,
        "method.request.path.tablename": true,
        "method.request.path.partition": true,
        "method.request.header.account": true,
        "method.request.header.password": true
      }
      HttpMethod: GET
      MethodResponses:
        - StatusCode: 200
          ResponseModels: 
            application/json: Empty
      RestApiId:
        !Ref ApigatewayRestAPI
      ResourceId: !GetAtt 
        - ApigatewayResourcePartition
        - ResourceId 
      Integration:
        Type: AWS
        Credentials: "arn:aws:iam::${AWS::AccountId}:role/iamr-replication-${IAMIteration}"
        IntegrationHttpMethod: GET
        IntegrationResponses:
          - StatusCode: 200
        PassthroughBehavior: when_no_match
        Uri: "arn:aws:apigateway:${AWS::Region}:s3:path/{folder}/{tablename}/{partition}"
        RequestParameters: {
            "integration.request.path.partition" : "method.request.path.partition",
            "integration.request.path.folder" : "method.request.path.folder",
            "integration.request.path.tablename" : "method.request.path.tablename"
          }


  ApigatewayResourceFilename:
    Type: AWS::ApiGateway::Resource
    Properties:
      RestApiId: 
        !Ref ApigatewayRestAPI
      PathPart: "{filename}"
      ParentId:
        !Ref ApigatewayResourcePartition

  ApigatewayMethodFilename:
    Type: AWS::ApiGateway::Method
    Properties:
      AuthorizerId:
        !Ref ApigatewayAuthorizer
      AuthorizationType: custom
      RequestParameters: {
        "method.request.path.folder": true,
        "method.request.path.tablename": true,
        "method.request.path.partition": true,
        "method.request.path.filename": true,
        "method.request.header.account": true,
        "method.request.header.password": true
      }
      HttpMethod: GET
      MethodResponses:
        - StatusCode: 200
          ResponseModels: 
            application/json: Empty
      RestApiId:
        !Ref ApigatewayRestAPI
      ResourceId: !GetAtt 
        - ApigatewayResourceFilename
        - ResourceId 
      Integration:
        Type: AWS
        Credentials: "arn:aws:iam::${AWS::AccountId}:role/iamr-replication-${IAMIteration}"
        IntegrationHttpMethod: GET
        IntegrationResponses:
          - StatusCode: 200
        PassthroughBehavior: when_no_match
        Uri: "arn:aws:apigateway:${AWS::Region}:s3:path/{folder}/{tablename}/{partition}/{filename}"
        RequestParameters: {
            "integration.request.path.partition" : "method.request.path.partition",
            "integration.request.path.filename" : "method.request.path.filename",
            "integration.request.path.folder" : "method.request.path.folder",
            "integration.request.path.tablename" : "method.request.path.tablename"
          }
          
  ApigatewayDeploymentv1:
    DependsOn: ApigatewayMethodFilename
    Type: AWS::ApiGateway::Deployment
    Properties: 
      RestApiId:
        !Ref ApigatewayRestAPI
      StageName : v1

  PermissionToInvokeLambda: 
    Type: AWS::Lambda::Permission
    Properties: 
      FunctionName: lamb-apigw-authorizer-${Iteration}
      Action: "lambda:InvokeFunction"
      Principal: "apigateway.amazonaws.com"
      SourceArn: !Sub
        - "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${APiId}/authorizers/${AuthorizerId}"
        - APiId: 
            !Ref ApigatewayRestAPI
          AuthorizerId: 
            !Ref ApigatewayAuthorizer

Outputs:
  RootResourceId:
    Value: !GetAtt ApigatewayRestAPI.RootResourceId
  AuthorizerId:
    Value: !GetAtt ApigatewayAuthorizer.AuthorizerId

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

【AWS】API Gateway创建Rest API--从S3下载文件 的相关文章

随机推荐

  • uniapp 基础知识学习

    uniapp 基础知识学习 uniapp 基础知识学习 uniapp 介绍 https uniapp dcloud io README 有哪些uni app的作品 uni app的社区规模 为什么要去学习uni app 快速体验 功能框架
  • js显示服务器路径下的图片,JS处理文件流(如果是图片,显示在当前页面)

    用ajax请求图片资源 服务器以文件流的形式返回 1 返回类型需要设置为 blob 所以需要用原生ajax 不能使用jq 原因 jquery将返回的数据转换为了string 不支持blob类型 当然 你也可以引入组件拓展jq的能力 我知道的
  • leetcode----121.买卖股票的最佳时机

    给定一个数组 它的第 i 个元素是一支给定股票第 i 天的价格 如果你最多只允许完成一笔交易 即买入和卖出一支股票一次 设计一个算法来计算你所能获取的最大利润 注意 你不能在买入股票前卖出股票 示例 1 输入 7 1 5 3 6 4 输出
  • 电脑快捷键大全表格_【Mac新手必看基础篇】Mac电脑快捷键大全

    Mac电脑以卓越的性能和出色的外表获得了越来越多的用户 你是Mac新手吗 你是否能熟练使用Mac电脑呢 刚接触Mac电脑的小伙伴千万不要错过这篇文章 小编给大家准备了Mac使用必看基础篇 Mac快捷键大全 对于新手用户很有帮助哦 一 开机相
  • Git如何合并分支到主干及合并主干到分支

    Git如何合并分支到主干及合并主干到分支 文章目录 Git如何合并分支到主干及合并主干到分支 零 预备知识 一 创建分支 二 合并分支到主干 三 合并主干到分支 参考资料 精益开发实践用看板管理大型项目 Git如何合并分支到主干及合并主干到
  • 合并两个有序数组(超详细)

    合并两个有序数组 给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2 另有两个整数 m 和 n 分别表示 nums1 和 nums2 中的元素数目 请你 合并 nums2 到 nums1 中 使合并后的数组同样按 非递减顺序
  • 一文读懂毫米波/激光/超声波雷达的区别(转)

    不知何时 自动驾驶技术从电影中跳出来 直接被拉到人们视野中 不过 去年特斯拉却因为几起自动驾驶事故 官网不得不把自动驾驶字眼改为辅助驾驶 本期 汽车总动员 讨论的不是自动驾驶 而是被称为自动驾驶汽车 眼睛 的雷达 目前主流的 眼睛 有四类
  • 在ubuntu下编译opencv程序后,执行报下面到错误: error while loading shared libraries: libopencv_core.so.2.4: cannot op

    转自 https www douban com note 327349156 在ubuntu下编译opencv程序后 执行报下面到错误 error while loading shared libraries libopencv core
  • 使用Python 进行分析

    在当今竞争激烈的互联网时代 对于网站的SEO优化至关重要 本文将介绍一种强大的秘密武器 使用Python 进行竞争对手网站分析 通过这种技术 您可以深入了解竞争对手的网站结构 关键词排名和优化策略 为您的SEO优化工作提供有力支持 1 为什
  • 神经网络随手记-1

    目录 sigmod函数主要缺点 Relu 线性整流函数 Leaky ReLU 随机梯度下降法 sigmod函数主要缺点 在输入值变大时 梯度会变得非常小甚至消失 这意味着 在训练神经网络时 如果发生这种饱和 我们将无法根据梯度来更新权重 函
  • 传感器尺寸与像素密度对相片分辨率的影响

    在人们日常生活摄影中 相机的传感器尺寸以及像素素往往决定了一幅图像的清晰度 当然 不同的镜头 不同的CMOS质量等等都会对相片的质量产生影响 今天就简单讨论讨论传感器尺寸和像素密度对图像分辨率的影响 当传感器尺寸一定时 像素越多 也就是像素
  • Python-集合

    探索Python集合的奇妙世界 在Python编程中 集合 Set 是一种强大且有用的数据结构 它用于存储多个不重复的元素 集合的独特之处在于它的元素是无序的 并且每个元素都是唯一的 这使得集合在处理去重和进行快速成员检查时非常有效 创建集
  • 手把手带你打造自己的UI样式库(第五章)之常用页面切图的设计与开发

    常用页面切图的设计与开发 在一些大的前端团队中 前端工程师这个职位会出现一个分支 叫做重构工程师 重构工程师主要负责 HTML 和 CSS 的制作 也就是把设计稿转换成 HTML 和 CSS 代码 重构工作完成以后 把制作好的 HTML 和
  • 【第十四届蓝桥杯单片机组底层驱动测试】

    第十四届蓝桥杯单片机组底层驱动测试 下面分享的是第十四届蓝桥杯单片机组底层驱动代码的测试和相关说明 今年官方提供的资料包中底层驱动代码和以往有了变化 主要代码还是提供给了我们 只是此次没有了相关头文件iic h ds1302 onewire
  • win10剪贴板快捷键win+v

    win v可以出现最近10多次粘贴的数据
  • Ioc容器refresh总结(3)--- Spring源码从入门到精通(三十三)

    上篇文章介绍了 调用bean工厂的后置处理器 主要分为两步 他是在beanFactory预准备标准初始化之后执行invokBeanFactoryPostProcessor 先调用beanDefinitionRegistryPostProce
  • [paper] MTCNN

    MTCNN 论文全称 Joint Face Detection and Alignment using Multi task Cascaded Convolutional Networks 论文下载链接 https arxiv org ab
  • vue.js基础学习(模板语法)

    基础入门 vue js模板语法 1 模板语法 methods 给vue定义方法 this 指向当前vue实例 v html 让内容以HTML形式编译 v bind 绑定动态数据 v noce 当数据发生改变时 插值处内容不发生改变 动态属性
  • maven相关

    1 webxml attribute is required or pre existing WEB INF web xml if executing in update 原因 web项目下缺少 WEB INF web xml 在servl
  • 【AWS】API Gateway创建Rest API--从S3下载文件

    一 背景 在不给AK SK的前提下 用户查看s3上文件 从s3下载文件 二 创建API 1 打开API Gateway 点击创建API 选择REST API REST API和HTTP API区别 来自AWS官网 REST API 和 HT