@alma-cdk/openapix

中文文档
2.0.1发布于 2026/08/10Apache-2.0TypeScriptCommonJS构建来源已验证近 30 天下载 1.5万

组合 AWS CDK 和 OpenAPI YAML 定义

中文使用文档
文档目录14 节
  1. 稳定项目
  2. 开始
  3. HTTP 整合
  4. Lambda一体化组织
  5. AWS 服务整合
  6. 模拟整合
  7. 验证器
  8. 授权者
  9. 认知作者
  10. Lambda 授权者
  11. 弹出/ 拒绝
  12. (简体中文)
  13. 默认 CORS
  14. API 网关端点Type


Alma CDK OpenApiX

npm i -D @alma-cdk/openapix

通过 AWS 生成 Api 网关 REST APIS 打开API (形式上称为 “ Swagger ”) Schema 通过消耗“ clean” OpenAPI 计划并注入定义 x-amazon-apigateway- 扩展 具有类型安全。 。 。 .



diagram


稳定项目

experimental

此构造仍为 v0 必要时可以引入大版本并进行断开修改(没有大版本起伏),尽管我们的目标是尽可能地保持API的稳定(即使在内部) v0 发展)。 我们的目标是出版 v1.0.0 不久之后, 将会通过大版本的突起来进行更改.

还有一些不完整或有缺陷的特征,例如CORS和 CognitoUserPoolsAuthorizer。 。 。 .


开始

  1. 安装 npm i -D @alma-cdk/openapix

  2. 定义您的 API OpenApi Schema 定义 .yaml 文件
    无 任意 x-amazon-apigateway- 扩展

  3. 使用 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 ],
    },
  },
});

版本与发布记录

@alma-cdk/openapix 共发布 54 个版本,首次发布于 2022/05/21;过去 12 个月发布了 8 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.0.1latest2026/08/102 个月前
2.0.02026/08/102 个月前
1.0.42026/08/102 个月前
1.0.32026/04/076 个月前
1.0.22026/04/027 个月前
1.0.12026/04/027 个月前

其他发布通道:beta → 1.0.0-beta.4。

关于 @alma-cdk/openapix 的常见问题

@alma-cdk/openapix 是什么?

组合 AWS CDK 和 OpenAPI YAML 定义

如何安装 @alma-cdk/openapix?

在项目目录运行 npm install @alma-cdk/openapix,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:aws-cdk-lib(^2.260.0)、constructs(^10.7.2)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@alma-cdk/openapix 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@alma-cdk/openapix 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@alma-cdk/openapix 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >= 22 <= 26。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@alma-cdk/openapix 可以商用吗?

@alma-cdk/openapix 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@alma-cdk/openapix 的下载量有多少?

根据 npm 官方下载统计,@alma-cdk/openapix 在 2026/10/06 – 2026/11/04 这 30 天内被下载 14,803 次,日均约 493 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@alma-cdk/openapix 还在维护吗?

最新版本 2.0.1 发布于 2026/08/10(2 个月前);至今共发布 54 个版本,其中过去 12 个月发布了 8 个;首次发布于 2022/05/21。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。