How do I return only selected certain fields in Strapi?

Andrew Duensing picture Andrew Duensing · Jul 29, 2016 · Viewed 7.6k times · Source

Pretty straightforward (I hope). I'd like to be able to use the API endpoint and have it only return specified fields. I.E. something like this

http://localhost:1337/api/reference?select=["name"]

Would ideally return something of the form

[{"name": "Ref1"}]

Unfortunately that is not the case, and in actuality it returns the following.

This immediately becomes problematic in any real world context if I decide to load 10, 20, 30, or more records at once, I and end up loading 50 times the data I needed. More bandwidth is used up, slower load times, etc.

Answer

idolgoff picture idolgoff · Aug 24, 2020

How I solved this:

  1. Create custom controller action (for example, 'findPaths') in contributor/controllers/contributor.js
    module.exports = {
       findPaths: async ctx => {
           const result = await strapi
               .query('contributor')
               .model.fetchAll({ columns: ['slug'] }) // here we wait for one column only
           ctx.send(result);
       }
    }
  1. Add custom route (for example 'paths') in contributor/config/routes.json
    {
      "method": "GET",
      "path": "/contributors/paths",
      "handler": "contributor.findPaths",
      "config": {
        "policies": []
      }
    },
  1. Add permission in admin panel for Contributor entity, path action

That's it. Now it shows only slug field from all contributor's records.

http://your-host:1337/contributors/paths