DEV Community

Cover image for Generate Dummy Data in Strapi
Andrii Shupta
Andrii Shupta

Posted on • Updated on • Originally published at blog.andriishupta.dev

Generate Dummy Data in Strapi

🔗 Links

📰 Also published on

🤓 Motivation

Strapi is powerful open-source headless CMS that helps projects control code customization with extensibility and, at the same time, don't worry about implementing a full-blown Content Management System on their own.

So, after you have set up your Strapi, you want to build Front-End on top of it. You hire front-end developers who are stuck: "Ye, I can query for data via REST and GraphQL, but what data should I see? Could I have an example?"

😬

To avoid this, we would generate example data upfront.

🌱 How to seed data?

"Generate dummy data"

There is the video in Strapi's Video-library that gave me a direction on how to do it.

The idea is simple:

Tip

Your case 💯 would be more complicated, so don't forget that you could take almost everything from Strapi's source code.

The flow:

  • find a place on Strapi Admin you want to copy
  • check URL and Network(in developer's inspection) to understand what is called
  • find code(start with controller) that corresponds to that calls
  • enjoy

🧑‍💻 Code

We have a simple Todo application(duh) with a Todo collection and a Todo List as a page(single type) that we want to send to the front-end. Also, our Todos has media functionality, so we upload some.

In the bootstrap function, we check for the development environment and decide if we should run seeding or not. Seeding would automatically run on the very first application run(valid when a developer clones an existing repository) and could be re-run with yarn seed to force seed, which clears old and creates new data - FORCE_APP_BOOTSTRAP_ONLY.

🔗source code

image.png

Collection Type

To create a todo using Entity Service API, we need to call the create method with data that matches our entity. In the current example and during seeding, I have used "bulk promises" to run requests in parallel cause they are not dependent on each other.

🔗 source code

image.png

And using faker, we fill a todo like this:

image.png

Single Type

Fulfilling the "Todo List page" is the same as Collection, but keep in mind that it could be only one entry all the time. Also, it contains a Todo relation, so we get five todos to fill it.

🔗 source code

image.png

Media Upload

To attach media on a todo, we first need to upload that media and then link its id to the entity. Code has been copied from Strapi's source code, modified, and I just created a helper function.

🔗 source code

image.png

Example in Todo:
image.png

✅ Results

After opening the Admin panel, you will see generated data.

image.png

image.png

Initially, I implemented this for Developer DAO's website developerdao.com. Original code is located here(archived and moved to monorepo).

Thanks for reading!

Top comments (0)