# @alma-cdk/openapix 中文文档

规范地址：https://npmcn.com/package/%40alma-cdk/openapix/

版本：2\.0\.1
npm 元数据更新时间：2026-08-10T14:06:34.104Z
中文译文更新时间：2026-11-05T21:55:54.020Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40alma-cdk/openapix
原文对照：https://npmcn.com/package/%40alma-cdk/openapix/?lang=original
项目主页：https://github.com/alma-cdk/openapix#readme
源码仓库：https://github.com/alma-cdk/openapix

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：6.8 MB，4423 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- Node.js 要求：\>= 22 \<= 26
- 运行依赖：4 个
- peer 依赖：aws-cdk-lib ^2\.260\.0，constructs ^10\.7\.2
- 首次发布：2022-05-20T22:42:02.843Z
- 最新版本发布：2026-08-10T14:06:33.694Z
- 近 30 天下载量：14803（2026-10-06 至 2026-11-04，npm 官方下载统计）
- 已发布版本数：54（近 12 个月 8 个）

## 中文简介

组合 AWS CDK 和 OpenAPI YAML 定义

## 安装

```sh
npm install @alma-cdk/openapix
```

也可以使用：`pnpm add @alma-cdk/openapix`、`yarn add @alma-cdk/openapix`、`bun add @alma-cdk/openapix`

## README

  
  

# ![Alma CDK OpenApiX](https://npmcn.com/package/%40alma-cdk/openapix/assets/alma-cdk-openapix.svg)  
  

```sh
npm i -D @alma-cdk/openapix
```

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

  

  

![diagram](https://npmcn.com/package/%40alma-cdk/openapix/assets/diagram.svg)

  

## 稳定项目

![experimental](https://img.shields.io/badge/stability-experimental-yellow "Stability: 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 计划定义](https://github.com/alma-cdk/openapix/blob/main/examples/http-proxy/schema/http-proxy.yaml), (中文(简体) ), _无_ 任何 AWS API 网关 OpenApi 扩展 :

```yaml
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 集成( 在您的堆栈内) :

```ts
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`](https://github.com/alma-cdk/openapix/tree/main/examples/http-proxy) 用于完整 OpenApi 定义(带有响应模型)和CDK应用程序中的实例.

  

## Lambda一体化组织

鉴于以下各点: [`hello-api.yaml` OpenApi 计划定义](https://github.com/alma-cdk/openapix/blob/main/examples/hello-api/schema/hello-api.yaml), (中文(简体) ), _无_ 任何 AWS API 网关 OpenApi 扩展 :

```yaml
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 集成(在您的堆栈内):

```ts
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`](https://github.com/alma-cdk/openapix/tree/main/examples/hello-api) 用于完整 OpenApi 定义(带有响应模型)和CDK应用程序中的实例.

  

## AWS 服务整合

鉴于 [`books-api.yaml` OpenApi 计划定义](https://github.com/alma-cdk/openapix/blob/main/examples/books-api/schema/books-api.yaml), (中文(简体) ), _无_ 任何 AWS API 网关 OpenApi 扩展名, 您可以定义 API Gateway AWS 服务集成, 如 DynamoDB( 在您的堆栈内) :

```ts
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`](https://github.com/alma-cdk/openapix/tree/main/examples/books-api) 用于完整 OpenApi 定义(带有响应模型)和CDK应用程序中的实例.

  

## 模拟整合

鉴于以下各点: [`mock-api.yaml` OpenApi 计划定义](https://github.com/alma-cdk/openapix/blob/main/examples/mock-api/schema/mock-api.yaml), (中文(简体) ), _无_ 任何 AWS API 网关 OpenApi 扩展 :

```yaml
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 网关模拟集成(在您的堆栈内):

```ts
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`](https://github.com/alma-cdk/openapix/tree/main/examples/mock-api) 用于完整 OpenApi 定义(带有响应模型)和CDK应用程序中的实例.

  

## 验证器

API 网关 REST API 可以执行 [请求参数和请求正文验证](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-method-request-validation.html)。您既可以提供默认验证器,也可以提供集成特定验证器(它将覆盖给定集的默认值).

见 [`/examples/todo-api`](https://github.com/alma-cdk/openapix/tree/main/examples/todo-api) 例如,在 CDK 应用程序中.

鉴于 [`todo-api.yaml` OpenApi 计划定义](https://github.com/alma-cdk/openapix/blob/main/examples/todo-api/schema/todo-api.yaml) 您可以定义用于您在 CDK 中的整合的 API 网关验证器 :

```ts
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 的访问](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-to-api.html) 例如 [资源政策](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-resource-policies.html), (中文(简体) ), [IAM 权限](https://docs.aws.amazon.com/apigateway/latest/developerguide/permissions.html) 财务报告和审定财务报表 [aPI 密钥的使用计划](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-usage-plans.html) 但本节的重点是 [认知用户池](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html) 财务报告和审定财务报表 [蓝巴达授权人](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html)。 。 。 .

  

### 认知作者

在这个例子中,我们正在定义一个基于Congito用户池的授权人.

鉴于以下各点: `schema.yaml` OpenApi 定义 :

```yaml
openapi: 3.0.3
paths:
  /:
    get:
      security:
        - MyAuthorizer: ["test/read"] # add scope
components:
  securitySchemes:
    MyCognitoAuthorizer:
      type: apiKey
      name: Authorization
      in: header
```

您可以用 :

```ts
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 定义 :

```yaml
openapi: 3.0.3
paths:
  /:
    get:
      security:
        - MyAuthorizer: [] # note the empty array
components:
  securitySchemes:
    MyCustomAuthorizer:
      type: apiKey
      name: code
      in: query
```

您可以用 :

```ts
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) :

```ts
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 集成, 以正确的响应标题响应 :

```ts
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 魔法](https://medium.com/@srikanth650/use-api-gateway-with-mock-integration-to-allow-cors-from-multiple-origins-bdcb431d07d3) 答复 `Access-Control-Allow-Origin` 头曰.

### 默认 CORS

如果您想要定义每个路径的相同的 CORS 选项, 您可以通过提供默认选项来定义 `cors` 值 :

```ts
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 端点_](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-endpoint-types.html#api-gateway-api-endpoint-types-edge-optimized) 通过使用 [`EndpointType.EDGE`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.RestApi.html#endpointtypes) 作为默认.

这个构造 `@alma-cdk/openapix` 而不是默认使用 [_区域API终点_](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-endpoint-types.html#api-gateway-api-endpoint-types-regional) 设置 `EndpointType.REGIONAL` 作为默认值。 这是因为我们认为,在大多数情况下,你最好在API前配置出自己的"云纹"分布. 如果你这样做,你也可能有兴趣 [`@alma-cdk/origin-verify` 构造](https://github.com/alma-cdk/origin-verify)。 。 。 .

您可以在 `@alma-cdk/openapix` ,通过 `restApiProps`数字 :

```ts
new openapix.Api(this, 'MyApi', {
  source: './schema.yaml',

  paths: {/*...*/},

  restApiProps: {
    endpointConfiguration: {
      types: [ apigateway.EndpointType.EDGE ],
    },
  },
});
```

## 常见问题

### @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 和提交记录判断。

