Search code examples
node.jstypescriptloopback

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.


Solution

  • 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"
        }
      ]
    }