Utilize an array as the response model in Amazon API Gateway using the AWS CDK

I am currently in the process of developing a TypeScript AWS CDK to set up an API Gateway along with its own Swagger documentation. One of the requirements is to create a simple endpoint that returns a list of "Supplier", but I am facing challenges in specifying this in the CDK.

Below is the code snippet:

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",
    }]
})
}

The challenge lies in defining how the GET method should return a list of supplierModel. I also need to use this model for both lists of suppliers and individual supplier instances (e.g., a GET method with ID as input).

Is it possible to achieve this? If so, how can it be done?

Upon reviewing the generated JSON, my goal is to have an output similar to the following:

https://i.sstatic.net/FURgp.png

However, the current result looks quite different:

https://i.sstatic.net/xFg8H.png

How can I modify the configuration to obtain a result similar to the first image?

Answer №1

When developing a model and assigning it to a method, consider creating an array of those models and then linking 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}
  },
})

Additionally, modify the

"application/json": supplierModel
in the API to instead read
"application/json": supplierModelArray

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Seamlessly incorporating Storybook with Tailwind CSS, Create Next App, and TypeScript

*This is a new question regarding my struggles with integrating Storybook and Tailwind CSS. Despite following the recommended steps, I am unable to make Tailwind work within Storybook. Here's what I've done: I started a TypeScript project from s ...

Adding a timestamp or hash as a request parameter for css or js files in the NextJS 12 build file can be accomplished by simply including "?ts=[timestamp]" in the file

It is important for me to be able to generate the following JavaScript and CSS file names with timestamps after building a NextJs application: ./path/file.js?ts=[timestamp] ./path/file.css?ts=[timestamp] ...

Locate the index position of an element in one array based on a corresponding element in a

I am seeking a way to determine the index and group that an item belongs to within a parent json group. Is there a method for achieving this? I am willing to modify the json format if necessary. I made an attempt using JSON.stringify(), but it seems to be ...

Changing an array of arrays into an object using javascript

Here is an example array: var arrays = [ { "name": "aaa", "value": "bbb" }, { "name": "ccc", "value": "ccc" }, { "name": "ddd", "value": [ & ...

What's causing the subscription feature to malfunction in a fresh browser tab?

I am facing an issue with camera entries on an angular website. Whenever I click on an entry, a new window opens to display the camera livestream. However, I am having trouble with the subscribe functionality. Important note: Once the window is open, subs ...

The Angular2 Router encounters an issue with the URL when it contains the "&

Ever since updating to the latest version of angular v4.3.2, I've encountered an issue where all my URLs break at the & value. For instance, I have a route /:value from which I need to retrieve the value: http://localhost:4200/one&two Inst ...

Error: The function list.forEach does not exist within service.buildList [as project]

Today, I've been grappling with a challenging issue. As someone new to Typescript and Angular, I'm attempting to make a call to my backend API. However, when trying to populate an array for display, I keep encountering an error that says rawRegis ...

Creating table structure dynamically using Node.js

I'm attempting to automatically create a table using nodejs "@google-cloud/bigquery": "^3.0.0" with the following approach: const bigqueryClient = new BigQuery(); schema = `driverId:string, passengerIds:(repeated string), pickedUp:(repeated s ...

Error encountered during the deployment of Ionic 3 with TypeScript

After completing the development of my app, I ran it on ionic serve without any issues. However, when compiling the app, I encountered the following error message. Any assistance in resolving this matter would be greatly appreciated. [15:40:08] typescri ...

Tips on looping through a universal array and retrieving user input

My current project involves creating a news site using the Guardian API. I want to implement a search feature that allows users to input keywords and retrieve the webTitle attribute for matching elements. While I could simply insert the user input directly ...

Expanding a TypeScript type by creating an alias for a property

I am working on defining a type that allows its properties to be "aliased" with another name. type TTitle: string; type Data<SomethingHere> = { id: string, title: TTitle, owner: TPerson, } type ExtendedData = Data<{cardTitle: "title&qu ...

Error encountered in Angular 7.2.0: Attempting to assign a value of type 'string' to a variable of type 'RunGuardsAndResolvers' is not allowed

Encountering an issue with Angular compiler-cli v.7.2.0: Error message: Types of property 'runGuardsAndResolvers' are incompatible. Type 'string' is not assignable to type 'RunGuardsAndResolvers' This error occurs when try ...

Using JavaScript or TypeScript to locate the key and add the value to an array

My dilemma involves an object structured as follows: [{ Date: 01/11/2022, Questionnaire: [ {Title: 'Rating', Ans: '5' }, {Title: 'Comment', Ans: 'Awesome' } ] }, { Date: 01/11/2022, Questionnaire ...

Code error TS2345 occurs when assigning the argument of type '{ headers: HttpHeaders; }' to a parameter of type 'RequestOptionsArgs'. This indicates a mismatch in the type of data being passed, causing an

Upon running ionic serve, these are the results that I am encountering. My setup consists of Ionic4 version with Angular 8. While executing the command, this error appears: src/app/home/home.page.ts:60:77 - error TS2345: Argument of type '{ headers ...

Transform an array of integers pointers into an array of characters pointers with a varied size or composition

I am attempting to transform an int** array into a char** array that consists of the number of rows and is comma-separated. The initial int** array looks like this: 1 2 3 4 5 6 7 8 9 3 2 1 An ideal representation of what I want the char** array to look l ...

Can someone assist me with running queries on the MongoDB collection using Node.js?

In my mongodb collection called "jobs," I have a document format that needs to display all documents matching my query. { "_id": { "$oid": "60a79952e8728be1609f3651" }, "title": "Full Stack Java Develo ...

The array is arranged properly, yet React is failing to render it in the correct order

Here's the code snippet I am working with: { this.state.rows.map((qc) => qc.BinsByDayByOrchardsQCs.map((qc2) => qc2.BinsByDayByOrchardsQCsDefects.map((qc3) => !defectsArray.includes(qc3.Defect) &am ...

What is the equivalent of getElementById in .ts when working with tags in .js?

Looking to incorporate Electron, Preload, Renderer with ReactJS and TypeScript into my project. <index.html> <body> <div id="root" /> <script src='./renderer.js'/> </body> <index.ts> const root = Re ...

Retrieve targeted information from the Coin Market Cap API by extracting specific data values using an array

I am looking to retrieve the symbol and other details using the "name" from my array. $.getJSON("//api.coinmarketcap.com/v1/ticker/?limit=0", function(data) { var crypto = [ "Ethereum", "Ripple", "Tron", ]; // used for arr ...

Duplicate the ng-template using ng-content as the body (make a duplicate of ng-content)

I have been working on creating a feature that allows users to add custom columns to a PrimeNg table. The main reason for developing this feature is to provide users with a default table that already has numerous configuration options pre-set. However, I ...