profile.jpg

Aditya Pratama

DevOps | SRE | Cloud Engineer
Return to Blog List

Strapi Setup: Customize Response API

August 19, 2022

Here I share how to customize the response from the API, by default the responses given. But there are times when I don't use these fields on the frontend.

strapi_adityacprtm_dev.jpg

This blog is part of Building my personal portfolio with Vue.js, Strapi and MongoDB series

Here I share how to customize the response from the API, by default the responses given include id, _id, __v, createdAt, updatedAt, published_at. But there are times when I don't use these fields on the frontend.

Hides the Default Response Fields

To hide unused fields, in this case _id, __v, createdAt, updatedAt, published_at, simply change the values as shown below:

Path - api -> <apiName> -> <apiName>.settings.json

{
  ...
  ""options"": {
    ""increments"": true,
    ""timestamps"": true,
    ""draftAndPublish"": false,
    ""privateAttributes"": [
      ""_id"",
      ""createdAt"",
      ""updatedAt"",
      ""__v""
    ]
  },
  ...
}

Manipulating Response Data

If you want to manipulate API response data, you can do this in the controllers section of each API. For example I want to accept the number of blogs associated with series when making a find series request to the API.

Path - . / Api / series / controller / Series.js

const { sanitizeEntity } = require(""strapi-utils"");

module.exports = {
  // Find
  async find(ctx) {
    let entities;
    if (ctx.query._q) {
      entities = await strapi.services.serie.search(ctx.query);
    } else {
      entities = await strapi.services.serie.find(ctx.query);
    }

    return entities.map((entity) => {
      const serie = sanitizeEntity(entity, {
        model: strapi.models.serie,
      });

      if (serie.blogs) {
        serie.countBlogs = serie.blogs.length;
      }

      return serie;
    });
  }
};

That's it, a little way of customizing the API response data.

0 Comments