bonnegnu
bonnegnu

Reputation: 195

Send parameters to strapi custom api

I need to send parameters to a custom api made in strapi.

The controller category.js:

module.exports = {
  async findCustom(ctx) {
    console.log(ctx.params);
    const { userId, categoryId } = ctx.params;
    var res = await strapi.connections.default.raw(
      `SELECT
      user_id,
      category
  FROM
      categories
  WHERE
      user_id = ${userId} AND category = ${categoryId}`
    );

    return res;
  },
};

The routes.json:

{
  "method": "GET",
  "path": "/categories/custom",
  "handler": "category.findCustom",
  "config": {
    "policies": []
  }
}

How do I get it to take the parameters sent from:

http://localhost:1337/categories/custom?userId=2&categoryId=1

Upvotes: 1

Views: 3688

Answers (1)

Eggcellentos
Eggcellentos

Reputation: 1758

Strapi uses koa - check this out.

You can get them inside your handler like this:

async findCustom(ctx) {
  const queryObj = ctx.request.query
  //rest of method
}

For your request the object will contain:

{
  userId: '2',
  categoryId: '1'
}

-----------------------Adding warnings to the answer----------------------
Expanding on @Daniel A. White's cooment -
You are really exposing yourself by allowing parts of an SQL query to be injected directly into a soon-to-be ran query. Just be careful if moving to production/public - understanding SQL injection is a must here.
Also adding suggested reads for dangers of Information exposure:
Should sensitive data ever be passed in the query string?
Information exposure through query strings in url

Upvotes: 4

Related Questions