npm i -D @alma-cdk/openapix
通过 AWS 生成 Api 网关 REST APIS 打开API (形式上称为 “ Swagger ”) Schema 通过消耗“ clean” OpenAPI 计划并注入定义 x-amazon-apigateway- 扩展 具有类型安全。 。 。 .
稳定项目
此构造仍为 v0 必要时可以引入大版本并进行断开修改(没有大版本起伏),尽管我们的目标是尽可能地保持API的稳定(即使在内部) v0 发展)。 我们的目标是出版 v1.0.0 不久之后, 将会通过大版本的突起来进行更改.
还有一些不完整或有缺陷的特征,例如CORS和 CognitoUserPoolsAuthorizer。 。 。 .
开始
-
安装
npm i -D @alma-cdk/openapix -
定义您的 API OpenApi Schema 定义
.yaml文件
无 任意x-amazon-apigateway-扩展 -
使用
openapix在 CDK 中构建以消耗.yaml文件然后使用 CDK 指定 API 网关集成
HTTP 整合
鉴于以下各点: http-proxy.yaml OpenApi 计划定义, (中文(简体) ), 无 任何 AWS API 网关 OpenApi 扩展 :
openapi: 3.0.3
info:
title: HTTP Proxy
description: Proxies requests to example.com
version: "0.0.1"
paths:
"/":
get:
summary: proxy
description: Proxies example.com
您可以定义 API 网关 HTTP 集成( 在您的堆栈内) :
new openapix.Api(this, 'HttpProxy', {
source: path.join(__dirname, '../schema/http-proxy.yaml'),
paths: {
'/': {
get: new openapix.HttpIntegration(this, 'http://example.com', {
httpMethod: 'get',
}),
},
},
});
见 /examples/http-proxy 用于完整 OpenApi 定义(带有响应模型)和CDK应用程序中的实例.
Lambda一体化组织
鉴于以下各点: hello-api.yaml OpenApi 计划定义, (中文(简体) ), 无 任何 AWS API 网关 OpenApi 扩展 :
openapi: 3.0.3
info:
title: Hello API
description: Defines an example “Hello World” API
version: "0.0.1"
paths:
"/":
get:
operationId: sayHello
summary: Say Hello
description: Prints out a greeting
parameters:
- name: name
in: query
required: false
schema:
type: string
default: "World"
responses:
"200":
description: Successful response
content:
"application/json":
schema:
$ref: "#/components/schemas/HelloResponse"
components:
schemas:
HelloResponse:
description: Response body
type: object
properties:
message:
type: string
description: Greeting
example: Hello World!
然后可以定义 API 网关 AWS Lambda 集成(在您的堆栈内):
const greetFn = new NodejsFunction(this, 'greet');
new openapix.Api(this, 'HelloApi', {
source: path.join(__dirname, '../schema/hello-api.yaml'),
paths: {
'/': {
get: new openapix.LambdaIntegration(this, greetFn),
},
},
})
见 /examples/hello-api 用于完整 OpenApi 定义(带有响应模型)和CDK应用程序中的实例.
AWS 服务整合
鉴于 books-api.yaml OpenApi 计划定义, (中文(简体) ), 无 任何 AWS API 网关 OpenApi 扩展名, 您可以定义 API Gateway AWS 服务集成, 如 DynamoDB( 在您的堆栈内) :
new openapix.Api(this, 'BooksApi', {
source: path.join(__dirname, '../schema/books-api.yaml'),
paths: {
'/': {
get: new openapix.AwsIntegration(this, {
service: 'dynamodb',
action: 'Scan',
options: {
credentialsRole: role, // role must have access to DynamoDB table
requestTemplates: {
'application/json': JSON.stringify({
TableName: table.tableName,
}),
},
integrationResponses: [
{
statusCode: '200',
responseTemplates: {
// See /examples/http-proxy/lib/list-books.vtl
'application/json': readFileSync(__dirname+'/list-books.vtl', 'utf-8'),
},
}
],
},
}),
},
'/{isbn}': {
get: new openapix.AwsIntegration(this, {
service: 'dynamodb',
action: 'GetItem',
options: {
credentialsRole: role, // role must have access to DynamoDB table
requestTemplates: {
'application/json': JSON.stringify({
TableName: table.tableName,
Key: {
item: {
"S": "$input.params('isbn')"
}
}
}),
},
integrationResponses: [
{
statusCode: '200',
responseTemplates: {
// See /examples/http-proxy/lib/get-book.vtl
'application/json': readFileSync(__dirname+'/get-book.vtl', 'utf-8'),
},
}
],
},
}),
},
},
});
见 /examples/books-api 用于完整 OpenApi 定义(带有响应模型)和CDK应用程序中的实例.
模拟整合
鉴于以下各点: mock-api.yaml OpenApi 计划定义, (中文(简体) ), 无 任何 AWS API 网关 OpenApi 扩展 :
openapi: 3.0.3
info:
title: Hello API
description: Defines an example “Hello World” API
version: "0.0.1"
paths:
"/":
get:
operationId: sayHello
summary: Say Hello
description: Prints out a greeting
parameters:
- name: name
in: query
required: false
schema:
type: string
default: "World"
responses:
"200":
description: Successful response
content:
"application/json":
schema:
$ref: "#/components/schemas/HelloResponse"
components:
schemas:
HelloResponse:
description: Response body
type: object
properties:
message:
type: string
description: Greeting
example: Hello World!
然后可以定义 API 网关模拟集成(在您的堆栈内):
new openapix.Api(this, 'MockApi', {
source: path.join(__dirname, '../schema/mock-api.yaml'),
paths: {
'/': {
get: new openapix.MockIntegration(this, {
requestTemplates: {
"application/json": JSON.stringify({ statusCode: 200 }),
},
passthroughBehavior: apigateway.PassthroughBehavior.NEVER,
requestParameters: {
'integration.request.querystring.name': 'method.request.querystring.name',
},
integrationResponses: [
{
statusCode: '200',
responseTemplates: {
// see /examples/mock-api/lib/greet.vtl
'application/json': readFileSync(__dirname+'/greet.vtl', 'utf-8'),
},
responseParameters: {},
},
],
}),
},
},
});
见 /examples/mock-api 用于完整 OpenApi 定义(带有响应模型)和CDK应用程序中的实例.
验证器
API 网关 REST API 可以执行 请求参数和请求正文验证。您既可以提供默认验证器,也可以提供集成特定验证器(它将覆盖给定集的默认值).
见 /examples/todo-api 例如,在 CDK 应用程序中.
鉴于 todo-api.yaml OpenApi 计划定义 您可以定义用于您在 CDK 中的整合的 API 网关验证器 :
new openapix.Api(this, 'MyApi', {
source: path.join(__dirname, '../schema/todo-api.yaml'),
validators: {
'all': {
validateRequestBody: true,
validateRequestParameters: true,
default: true, // set this as the "API level" default validator (there can be only one)
},
'params-only' : {
validateRequestBody: false,
validateRequestParameters: true,
},
},
paths: {
'/todos': {
// this one uses the default 'all' validator
post: new openapix.HttpIntegration(this, baseUrl, { httpMethod: 'post' }),
},
'/todos/{todoId}': {
// this one has validator override and uses 'params-only' validator
get: new openapix.HttpIntegration(this, `${baseUrl}/{todoId}`, {
validator: 'params-only',
options: {
requestParameters: {
'integration.request.path.todoId': 'method.request.path.todoId',
},
},
}),
},
},
})
授权者
工作进展
有很多办法 控制并管理对 API 网关 REST API 的访问 例如 资源政策, (中文(简体) ), IAM 权限 财务报告和审定财务报表 aPI 密钥的使用计划 但本节的重点是 认知用户池 财务报告和审定财务报表 蓝巴达授权人。 。 。 .
认知作者
在这个例子中,我们正在定义一个基于Congito用户池的授权人.
鉴于以下各点: schema.yaml OpenApi 定义 :
openapi: 3.0.3
paths:
/:
get:
security:
- MyAuthorizer: ["test/read"] # add scope
components:
securitySchemes:
MyCognitoAuthorizer:
type: apiKey
name: Authorization
in: header
您可以用 :
const userPool: cognito.IUserPool;
new openapix.Api(this, 'MyApi', {
source: './schema.yaml',
authorizers: [
new openapix.CognitoUserPoolsAuthorizer(this, 'MyCognitoAuthorizer', {
cognitoUserPools: [userPool],
resultsCacheTtl: Duration.minutes(5),
})
],
})
Lambda 授权者
在这个例子中,我们正在定义一个定制的Lambda授权人. 授权者函数代码与示例无关,但示例中的想法是,一个API调用者在查询参数中发送一些"秘密代码"(Secret Code)?code=example123456然后授权人以某种方式进行评估.
鉴于以下各点: schema.yaml OpenApi 定义 :
openapi: 3.0.3
paths:
/:
get:
security:
- MyAuthorizer: [] # note the empty array
components:
securitySchemes:
MyCustomAuthorizer:
type: apiKey
name: code
in: query
您可以用 :
const authFn: lambda.IFunction;
new openapix.Api(this, 'MyApi', {
source: './schema.yaml',
authorizers: [
new openapix.LambdaAuthorizer(this, 'MyCustomAuthorizer', {
fn: authFn,
identitySource: apigateway.IdentitySource.queryString('code'),
type: 'request',
authType: 'custom',
resultsCacheTtl: Duration.minutes(5),
}),
],
})
弹出/ 拒绝
您可以通过插入或拒绝源代码OpenAPI的值来修改生成的 OpenAPI 定义(用于定义 API Gateway REST API) :
new openapix.Api(this, 'MyApi', {
source: './schema.yaml',
// Add any OpenAPI v3 data.
// Can be useful for passing values from CDK code.
// See https://swagger.io/specification/
injections: {
"info.title": "FancyPantsAPI"
},
// Reject fields by absolute object path from generated definition
rejections: ['info.description'],
// Reject all matching fields from generated definition
rejectionsDeep: ['example', 'examples'],
});
(简体中文)
工作进展
使用 openapix.CorsIntegration 创建一个 Moc 集成, 以正确的响应标题响应 :
new openapix.Api(this, 'MyApi', {
source: './schema.yaml',
paths: {
'/foo': {
options: new openapix.CorsIntegration(this, {
// using helper method to define explicit values:
headers: CorsHeaders.from(this, 'Content-Type', 'X-Amz-Date', 'Authorization'),
origins: CorsOrigins.from(this, 'https://www.example.com'),
methods: CorsMethods.from(this, 'options','post','get'),
}),
},
'/bar': {
options: new openapix.CorsIntegration(this, {
// using regular string values:
headers: 'Content-Type,X-Amz-Date,Authorization',
origins: '*',
methods: 'options,get',
}),
},
'/baz': {
options: new openapix.CorsIntegration(this, {
// using helper constant for wildcard values:
headers: CorsHeaders.ANY,
origins: CorsOrigins.ANY,
methods: CorsMethods.ANY,
}),
},
},
});
指定多个时 origins 模拟整合用途 VTL 魔法 答复 Access-Control-Allow-Origin 头曰.
默认 CORS
如果您想要定义每个路径的相同的 CORS 选项, 您可以通过提供默认选项来定义 cors 值 :
new openapix.Api(this, 'MyApi', {
source: './schema.yaml',
defaultCors: new openapix.CorsIntegration(this, {
headers: CorsHeaders.ANY,
origins: CorsOrigins.ANY,
methods: CorsMethods.ANY,
}),
paths: {/*...*/},
});
这将应用给定的 cors 配置为 每个 路径为 options 方法。 您仍然可以通过添加一个 options 用于特定路径的方法.
API 网关端点Type
AWS CDK API 网关构造默认为 边际优化 API 端点 通过使用 EndpointType.EDGE 作为默认.
这个构造 @alma-cdk/openapix 而不是默认使用 区域API终点 设置 EndpointType.REGIONAL 作为默认值。 这是因为我们认为,在大多数情况下,你最好在API前配置出自己的"云纹"分布. 如果你这样做,你也可能有兴趣 @alma-cdk/origin-verify 构造。 。 。 .
您可以在 @alma-cdk/openapix ,通过 restApiProps数字 :
new openapix.Api(this, 'MyApi', {
source: './schema.yaml',
paths: {/*...*/},
restApiProps: {
endpointConfiguration: {
types: [ apigateway.EndpointType.EDGE ],
},
},
});