'How to get random records from Strapi content API

I have records in strapi. I am using strapi content API. In my front-end, I need to display only 2 records randomly. For limiting, I have used limit query from content API. But random fetching what keyword I need to use. The official documentation doesn't provide any details regarding this - https://strapi.io/documentation/v3.x/content-api/parameters.html#available-operators



Solution 1:[1]

One way you can do this reliably is by two steps:

  1. Get the total number of records
  2. Fetch the number of records using _start and _limit parameters
// Untested code but you get the idea

// Returns a random number between min (inclusive) and max (exclusive)
function getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
}

const { data: totalNumberPosts } = await axios.get('/posts/count');

// Fetch 20 posts
const _limit = 20;

// We need to be sure that we are not fetching less than 20 posts
// e.g. we only have 40 posts. We generate a random number that is 30.
// then we would start on 30 and would only fetch 10 posts (because we only have 40)
const _start = getRandomArbitrary(0, totalNumberPosts - _limit);

const { data: randomPosts } = await axios.get('/posts', { params: { _limit, _start } })

The problem with this approach is that it requires two network requests but for my needs, this is not a problem.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1