LoginSignup
1
1

More than 3 years have passed since last update.

AWS CDKでSwaggerからAPI Gatewayを構築する

Last updated at Posted at 2020-04-22

概要

AWS CDKでは、API GatewayのSwaggerが対応されてなくてハマったのでメモ。

API Gatewayのリソース定義

import cdk = require('@aws-cdk/aws-core');
import apigateway = require('@aws-cdk/aws-apigateway');

export class ApigatewayStack extends cdk.Stack {
    constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
        // Rest API
        const api = new apigateway.RestApi(this, 'ApiGateway', {
            endpointConfiguration: {
                types: [ apigateway.EndpointType.REGIONAL ],
            },
            restApiName: 'API',
        });

        // Api Gateway Stage
        const stage = new apigateway.Stage(this, 'ApiGatewayStage', {
            deployment: new apigateway.Deployment(this, 'ApiGatewayDeployment', { api }),
            stageName: 'Stage'
        });

        // Usage Plan
        api.addUsagePlan('ApiGatewayUsagePlan', {
            apiStages: [
                { api, stage },
            ],
            description: 'UsagePlan for API',
            name: 'UsagePlan',
        });
    }
}

SwaggerのJsonファイルをS3にアップロード

S3バケットのJSONファイルを参照してAPI Gatewayのリソースを構築するので先にアップロードしておく。
事前に、SwaggerのJSONファイルをredoc-cliなどで生成しておく。

new s3deploy.BucketDeployment(this, 'DeploySwagger', {
    sources: [s3deploy.Source.asset(`${destDir}`)], // JSONファイルのディレクトリ
    destinationBucket: s3.Bucket.fromBucketName(this, 'SwaggerBucketName', 'Bucket'), // アップロード先のバケット
    destinationKeyPrefix: `swagger/`,
});

SwaggerのJSONファイルからAPI Gatewayのリソース生成

Cfnリソースを利用する。bodyプロパティにSwaggerのJSONファイルのパスを指定する。

const cfnApi = api.node.defaultChild as apigateway.CfnRestApi;

cfnApi.bodyS3Location = {
    bucket: 'Bucket',
    key: 'swagger/openapi.json'
};

以上でAPI Gatewayのリソースが生成できるが、これだけではエラーになってしまったので、モックのMETHODを定義しておく。

api.root.addMethod('ANY', new apigateway.MockIntegration());
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1