aws::apigateway的cdk构造库
aws-cdk.aws-apigatewa的Python项目详细描述
Amazon API网关构造库
amazon api网关是一个完全托管的服务,它使开发人员很容易 以任何规模发布、维护、监视和保护api。创建一个api 从后端服务访问数据、业务逻辑或功能,如 作为运行在AmazonElasticComputeCloud(AmazonEC2)上的应用程序,代码 在AWS Lambda或任何Web应用程序上运行。
定义API
api被定义为资源和方法的层次结构。添加资源
和
addMethod
可用于构建此层次结构。根资源是
api.root
例如,下面的代码定义了一个api,该api包含以下http
端点:any/,get/books
,post/books
,get/books/{book_id}
,delete/books/{book_id}
constapi=newapigateway.RestApi(this,'books-api');api.root.addMethod('ANY');constbooks=api.root.addResource('books');books.addMethod('GET');books.addMethod('POST');constbook=books.addResource('{book_id}');book.addMethod('GET');book.addMethod('DELETE');
aws lambda支持的api
一个非常常见的做法是使用amazon api网关和aws lambda作为
后端集成。lambdarestapi的构造使它变得简单:
下面的代码定义了一个rest api,它将所有请求路由到 指定的aws lambda函数:
constbackend=newlambda.Function(...);newapigateway.LambdaRestApi(this,'myapi',{handler: backend,});
您还可以提供proxy:false
,在这种情况下,您必须显式地
定义API模型:
constbackend=newlambda.Function(...);constapi=newapigateway.LambdaRestApi(this,'myapi',{handler: backend,proxy: false});constitems=api.root.addResource('items');items.addMethod('GET');// GET /itemsitems.addMethod('POST');// POST /itemsconstitem=items.addResource('{item}');item.addMethod('GET');// GET /items/{item}// the default integration for methods is "handler", but one can// customize this behavior per method or even a sub path.item.addMethod('DELETE',newapigateway.HttpIntegration('http://amazon.com'));
集成目标
方法与后端集成关联,当 方法被调用。API网关支持以下集成:
mockintegration
-可用于测试API。这是默认值 如果未指定集成。lambdaintegration
-可用于调用aws lambda函数。awsintegration
-可用于调用任意aws服务api。httpintegration
-可用于调用http端点。
下面的示例演示如何将get/book/{book\u id}
方法集成到
aws lambda函数:
constgetBookHandler=newlambda.Function(...);constgetBookIntegration=newapigateway.LambdaIntegration(getBookHandler);book.addMethod('GET',getBookIntegration);
可以选择指定集成选项:
constgetBookIntegration=newapigateway.LambdaIntegration(getBookHandler,{contentHandling: apigateway.ContentHandling.CONVERT_TO_TEXT,// convert to base64credentialsPassthrough: true,// use caller identity to invoke the function});
添加方法时,可以选择指定方法选项:
book.addMethod('GET',getBookIntegration,{authorizationType: apigateway.AuthorizationType.IAM,apiKeyRequired: true});
下面的示例演示如何在使用计划中使用API密钥:
consthello=newlambda.Function(this,'hello',{runtime: lambda.Runtime.NODEJS_10_X,handler:'hello.handler',code: lambda.Code.fromAsset('lambda')});constapi=newapigateway.RestApi(this,'hello-api',{});constintegration=newapigateway.LambdaIntegration(hello);constv1=api.root.addResource('v1');constecho=v1.addResource('echo');constechoMethod=echo.addMethod('GET',integration,{apiKeyRequired: true});constkey=api.addApiKey('ApiKey');constplan=api.addUsagePlan('UsagePlan',{name:'Easy',apiKey: key});plan.addApiStage({stage: api.deploymentStage,throttle:[{method: echoMethod,throttle:{rateLimit: 10,burstLimit: 2}}]});
使用型号
当您使用不是代理集成的lambda集成时, 必须为请求、响应和集成定义模型和映射。
consthello=newlambda.Function(this,'hello',{runtime: lambda.Runtime.NODEJS_10_X,handler:'hello.handler',code: lambda.Code.fromAsset('lambda')});constapi=newapigateway.RestApi(this,'hello-api',{});constresource=api.root.addResource('v1');
您可以在集成上定义更多参数来优化api网关的行为
constintegration=newLambdaIntegration(hello,{proxy: false,requestParameters:{// You can define mapping parameters from your method to your integration// - Destination parameters (the key) are the integration parameters (used in mappings)// - Source parameters (the value) are the source request parameters or expressions// @see: https://docs.aws.amazon.com/apigateway/latest/developerguide/request-response-data-mappings.html'integration.request.querystring.who':'method.request.querystring.who'},allowTestInvoke: true,requestTemplates:{// You can define a mapping that will build a payload for your integration, based// on the integration parameters that you have specified// Check: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html'application/json':JSON.stringify({action:'sayHello',pollId:"$util.escapeJavaScript($input.params('who'))"})},// This parameter defines the behavior of the engine is no suitable response template is foundpassthroughBehavior: PassthroughBehavior.NEVER,integrationResponses:[{// Successful response from the Lambda function, no filter defined// - the selectionPattern filter only tests the error message// We will set the response status code to 200statusCode:"200",responseTemplates:{// This template takes the "message" result from the Lambda function, adn embeds it in a JSON response// Check https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html'application/json':JSON.stringify({state:'ok',greeting:'$util.escapeJavaScript($input.body)'})},responseParameters:{// We can map response parameters// - Destination parameters (the key) are the response parameters (used in mappings)// - Source parameters (the value) are the integration response parameters or expressions'method.response.header.Content-Type':"'application/json'",'method.response.header.Access-Control-Allow-Origin':"'*'",'method.response.header.Access-Control-Allow-Credentials':"'true'"}},{// For errors, we check if the error message is not empty, get the error dataselectionPattern:'(\n|.)+',// We will set the response status code to 200statusCode:"400",responseTemplates:{'application/json':JSON.stringify({state:'error',message:"$util.escapeJavaScript($input.path('$.errorMessage'))"})},responseParameters:{'method.response.header.Content-Type':"'application/json'",'method.response.header.Access-Control-Allow-Origin':"'*'",'method.response.header.Access-Control-Allow-Credentials':"'true'"}}]});
您可以为响应(和请求)定义模型
constapi=newapigateway.RestApi(this,'books-api');api.root.addMethod('ANY');constbooks=api.root.addResource('books');books.addMethod('GET');books.addMethod('POST');constbook=books.addResource('{book_id}');book.addMethod('GET');book.addMethod('DELETE');0
并参考方法定义中的所有内容。
constapi=newapigateway.RestApi(this,'books-api');api.root.addMethod('ANY');constbooks=api.root.addResource('books');books.addMethod('GET');books.addMethod('POST');constbook=books.addResource('{book_id}');book.addMethod('GET');book.addMethod('DELETE');1
默认集成和方法选项
defaultintegration
和defaultmethodoptions
属性可用于
在任何资源级别配置默认集成。这些选项将是
使用未定义的在该资源下定义方法(递归)时使用
集成或选项。
如果未定义,则默认集成为mockintegration
。见参考文献
默认方法选项的文档。
下面的示例将booksbackend
集成定义为默认值
整合。这意味着所有没有显式定义
集成将路由到此AWS Lambda功能。
constapi=newapigateway.RestApi(this,'books-api');api.root.addMethod('ANY');constbooks=api.root.addResource('books');books.addMethod('GET');books.addMethod('POST');constbook=books.addResource('{book_id}');book.addMethod('GET');book.addMethod('DELETE');2
代理路由
可以使用addproxy
方法安装贪婪的{proxy+}
资源
在一条小路上。默认情况下,这还会安装一个"any"
方法:
constapi=newapigateway.RestApi(this,'books-api');api.root.addMethod('ANY');constbooks=api.root.addResource('books');books.addMethod('GET');books.addMethod('POST');constbook=books.addResource('{book_id}');book.addMethod('GET');book.addMethod('DELETE');3
部署
默认情况下,restapi
构造将自动执行创建一个api网关
部署和一个"prod"阶段表示您的api配置
在CDK应用程序中定义。这意味着当您部署应用程序时,您的api将
您可以通过Stage URL从Internet进行开放式访问。
api的url可以从属性 要禁用此行为,可以在创建
应用程序编程接口。这意味着不会部署api,也不会部署stage
为之而生。您需要手动定义 使用 下面的示例将配置API网关以将日志和数据跟踪发送到
所有api调用的aws cloudwatch: 默认情况下,将创建一个IAM角色并与
允许它向aws cloudwatch写入日志和度量,除非 api网关部署是api的不可变快照。这意味着我们
希望在每次API模型
在我们的CDK应用程序更改中定义。 为了实现这一点,aws的cloudformation逻辑id
默认情况下,旧部署将被删除。您可以设置 要将api与自定义域关联,请在以下情况下使用 这将为您定义一个 要将域通信路由到api网关api,请使用amazon route 53创建
别名记录。别名记录是DNS的路由53扩展。它类似于
cname记录,但可以为根域创建别名记录,如
对于 您还可以直接定义 一旦有了域,就可以将域的基本路径映射到api。
下面的示例将映射urlhttps://example.com/go-to-api1
到 注意:目前,映射将始终分配给api
如果未指定 这也可以通过 如果您希望使用amazon route53别名设置此域,请使用 本模块是aws云开发工具包项目的一部分。restapi.url
获得,并且是
也从堆栈中导出为输出,因此当您的应用程序
cdk deploy
constapi=newapigateway.RestApi(this,'books-api');api.root.addMethod('ANY');constbooks=api.root.addResource('books');books.addMethod('GET');books.addMethod('POST');constbook=books.addResource('{book_id}');book.addMethod('GET');book.addMethod('DELETE');
4
apigateway.deployment
和
apigateway.stage
资源。deployoptions
属性自定义
API.cloudwatchrole
设置为false
constapi=newapigateway.RestApi(this,'books-api');api.root.addMethod('ANY');constbooks=api.root.addResource('books');books.addMethod('GET');books.addMethod('POST');constbook=books.addResource('{book_id}');book.addMethod('GET');book.addMethod('DELETE');
5
更深层次:部署失效
aws::apigateway::部署
资源是通过散列
API配置(资源、方法)。这意味着当配置
更改(即添加资源或方法、更改配置)、新的
逻辑ID将分配给部署资源。这会导致
创建新部署资源的云信息。重新部署:true
允许用户手动将阶段还原为旧部署。自定义域
domainname
配置
你定义你的api:constapi=newapigateway.RestApi(this,'books-api');api.root.addMethod('ANY');constbooks=api.root.addResource('books');books.addMethod('GET');books.addMethod('POST');constbook=books.addResource('{book_id}');book.addMethod('GET');book.addMethod('DELETE');
6
domainname
资源,以及一个basepathmapping
从域的根目录到api的部署阶段。这是很常见的
设置,example.com
,对于子域,例如www.example.com
。(您可以创建
cname只记录子域。)constapi=newapigateway.RestApi(this,'books-api');api.root.addMethod('ANY');constbooks=api.root.addResource('books');books.addMethod('GET');books.addMethod('POST');constbook=books.addResource('{book_id}');book.addMethod('GET');book.addMethod('DELETE');
7
域名
资源,以便自定义默认行为:
constapi=newapigateway.RestApi(this,'books-api');api.root.addMethod('ANY');constbooks=api.root.addResource('books');books.addMethod('GET');books.addMethod('POST');constbook=books.addResource('{book_id}');book.addMethod('GET');book.addMethod('DELETE');
8
API1
API和https://example.com/boom到API2
API。constapi=newapigateway.RestApi(this,'books-api');api.root.addMethod('ANY');constbooks=api.root.addResource('books');books.addMethod('GET');books.addMethod('POST');constbook=books.addResource('{book_id}');book.addMethod('GET');book.addMethod('DELETE');
9
deploymentstage
,它将自动分配给最新的api
部署。如果需要对
将基本路径映射到阶段。basepath
,则将映射此域下的所有URL
到api,您将无法将另一个api映射到同一域:constbackend=newlambda.Function(...);newapigateway.LambdaRestApi(this,'myapi',{handler: backend,});
0
m在定义
域,如上所示。
route53_targets.apigatewaydomain
:constbackend=newlambda.Function(...);newapigateway.LambdaRestApi(this,'myapi',{handler: backend,});
1
推荐PyPI第三方库