AWS:: APIGatewayv2 构造库
AWS CDK v1在2023-06-01上达到了支持结束. 此软件包不再更新,用户应该迁移到 AWS CDK v2.
关于如何移徙的更多信息,请参见: 移动到 AWS CDK v2 指南。 。 。 .
| 特征 | 稳定 |
|---|---|
| CFN 资源 | |
| HTTP API 的更高层次构造 | |
| Websocket APIs 的更高层次构造 |
CFN 资源: 所有课程与
Cfn此模块中的前缀( n)CFN 资源总是 稳定安全使用.
实验: 本模块中标为实验性的更高层次构造是: 正在积极发展之中。 它们受到非后向相容性修改或任何 未来版本. 这些限制不受《公约》的约束 语义版本 模型和 断开更改将在发布注释中宣布。 这意味着当你可以使用它们, 您可能需要在升级到此软件包的更新版本时更新源代码.
目录
导言
亚马逊 API Gateway 是一个 AWS 服务,用于创建、发布、维护、监测和保障 REST、HTTP和 WebSocket 任何尺度的API. API开发者可以创建访问AWS或其他网络服务的API,以及存储在AWS Cloud中的数据. 作为API Gateway API开发者,您可以创建API,用于自己的客户端应用程序. 读取 Amazon API 网关开发者指南。 。 。 .
本模块支持以下特性: API 网关 v2
让用户设置 Websocket 和 HTTP API .
REST API 可以使用 @aws-cdk/aws-apigateway 模块.
HTTP API 密码
HTTP APIs 允许创建与 AWS Lambda 函数相融合的 RESTful APIs,称为 Lambda 代理集成, 或到任何rotable HTTP端点,称为HTTP代理集成.
定义 HTTP API
HTTP API有两个基本概念——路线和整合.
路由将收到的API请求引导到后端资源. 路线由两部分组成:HTTP方法和资源
路径,例如, GET /books。学习更多 与
路线。使用 ANY 方法
以匹配未明确定义的路由的任何方法.
集成定义了当客户端到达特定路由时HTTP API如何响应. HTTP APIs 支持 Lambda 代理 集成,HTTP代理集成和,AWS服务集成,也称私人集成. 学习更多 配置融合。 。 。 .
学校提供综合课程 aws-apigatewayv2-integrations 模块和更多信息可在该模块中查阅.
作为早期的例子,以下代码片段配置一个路由 GET /books 全部拥有 HTTP 代理集成
配置所有其他 HTTP 方法调用 /books 给一个lambda代理.
import { HttpUrlIntegration, HttpLambdaIntegration } from '@aws-cdk/aws-apigatewayv2-integrations';
const getBooksIntegration = new HttpUrlIntegration('GetBooksIntegration', 'https://get-books-proxy.myproxy.internal');
declare const booksDefaultFn: lambda.Function;
const booksDefaultIntegration = new HttpLambdaIntegration('BooksIntegration', booksDefaultFn);
const httpApi = new apigwv2.HttpApi(this, 'HttpApi');
httpApi.addRoutes({
path: '/books',
methods: [ apigwv2.HttpMethod.GET ],
integration: getBooksIntegration,
});
httpApi.addRoutes({
path: '/books',
methods: [ apigwv2.HttpMethod.ANY ],
integration: booksDefaultIntegration,
});
端点的 URL 可通过 apiEndpoint 属性。 默认情况下, 客户端启用了此 URL 。 使用 disableExecuteApiEndpoint 来禁用它.
const httpApi = new apigwv2.HttpApi(this, 'HttpApi', {
disableExecuteApiEndpoint: true,
});
这个 defaultIntegration 选项,同时定义 HTTP API 允许您创建默认的全覆盖集成
匹配客户端到达未明确定义的路径.
import { HttpUrlIntegration } from '@aws-cdk/aws-apigatewayv2-integrations';
new apigwv2.HttpApi(this, 'HttpProxyApi', {
defaultIntegration: new HttpUrlIntegration('DefaultIntegration', 'https://example.com'),
});
交叉来源资源分享
跨部门资源分享 是浏览器安全 特性限制从浏览器中运行的脚本启动的 HTTP 请求。 启用 CORS 将允许 请求从一个与您的 API 域不同的域内托管的网络应用程序向您的 API .
当配置 HTTP API 时, API Gateway 自动发送对飞行前的响应 OPTIONS 请求,甚至
如果没有 OPTIONS 路径已配置 。 注意, 当使用此选项时, API Gateway 会忽略 CORS 头
从您的后端集成返回 。 学习更多关于 配置 HTTP 的 CORS
API 密码。 。 。 .
这个 corsPreflight 选项允许您为 API 指定 CORS 配置.
new apigwv2.HttpApi(this, 'HttpProxyApi', {
corsPreflight: {
allowHeaders: ['Authorization'],
allowMethods: [
apigwv2.CorsHttpMethod.GET,
apigwv2.CorsHttpMethod.HEAD,
apigwv2.CorsHttpMethod.OPTIONS,
apigwv2.CorsHttpMethod.POST,
],
allowOrigins: ['*'],
maxAge: Duration.days(10),
},
});
发布 HTTP API
A Stage 是您 API 生命周期状态的逻辑引用( 例如, ), dev, (中文(简体) ), prod, (中文(简体) ), beta,或 v2API (英语)
阶段按其艺名确定。 每个阶段都有一个命名的参考文献,说明为下列目的部署的API:
要调用客户端应用程序 .
使用 HttpStage 为 HTTP API 创建 Stage 资源。 以下代码设置一个 Stage, 其 URL 可用于
https://{api_id}.execute-api.{region}.amazonaws.com/beta。 。 。 .
declare const api: apigwv2.HttpApi;
new apigwv2.HttpStage(this, 'Stage', {
httpApi: api,
stageName: 'beta',
});
如果你省略 stageName 将创建 $default 阶段。 A 类 $default 舞台是一个从
aPI 的 URL - https://{api_id}.execute-api.{region}.amazonaws.com/。 。 。 .
请注意, HttpApi 将永远创建 $default 阶段,除非 createDefaultStage 属性未设置.
自定义域
自定义域名更简单,更能直观地向您的API用户提供URL. 自定义域名与API阶段相关.
下面的代码片段创建自定义域,并为您的 API 配置默认域映射
自定义域为 $default 阶段 API.
import * as acm from '@aws-cdk/aws-certificatemanager';
import { HttpLambdaIntegration } from '@aws-cdk/aws-apigatewayv2-integrations';
const certArn = 'arn:aws:acm:us-east-1:111111111111:certificate';
const domainName = 'example.com';
const dn = new apigwv2.DomainName(this, 'DN', {
domainName,
certificate: acm.Certificate.fromCertificateArn(this, 'cert', certArn),
});
declare const handler: lambda.Function;
const api = new apigwv2.HttpApi(this, 'HttpProxyProdApi', {
defaultIntegration: new HttpLambdaIntegration('DefaultIntegration', handler),
// https://${dn.domainName}/foo goes to prodApi $default stage
defaultDomainMapping: {
domainName: dn,
mappingKey: 'foo',
},
});
要将一个域端点从一个类型迁移到另一个类型,您可以通过 addEndpoint()
然后将 DNS 记录配置到向新终点的路由流量。 之后,可以去除之前的终点配置.
学习更多 正在移动自定义域名
将一个具体 Stage 到自定义域映射 -
declare const api: apigwv2.HttpApi;
declare const dn: apigwv2.DomainName;
api.addStage('beta', {
stageName: 'beta',
autoDeploy: true,
// https://${dn.domainName}/bar goes to the beta stage
domainMapping: {
domainName: dn,
mappingKey: 'bar',
},
});
同一个域名可以和不同阶段联系起来 HttpApi 这样..
import { HttpLambdaIntegration } from '@aws-cdk/aws-apigatewayv2-integrations';
declare const handler: lambda.Function;
declare const dn: apigwv2.DomainName;
const apiDemo = new apigwv2.HttpApi(this, 'DemoApi', {
defaultIntegration: new HttpLambdaIntegration('DefaultIntegration', handler),
// https://${dn.domainName}/demo goes to apiDemo $default stage
defaultDomainMapping: {
domainName: dn,
mappingKey: 'demo',
},
});
这个 mappingKey 确定带有自定义域的 URL 的基础路径。 仅允许每个自定义域
以未定义的 API 映射 mappingKey如果指定了一个以上的API映射, mappingKey 需要他们全部。 在上述样本中,自定义域关联
包含3个 API 映射不同 API 和 Stages 的资源.
| API 密码 | 阶段 | 網址 |
|---|---|---|
| api 密码 | 默认 | https://${domainName}/foo |
| api 密码 | β 语录 | https://${domainName}/bar |
| 高级 | 默认 | https://${domainName}/demo |
您可以使用 : domainUrl 财产本身
declare const apiDemo: apigwv2.HttpApi;
const demoDomainUrl = apiDemo.defaultStage?.domainUrl; // returns "https://example.com/demo"
互通 TLS (mTLS)
可以通过使用客户端证书来限制访问基于您的 API 的互通 TLS 配置,而不是使用授权头(或作为扩展) .
import * as s3 from '@aws-cdk/aws-s3';
import * as acm from '@aws-cdk/aws-certificatemanager';
const certArn = 'arn:aws:acm:us-east-1:111111111111:certificate';
const domainName = 'example.com';
declare const bucket: s3.Bucket;
new apigwv2.DomainName(this, 'DomainName', {
domainName,
certificate: acm.Certificate.fromCertificateArn(this, 'cert', certArn),
mtls: {
bucket,
key: 'someca.pem',
version: 'version',
},
});
配置信任仓库的指令可以找到 这里
管理 HTTP API 的访问
API 网关支持多种机制 控制和管理您的 HTTP 访问 API 密码 通过授权人.
这些授权人可在 APIGateway V2-认证器 构建库.
计量
API Gateway v2服务将围绕HTTP API的性能的度量衡发送到亚马逊Cloud Watch.
这些度量衡可以使用以下表格上可用的度量API参考: HttpApi 构造.
与 metric 前缀可以用来为这个API获取特定度量衡的引用. 譬如说,
以下方法指此API的客户端错误度量.
const api = new apigwv2.HttpApi(this, 'my-api');
const clientErrorMetric = api.metricClientError();
请注意, 这将返回 Api 中定义的所有阶段的度量 。 也可以使用下列方法参考特定阶段的衡量尺度:
页:1 metric 方法从 Stage 构造.
const api = new apigwv2.HttpApi(this, 'my-api');
const stage = new apigwv2.HttpStage(this, 'Stage', {
httpApi: api,
});
const clientErrorMetric = stage.metricClientError();
VPC 链接
私人集成让HTTP API与放置在VPC后方的AWS资源相接. 这些通常是应用程序
负载平衡器,网络负载平衡器或云图服务. 这个 VpcLink 构造可以实现这种整合.
以下代码创建 VpcLink 对一个私人的VPC.
import * as ec2 from '@aws-cdk/aws-ec2';
const vpc = new ec2.Vpc(this, 'VPC');
const vpcLink = new apigwv2.VpcLink(this, 'VpcLink', { vpc });
任何现有的 VpcLink 资源可以通过 VpcLink.fromVpcLinkAttributes()。 。 。 .
import * as ec2 from '@aws-cdk/aws-ec2';
declare const vpc: ec2.Vpc;
const awesomeLink = apigwv2.VpcLink.fromVpcLinkAttributes(this, 'awesome-vpc-link', {
vpcLinkId: 'us-east-1_oiuR12Abd',
vpc,
});
私营一体化
私有集成可以将 HTTP API 路由与私有资源整合到 VPC 中,例如应用程序负载平衡器或 亚马逊ECS容器应用. 利用私人集成,VPC中的资源可以被曝出,供 在VPC以外的客户.
这些融合可参见: aws-apigatewayv2-集成系统 构建库.
WebSocket API 服务器
API Gateway中的WebSocket API是集成后端HTTP端点为一体的WebSocket路由, Lambda功能,或其他AWS服务. 您可以使用 API 网关功能来帮助您处理 API 的各个方面 生命周期,从创造到监测你的生产 API. 更多信息
WebSocket API有两个基本概念——路线和整合.
WebSocket API将JSON消息引导到基于所配置的路由的后端集成. (非JSON消息是针对
切换到配置 $default 路径。 )
整合定义了当客户端到达特定路由时WebSocket API的行为. 学习更多 配置融合。 。 。 .
综合内容可在 aws-apigatewayv2-integrations 模块和更多信息可在该模块中查阅.
添加由 API Gateway 支持的默认 WebSocket 路由($connect, (中文(简体) ), $disconnect 财务报告和审定财务报表 $default,将其配置为 api 道具的一部分 :
import { WebSocketLambdaIntegration } from '@aws-cdk/aws-apigatewayv2-integrations';
declare const connectHandler: lambda.Function;
declare const disconnectHandler: lambda.Function;
declare const defaultHandler: lambda.Function;
const webSocketApi = new apigwv2.WebSocketApi(this, 'mywsapi', {
connectRouteOptions: { integration: new WebSocketLambdaIntegration('ConnectIntegration', connectHandler) },
disconnectRouteOptions: { integration: new WebSocketLambdaIntegration('DisconnectIntegration',disconnectHandler) },
defaultRouteOptions: { integration: new WebSocketLambdaIntegration('DefaultIntegration', defaultHandler) },
});
new apigwv2.WebSocketStage(this, 'mystage', {
webSocketApi,
stageName: 'dev',
autoDeploy: true,
});
要取回 Websocket URL 和 回调 URL :
declare const webSocketStage: apigwv2.WebSocketStage;
const webSocketURL = webSocketStage.url;
// wss://${this.api.apiId}.execute-api.${s.region}.${s.urlSuffix}/${urlPath}
const callbackURL = webSocketStage.callbackUrl;
// https://${this.api.apiId}.execute-api.${s.region}.${s.urlSuffix}/${urlPath}
要添加任何其他路线:
import { WebSocketLambdaIntegration } from '@aws-cdk/aws-apigatewayv2-integrations';
declare const messageHandler: lambda.Function;
const webSocketApi = new apigwv2.WebSocketApi(this, 'mywsapi');
webSocketApi.addRoute('sendmessage', {
integration: new WebSocketLambdaIntegration('SendMessageIntegration', messageHandler),
});
要导入已有的 WebSocketApi :
const webSocketApi = apigwv2.WebSocketApi.fromWebSocketApiAttributes(this, 'mywsapi', { webSocketId: 'api-1234' });
管理连接权限
授权使用 WebSocket API 的 API 网关管理 API grantManageConnections API (英语).
您可以使用管理API向一个连接的客户端发送回调消息,获取连接信息,或者断开客户端. 学习更多 在您的后端服务中使用@ connections 命令。 。 。 .
declare const fn: lambda.Function;
const webSocketApi = new apigwv2.WebSocketApi(this, 'mywsapi');
const stage = new apigwv2.WebSocketStage(this, 'mystage', {
webSocketApi,
stageName: 'dev',
});
// per stage permission
stage.grantManagementApiAccess(fn);
// for all the stages permission
webSocketApi.grantManageConnections(fn);
管理WebSocket API的访问
API 网关支持多种机制 控制和管理对 WebSocket API 的访问 通过授权人.
这些授权人可在 APIGateway V2-认证器 构建库.
API 密钥
Websocket APIs也支持使用API密钥. 一个API密钥是用于授予一个API访问权限的密钥. 用于控制并跟踪对API的访问 使用计划。这些组合使您可以配置关于 API 访问的控件,如配额和节奏,以及每API 使用量的关键度量.
访问 Websocket API 时需要 API 密钥 :
const webSocketApi = new apigwv2.WebSocketApi(this, 'mywsapi',{
apiKeySelectionExpression: apigwv2.WebSocketApiKeySelectionExpression.HEADER_X_API_KEY,
});