🛠️ How to populate creator fields such as createdBy
and updatedBy
The creator fields createdBy
and updatedBy
are removed from the REST API response by default. These 2 fields can be returned in the REST API by activating the populateCreatorFields
parameter at the content-type level.
note
The populateCreatorFields
property is not available to the GraphQL API.
Only the following fields will be populated: id
, firstname
, lastname
, username
, preferedLanguage
, createdAt
, and updatedAt
.
To add createdBy
and updatedBy
to the API response:
- Open the content-type
schema.json
file. - Add
"populateCreatorFields": true
to theoptions
object:
"options": {
"draftAndPublish": true,
"populateCreatorFields": true
},
- Save the
schema.json
. - Create a new route middleware either using the generate CLI or by manually creating a new file in
./src/api/[content-type-name]/middlewares/[your-middleware-name].js
- Add the following piece of code, you can modify this example to suit your needs:
./src/api/test/middlewares/defaultTestPopulate.js
"use strict";
module.exports = (config, { strapi }) {
return async (ctx, next) {
if (!ctx.query.populate) {
ctx.query.populate = ["createdBy", "updatedBy"];
}
await next();
};
};
- Modify your default route factory to enable this middleware on the specific routes you want this population to apply to and replacing the content-type/middleware name with yours:
./src/api/test/routes/test.js
"use strict";
const { createCoreRouter } = require("@strapi/strapi").factories;
module.exports = createCoreRouter("api::test.test", {
config: {
find: {
middlewares: ["api::test.default-test-populate"],
},
findOne: {
middlewares: ["api::test.default-test-populate"],
},
},
});
REST API requests with no populate
parameter will include the createdBy
or updatedBy
fields by default.