Search code examples
strapi

Select fewer fields in populated data using query for Strapi


The idea is to get localizations of a product, which ID we know, by populating localizations field. So result of the query ( {{strapiUrl}}/products/2?populate=localizations ) could look like an example:

{
    "data": {
        "id": 2,
        "attributes": {
            "title": "title en",
            // ...
            "localizations": {
                "data": [
                    {
                        "id": 1,
                        "attributes": {
                            "title": "title ka",
                            "locale": "ka",
                            // ...
                        }
                    }
                ]
            }
        }
    },
    "meta": {}
}

I'd like to use filter by and get only the fields in order to get only the id field of the localizations filed, possibly, that matches "locale": "ka" only. Otherwise, we have to just get [0] the first index of it.

So the expected output after "filtering" the returned object would not include some other fields of the item with id=1, but just locale of it:

// expected output
{
    "data": {
        "id": 2,
        "attributes": {
            "title": "title en",
            // ...
            "localizations": {
                "data": [
                    {
                        "id": 1,
                        "attributes": {
                            // want only locale
                            "locale": "ka",
                        }
                    }
                ]
            }
        }
    },
    "meta": {}
}

Just to be clear - we need to not get anything than locale in data.attributes.localizations[0].data.attributes.locale without the need to filter it on the frontend.


Solution

  • Figured out combining few sections of documentation:

    So, if you need to get limited amount of the other localized object (like only id and locale of requested id of the product (in my case 2), the solution is this:

    GET: {{strapiUrl}}/products/2?populate[localizations][fields]=locale