Jota
Jota

Reputation: 81

LOOPBACK 4: Add parameters in a API call

I am new in Loopback 4 (NodeJS) and I have a question. I am developing an API. How can indicate parameters in the body of a post request that are not define as a model?.

Example:

@post('/gameshits/{id}', {
    responses: {
      '200': {
        description: 'Return the number of correct answers',
      },
    },
  })
  async gamesHits(
    @param.path.string('id') id: string,
    @requestBody() answers: Array<String>,
  ): Promise<number> {
     ....
}

The problem is in the requestBody() Its compile but in the loopback/explorer said that it can be render. The only option is create a model? how can add more parameters to send in the body of the call? (not in the url like @param do)

Thanks.

Upvotes: 0

Views: 2506

Answers (2)

You don't need any documentation but swagger's documentation regarding describing requests: https://swagger.io/docs/specification/2-0/describing-request-body/?sbsearch=request

Then just apply the OpenAPI Specification inside the @requestBody decorator as mentioned by darkunbeknownst.

Upvotes: 0

darkunbeknownst
darkunbeknownst

Reputation: 46

No you don't need to create a model to indicate parameters, actually it's very easy but there's no much documentation about it.

You can indicate something like this.

@post('/gameshits/{id}', {
  responses: {
    '200': {
      description: 'Return the number of correct answers',
    },
  },
})
async gamesHits(
  @param.path.string('id') id: string,
  @requestBody({
    content: {
      'application/json': {
        type: 'object',
        schema: {
          properties: {
            gameName: {type: 'string'},
            characters: {
              type: 'array',
              items: {
                properties: {
                  name: {type: 'number'},
                  power: {type: 'number'},
                  cost: {type: 'number'},
                  ability: {type: 'string'}
                },    
              },
            },
          },
        },
      },
    },
  }) data: any,
): Promise<number> {
   ....
}

To get a loopback/explorer response like this.

{
  "gameName": "string",
  "characters": [
    {
      "name": 0,
      "power": 0,
      "cost": 0,
      "ability": "string"
    }
  ]
}

Upvotes: 3

Related Questions