aws-api-gatewayaws-cdkaws-cdk-typescript

Adding a new model to an existing aws api gateway using CDK and Typescript


I have an API gateway defined in a cdk project and I have exported the RestApi. In a different project, I'm trying to add a few Models to this API gateway but I get an error. Here is how the import line:

const restApi = apiGateway.RestApi.fromRestApiId(this,"MyGatewayApi",props.restApiId);

and when I try to add a model I get this error:

Property 'addModel' does not exist on type 'IRestApi'.

Here is the code that uses the restApi:

const errorModel = restApi.addModel('errorModel', {
      contentType: 'application/json',
      modelName: 'Error',
      schema: {
        schema: apiGateway.JsonSchemaVersion.DRAFT4,
        title: 'Error',
        type: apiGateway.JsonSchemaType.OBJECT,
        properties: {
          errorId: {type: apiGateway.JsonSchemaType.STRING} ,
        }
      }
    });

Then I changed my import line to this :

const restApi = apiGateway.RestApi.fromRestApiId(this,"MyGatewayApi",props.restApiId) as apiGateway.RestApi;

and the IDE doesn't show any errors. But the problem is when I run cdk synth it returns another error:

const errorModel = restApi.addModel('errorModel', { ^ TypeError: restApi.addModel is not a function

Does anybody know what's wrong? and how can I fix it?


Solution

  • Add a model with the Model constructor. The restApi prop accepts the IRestApi type:

    const errorModel = new apigw.Model(this, "errorModal", {
        restApi,
        schema: {},
    });
    

    The addModel method isn't exposed on the IRestApi interface type returned by the fromRestApiId method. This is an implemenation choice, not an underlying constraint. Under the hood, addModel just calls the Model constructor as we do above.