{"id":13602660,"url":"https://github.com/alma-cdk/openapix","last_synced_at":"2026-02-14T04:10:02.469Z","repository":{"id":39798004,"uuid":"429589258","full_name":"alma-cdk/openapix","owner":"alma-cdk","description":"Combine the power of AWS CDK \u0026 OpenAPI YAML Schema Definitions","archived":false,"fork":false,"pushed_at":"2024-03-24T18:08:03.000Z","size":1174,"stargazers_count":97,"open_issues_count":20,"forks_count":6,"subscribers_count":8,"default_branch":"main","last_synced_at":"2025-04-02T09:09:25.335Z","etag":null,"topics":["api-gateway","aws","aws-cdk","aws-cdk-construct","cdk","openapi","rest-api","swagger"],"latest_commit_sha":null,"homepage":"https://constructs.dev/packages/@alma-cdk/openapix/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/alma-cdk.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-11-18T21:48:01.000Z","updated_at":"2025-03-27T10:59:07.000Z","dependencies_parsed_at":"2024-06-20T23:24:03.989Z","dependency_job_id":"2fe33bc1-142b-475f-87a1-44d2d4901714","html_url":"https://github.com/alma-cdk/openapix","commit_stats":{"total_commits":168,"total_committers":8,"mean_commits":21.0,"dds":0.2321428571428571,"last_synced_commit":"f4ec29a282bea3bc0cb6cf97eeabf182523bc9c5"},"previous_names":["almamedia-open-source/cdk-openapix"],"tags_count":56,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alma-cdk%2Fopenapix","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alma-cdk%2Fopenapix/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alma-cdk%2Fopenapix/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alma-cdk%2Fopenapix/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/alma-cdk","download_url":"https://codeload.github.com/alma-cdk/openapix/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248018060,"owners_count":21034048,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api-gateway","aws","aws-cdk","aws-cdk-construct","cdk","openapi","rest-api","swagger"],"created_at":"2024-08-01T18:01:33.118Z","updated_at":"2026-02-14T04:09:57.451Z","avatar_url":"https://github.com/alma-cdk.png","language":"TypeScript","funding_links":[],"categories":["TypeScript","aws"],"sub_categories":[],"readme":"\u003cdiv align=\"center\"\u003e\n\t\u003cbr/\u003e\n\t\u003cbr/\u003e\n  \u003ch1\u003e\n\t\u003cimg height=\"140\" src=\"assets/alma-cdk-openapix.svg\" alt=\"Alma CDK OpenApiX\" /\u003e\n  \u003cbr/\u003e\n  \u003cbr/\u003e\n  \u003c/h1\u003e\n\n  ```sh\n  npm i -D @alma-cdk/openapix\n  ```\n\n  \u003cdiv align=\"left\"\u003e\n\n  Generate AWS Api Gateway REST APIs via [OpenAPI](https://www.openapis.org/) (formely known as “Swagger”) Schema Definitions by consuming \"clean\" OpenAPI schemas and inject `x-amazon-apigateway-` extensions _with type-safety_.\n\n  \u003c/div\u003e\n  \u003cbr/\u003e\n\u003c/div\u003e\n\n\n\u003cbr/\u003e\n\n\u003cdiv align=\"center\"\u003e\n\n![diagram](assets/diagram.svg)\n\n\u003c/div\u003e\n\n\u003cbr/\u003e\n\n## 🚧 \u0026nbsp; Project Stability\n\n![experimental](https://img.shields.io/badge/stability-experimental-yellow \"Stability: Experimental\")\n\nThis construct is still versioned with `v0` major version and breaking changes might be introduced if necessary (without a major version bump), though we aim to keep the API as stable as possible (even within `v0` development). We aim to publish `v1.0.0` soon and after that breaking changes will be introduced via major version bumps.\n\nThere are also some incomplete or buggy features, such as CORS and `CognitoUserPoolsAuthorizer`.\n\n\n\u003cbr/\u003e\n\n## Getting Started\n\n1. Install `npm i -D @alma-cdk/openapix`\n\n2. Define your API OpenApi Schema Definition in a `.yaml` file\u003cbr/\u003e_without_ any `x-amazon-apigateway-` extensions\n\n3. Use `openapix` constructs in CDK to consume the `.yaml` file and then assign API Gateway integrations using CDK\n\n\n\u003cbr/\u003e\n\n## HTTP Integration\n\nGiven the following [`http-proxy.yaml` OpenApi schema definition](https://github.com/alma-cdk/openapix/blob/main/examples/http-proxy/schema/http-proxy.yaml), _without_ any AWS API Gateway OpenApi extensions:\n```yaml\nopenapi: 3.0.3\ninfo:\n  title: HTTP Proxy\n  description: Proxies requests to example.com\n  version: \"0.0.1\"\npaths:\n  \"/\":\n    get:\n      summary: proxy\n      description: Proxies example.com\n```\n\nYou may then define API Gateway HTTP integration (within your stack):\n```ts\nnew openapix.Api(this, 'HttpProxy', {\n  source: path.join(__dirname, '../schema/http-proxy.yaml'),\n\n  paths: {\n    '/': {\n      get: new openapix.HttpIntegration(this, 'http://example.com', {\n          httpMethod: 'get',\n      }),\n    },\n  },\n});\n```\n\nSee [`/examples/http-proxy`](https://github.com/alma-cdk/openapix/tree/main/examples/http-proxy) for full OpenApi definition (with response models) and an example within a CDK application.\n\n\n\u003cbr/\u003e\n\n## Lambda Integration\n\nGiven the following [`hello-api.yaml` OpenApi schema definition](https://github.com/alma-cdk/openapix/blob/main/examples/hello-api/schema/hello-api.yaml), _without_ any AWS API Gateway OpenApi extensions:\n```yaml\nopenapi: 3.0.3\ninfo:\n  title: Hello API\n  description: Defines an example “Hello World” API\n  version: \"0.0.1\"\npaths:\n  \"/\":\n    get:\n      operationId: sayHello\n      summary: Say Hello\n      description: Prints out a greeting\n      parameters:\n      - name: name\n        in: query\n        required: false\n        schema:\n          type: string\n          default: \"World\"\n      responses:\n        \"200\":\n          description: Successful response\n          content:\n            \"application/json\":\n              schema:\n                $ref: \"#/components/schemas/HelloResponse\"\n\ncomponents:\n  schemas:\n    HelloResponse:\n      description: Response body\n      type: object\n      properties:\n        message:\n          type: string\n          description: Greeting\n          example: Hello World!\n```\n\nYou may then define API Gateway AWS Lambda integration (within your stack):\n```ts\nconst greetFn = new NodejsFunction(this, 'greet');\n\nnew openapix.Api(this, 'HelloApi', {\n  source: path.join(__dirname, '../schema/hello-api.yaml'),\n  paths: {\n    '/': {\n      get: new openapix.LambdaIntegration(this, greetFn),\n    },\n  },\n})\n```\n\nSee [`/examples/hello-api`](https://github.com/alma-cdk/openapix/tree/main/examples/hello-api) for full OpenApi definition (with response models) and an example within a CDK application.\n\n\n\u003cbr/\u003e\n\n\n\n## AWS Service Integration\n\nGiven [`books-api.yaml` OpenApi schema definition](https://github.com/alma-cdk/openapix/blob/main/examples/books-api/schema/books-api.yaml), _without_ any AWS API Gateway OpenApi extensions, You may then define API Gateway AWS service integration such as DynamoDB (within your stack):\n\n```ts\nnew openapix.Api(this, 'BooksApi', {\n  source: path.join(__dirname, '../schema/books-api.yaml'),\n  paths: {\n    '/': {\n      get: new openapix.AwsIntegration(this, {\n        service: 'dynamodb',\n        action: 'Scan',\n        options: {\n          credentialsRole: role, // role must have access to DynamoDB table\n          requestTemplates: {\n            'application/json': JSON.stringify({\n              TableName: table.tableName,\n            }),\n          },\n          integrationResponses: [\n            {\n              statusCode: '200',\n              responseTemplates: {\n                // See /examples/http-proxy/lib/list-books.vtl\n                'application/json': readFileSync(__dirname+'/list-books.vtl', 'utf-8'),\n              },\n            }\n          ],\n        },\n      }),\n    },\n    '/{isbn}': {\n      get: new openapix.AwsIntegration(this, {\n        service: 'dynamodb',\n        action: 'GetItem',\n        options: {\n          credentialsRole: role, // role must have access to DynamoDB table\n          requestTemplates: {\n            'application/json': JSON.stringify({\n              TableName: table.tableName,\n              Key: {\n                item: {\n                  \"S\": \"$input.params('isbn')\"\n                }\n              }\n            }),\n          },\n          integrationResponses: [\n            {\n              statusCode: '200',\n              responseTemplates: {\n                // See /examples/http-proxy/lib/get-book.vtl\n                'application/json': readFileSync(__dirname+'/get-book.vtl', 'utf-8'),\n              },\n            }\n          ],\n        },\n      }),\n    },\n  },\n});\n```\n\nSee [`/examples/books-api`](https://github.com/alma-cdk/openapix/tree/main/examples/books-api) for full OpenApi definition (with response models) and an example within a CDK application.\n\n\u003cbr/\u003e\n\n## Mock Integration\n\nGiven the following [`mock-api.yaml` OpenApi schema definition](https://github.com/alma-cdk/openapix/blob/main/examples/mock-api/schema/mock-api.yaml), _without_ any AWS API Gateway OpenApi extensions:\n\n```yaml\nopenapi: 3.0.3\ninfo:\n  title: Hello API\n  description: Defines an example “Hello World” API\n  version: \"0.0.1\"\npaths:\n  \"/\":\n    get:\n      operationId: sayHello\n      summary: Say Hello\n      description: Prints out a greeting\n      parameters:\n      - name: name\n        in: query\n        required: false\n        schema:\n          type: string\n          default: \"World\"\n      responses:\n        \"200\":\n          description: Successful response\n          content:\n            \"application/json\":\n              schema:\n                $ref: \"#/components/schemas/HelloResponse\"\n\ncomponents:\n  schemas:\n    HelloResponse:\n      description: Response body\n      type: object\n      properties:\n        message:\n          type: string\n          description: Greeting\n          example: Hello World!\n```\n\nYou may then define API Gateway Mock integration (within your stack):\n```ts\nnew openapix.Api(this, 'MockApi', {\n  source: path.join(__dirname, '../schema/mock-api.yaml'),\n  paths: {\n    '/': {\n      get: new openapix.MockIntegration(this, {\n        requestTemplates: {\n          \"application/json\": JSON.stringify({ statusCode: 200 }),\n        },\n        passthroughBehavior: apigateway.PassthroughBehavior.NEVER,\n        requestParameters: {\n          'integration.request.querystring.name': 'method.request.querystring.name',\n        },\n        integrationResponses: [\n          {\n            statusCode: '200',\n            responseTemplates: {\n              // see /examples/mock-api/lib/greet.vtl\n              'application/json': readFileSync(__dirname+'/greet.vtl', 'utf-8'),\n            },\n            responseParameters: {},\n          },\n        ],\n      }),\n    },\n  },\n});\n```\n\nSee [`/examples/mock-api`](https://github.com/alma-cdk/openapix/tree/main/examples/mock-api) for full OpenApi definition (with response models) and an example within a CDK application.\n\n\u003cbr/\u003e\n\n## Validators\n\nAPI Gateway REST APIs can perform [request parameter and request body validation](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-method-request-validation.html). You can provide both default validator and integration specific validator (which will override the default for given integration).\n\nSee [`/examples/todo-api`](https://github.com/alma-cdk/openapix/tree/main/examples/todo-api) for complete example within a CDK application.\n\nGiven [`todo-api.yaml` OpenApi schema definition](https://github.com/alma-cdk/openapix/blob/main/examples/todo-api/schema/todo-api.yaml) you may define the API Gateway validators for your integration in CDK:\n```ts\nnew openapix.Api(this, 'MyApi', {\n  source: path.join(__dirname, '../schema/todo-api.yaml'),\n\n  validators: {\n    'all': {\n      validateRequestBody: true,\n      validateRequestParameters: true,\n      default: true, // set this as the \"API level\" default validator (there can be only one)\n    },\n    'params-only' : {\n      validateRequestBody: false,\n      validateRequestParameters: true,\n    },\n  },\n\n  paths: {\n    '/todos': {\n      // this one uses the default 'all' validator\n      post:  new openapix.HttpIntegration(this, baseUrl, { httpMethod: 'post' }),\n    },\n    '/todos/{todoId}': {\n      // this one has validator override and uses 'params-only' validator\n      get: new openapix.HttpIntegration(this, `${baseUrl}/{todoId}`, {\n        validator: 'params-only',\n        options: {\n          requestParameters: {\n            'integration.request.path.todoId': 'method.request.path.todoId',\n          },\n        },\n      }),\n    },\n  },\n})\n```\n\n\u003cbr/\u003e\n\n## Authorizers\n\n🚧 Work-in-Progress\n\nThere are multiple ways to [control \u0026 manages access to API Gateway REST APIs](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-to-api.html) such as [resource policies](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-resource-policies.html), [IAM permissions](https://docs.aws.amazon.com/apigateway/latest/developerguide/permissions.html) and [usage plans with API keys](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-usage-plans.html) but this section focuses on [Cognito User Pools ](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html) and [Lambda authorizers](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html).\n\n\u003cbr/\u003e\n\n### Cognito Authorizers\n\nIn this example we're defining a Congito User Pool based authorizer.\n\nGiven the following `schema.yaml` OpenApi definition:\n```yaml\nopenapi: 3.0.3\npaths:\n  /:\n    get:\n      security:\n        - MyAuthorizer: [\"test/read\"] # add scope\ncomponents:\n  securitySchemes:\n    MyCognitoAuthorizer:\n      type: apiKey\n      name: Authorization\n      in: header\n```\n\nYou can define the Cognito Authorizer in CDK with:\n```ts\nconst userPool: cognito.IUserPool;\n\nnew openapix.Api(this, 'MyApi', {\n  source: './schema.yaml',\n\n  authorizers: [\n    new openapix.CognitoUserPoolsAuthorizer(this, 'MyCognitoAuthorizer', {\n      cognitoUserPools: [userPool],\n      resultsCacheTtl: Duration.minutes(5),\n    })\n  ],\n})\n```\n\n\u003cbr/\u003e\n\n### Lambda Authorizers\n\nIn this example we're defining a custom Lambda authorizer. The authorizer function code is not relevant for the example but the idea in the example is that an API caller sends some \"secret code\" in query parameters (`?code=example123456`) which then the authorizer function somehow evaluates.\n\nGiven the following `schema.yaml` OpenApi definition:\n```yaml\nopenapi: 3.0.3\npaths:\n  /:\n    get:\n      security:\n        - MyAuthorizer: [] # note the empty array\ncomponents:\n  securitySchemes:\n    MyCustomAuthorizer:\n      type: apiKey\n      name: code\n      in: query\n```\n\nYou can define the custom Lambda Authorizer in CDK with:\n```ts\nconst authFn: lambda.IFunction;\n\nnew openapix.Api(this, 'MyApi', {\n  source: './schema.yaml',\n\n  authorizers: [\n\n    new openapix.LambdaAuthorizer(this, 'MyCustomAuthorizer', {\n      fn: authFn,\n      identitySource: apigateway.IdentitySource.queryString('code'),\n      type: 'request',\n      authType: 'custom',\n      resultsCacheTtl: Duration.minutes(5),\n    }),\n  ],\n\n\n})\n```\n\n\n\u003cbr/\u003e\n\n## Inject/Reject\n\nYou may modify the generated OpenAPI definition (which is used to define API Gateway REST API) by injecting or rejecting values from the source OpenAPI schema definition:\n```ts\nnew openapix.Api(this, 'MyApi', {\n  source: './schema.yaml',\n\n  // Add any OpenAPI v3 data.\n  // Can be useful for passing values from CDK code.\n  // See https://swagger.io/specification/\n  injections: {\n    \"info.title\": \"FancyPantsAPI\"\n  },\n\n  // Reject fields by absolute object path from generated definition\n  rejections: ['info.description'],\n\n  // Reject all matching fields from generated definition\n  rejectionsDeep: ['example', 'examples'],\n});\n```\n\n\u003cbr/\u003e\n\n## CORS\n\n🚧 Work-in-Progress\n\nUsing `openapix.CorsIntegration` creates a Mock integration which responds with correct response headers:\n\n```ts\nnew openapix.Api(this, 'MyApi', {\n  source: './schema.yaml',\n\n  paths: {\n    '/foo': {\n      options: new openapix.CorsIntegration(this, {\n        // using helper method to define explicit values:\n        headers: CorsHeaders.from(this, 'Content-Type', 'X-Amz-Date', 'Authorization'),\n        origins: CorsOrigins.from(this, 'https://www.example.com'),\n        methods: CorsMethods.from(this, 'options','post','get'),\n      }),\n    },\n    '/bar': {\n      options: new openapix.CorsIntegration(this, {\n        // using regular string values:\n        headers: 'Content-Type,X-Amz-Date,Authorization',\n        origins: '*',\n        methods: 'options,get',\n      }),\n    },\n    '/baz': {\n      options: new openapix.CorsIntegration(this, {\n        // using helper constant for wildcard values:\n        headers: CorsHeaders.ANY,\n        origins: CorsOrigins.ANY,\n        methods: CorsMethods.ANY,\n      }),\n    },\n  },\n});\n```\n\nWhen specifying multiple `origins` the mock integration uses [VTL magic](https://medium.com/@srikanth650/use-api-gateway-with-mock-integration-to-allow-cors-from-multiple-origins-bdcb431d07d3) to respond with the correct `Access-Control-Allow-Origin` header.\n\n### Default CORS\n\nIf you wish to define same CORS options to every path, you may do so by providing a default `cors` value:\n```ts\nnew openapix.Api(this, 'MyApi', {\n  source: './schema.yaml',\n\n  defaultCors: new openapix.CorsIntegration(this, {\n    headers: CorsHeaders.ANY,\n    origins: CorsOrigins.ANY,\n    methods: CorsMethods.ANY,\n  }),\n\n  paths: {/*...*/},\n});\n```\n\nThis will apply the given `cors` configuration to _every_ path as `options` method. You may still do path specific overrides by adding an `options` method to specific paths.\n\n\u003cbr/\u003e\n\n## API Gateway EndpointType\n\nAWS CDK API Gateway constructs default to [_Edge-optimized API endpoints_](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-endpoint-types.html#api-gateway-api-endpoint-types-edge-optimized) by using [`EndpointType.EDGE`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.RestApi.html#endpointtypes) as the default.\n\nThis construct `@alma-cdk/openapix` instead defaults to using [_Regional API endpoints_](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-endpoint-types.html#api-gateway-api-endpoint-types-regional) by setting `EndpointType.REGIONAL` as the default value. This is because we believe that in most cases you're better of by configuring your own CloudFront distribution in front the API. If you do that, you might also be interested in [`@alma-cdk/origin-verify` construct](https://github.com/alma-cdk/origin-verify).\n\nYou MAY override this default in `@alma-cdk/openapix` by providing your preferred endpoint types via `restApiProps`:\n```ts\nnew openapix.Api(this, 'MyApi', {\n  source: './schema.yaml',\n\n  paths: {/*...*/},\n\n  restApiProps: {\n    endpointConfiguration: {\n      types: [ apigateway.EndpointType.EDGE ],\n    },\n  },\n});\n```\n\n\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falma-cdk%2Fopenapix","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falma-cdk%2Fopenapix","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falma-cdk%2Fopenapix/lists"}