How to Count in REST API in v4?

Hi @gorlaz,

You are right that this is not an enabled route by default (I think).

But you can create a custom route easily, by creating/modifying two files:

First, create a custom route file for in your api/content-type folder (assuming you have a content type named product and want the total count of them):

module.exports = {
    routes: [
        { // Path defined with a URL parameter
            method: 'GET',
            path: '/products/count',
            handler: 'product.count',
        },
    ]
}

Then customize your content type’s controller, and use the query engine to get the UID count.

'use strict';

/**
 *  product controller
 */

const { createCoreController } = require('@strapi/strapi').factories;

module.exports = createCoreController('api::product.product', {
    count(ctx) {
        var { query } = ctx.request
        return strapi.query('api::product.product').count({ where: query });
    }
});

Enable route permissions and test:
image
With parameters:
image

I have provided the code in this github repo if you’d like to fork:

1 Like