Search code examples
arraystypescriptswaggeraws-api-gatewayaws-cdk

Use an array as response model in AWS Gateway cdk


I'm trying to create a typescript aws cdk to build up an API Gateway with this own swagger documentation. There is one simple endpoint returning a list of "Supplier", but we don't know how to specify this in the cdk.

Here the code:

export function CreateSupplierMethods(apigw: apigateway.Resource,restApiId: string, scope: cdk.Construct, api: apigateway.RestApi) {

let suppliers = apigw.addResource('suppliers')

let supplierModel = new apigateway.Model(scope, "supplier-model", {
  modelName: "supplier",
  restApi: api,
  contentType: 'application/json',
  schema: {
    description: "Supplier data",
    title: "Supplier",
    properties: {
      code: { type: apigateway.JsonSchemaType.STRING, minLength: 4, maxLength: 6},
      name: { type: apigateway.JsonSchemaType.STRING, maxLength: 81},
    }
  },
})

let getSuppliers = suppliers.addMethod('GET', new apigateway.MockIntegration(), {
    methodResponses: [{
        statusCode: "200",
        responseModels: {
          "application/json": supplierModel,
        }
    },
    {
        statusCode: "401",
    }]
})
}

As you can see, the GET has the supplierModel as output. How can I say "returns a list of supplierModel"? I wish I can use this model for both list of supplier and single instances of supplier (like a GET method with id as input).

Is this possible? If yes, how?

Looking the generated json, I'm trying to have something like this:

enter image description here

But what I'm getting now is quite different:

enter image description here

How can I get a result like the first image?


Solution

  • You are creating a model and assigning it to the method. Create an array of those models and then assign that array to the method.

    let supplierModelArray = new apigateway.Model(scope, "supplier-model-array", {
      modelName: "supplier-array",
      restApi: api,
      contentType: 'application/json',
      schema: {
        description: "Supplier data",
        title: "Supplier",
        type: apigateway.JsonSchemaType.ARRAY
        items: {type: supplierModel}
      },
    })
    

    And change the "application/json": supplierModel in api to "application/json": supplierModelArray