AdviceWeb Development

Automate the Creation of Your Collections with Directus

Directus is a headless CMS that allows you to create data models composed of fields of your choice. The interface is excellent and allows you to do almost everything you could do with a traditional framework.
But what if you want to create your Collections and fields programmatically to save time? Here is our method for creating your Collections via the Directus API.

Collections and Fields

Collections in Directus are organized groups of similar content items, comparable to tables in a database. They allow for the coherent and flexible structuring and management of data.

Each collection is composed of several fields, which are individual fields precisely defining the specific attributes or properties of each entry (text, date, number, file, relation, etc.). These fields are configurable and ensure the uniform and structured entry of information in Directus.

Directus interface showing the automatic creation of collections with custom fields.

These fields can be easily created via the interface, but when you want to create numerous collections each with dozens of fields, the programmatic approach becomes the most efficient.

Collection Structure

Indeed, Directus offers an API that allows you to create Collections without using the interface. Let's imagine we want to create two collections posts and events. We will start with a JSON:

[
  {
    "name": "posts",
    "displayName": "Posts",
    "icon": "article",
    "singleton": false
  },
  {
    "name": "events",
    "displayName": "Events",
    "icon": "event",
    "singleton": false
  }
]

This JSON specifies the name of the collection, its icon, and that the collection hosts multiple objects.

Create the Collection via the API

Some technical prerequisites to create your collections:

  • Node.js installed
  • .env file properly configured with DIRECTUS_URL and DIRECTUS_TOKEN
  • data folder containing collections.json

Interested in Switching to Directus?

We assist you in getting started on the right foot with this Headless CMS and saving time in its use.

Schedule an appointment

Script for automating the creation of collections in Directus.

Here is our script that will allow you to create your collections:

Note that in this script, I am directly using the API without using the Directus SDK. This choice is intentional because the SDK changes depending on the versions and the documentation is sometimes not up to date. By directly using the API with a standard request, we avoid these version changes, and the script will continue to work even as the SDK evolves.

require('dotenv').config();
const axios = require('axios');
const fs = require('fs');
const path = require('path');
 
function createApiClient(directusUrl, token) {
  return axios.create({
    baseURL: directusUrl,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    }
  });
}
 
function loadJsonData(filePath) {
  return JSON.parse(fs.readFileSync(filePath, 'utf8'));
}
 
async function createCollection(api, collection) {
  return api.post('/collections', {
    collection: collection.name,
    meta: {
      icon: collection.icon,
      display_template: '{{name}}',
      hidden: false,
      singleton: collection.singleton,
      translations: [{ language: 'fr-FR', translation: collection.displayName }]
    },
    schema: { name: collection.name }
  });
}
 
async function run() {
  const directusUrl = process.env.DIRECTUS_URL;
  const token = process.env.DIRECTUS_TOKEN;
  if (!token) {
    console.error('ERROR: DIRECTUS_TOKEN must be set in your .env file');
    process.exit(1);
  }
 
  const api = createApiClient(directusUrl, token);
  const collectionsPath = path.join(__dirname, 'data', 'collections.json');
  const collections = loadJsonData(collectionsPath);
 
  for (const collection of collections) {
    try {
      const response = await createCollection(api, collection);
      console.log(`Created collection: ${collection.name}`);
    } catch (error) {
      console.error(`Failed to create collection ${collection.name}:`, error.message);
    }
  }
}
 
run();

You can also add fields when creating Collections with the fields key.

This approach will allow you to create all your collections in no time, and you are free to go back through the interface to adjust your collections if needed.

Error Management and Logging

When running the script, it is essential to plan for clear error management to quickly identify any potential issues. Be sure to check the logs displayed in your terminal, as they contain valuable information for diagnosing any anomalies encountered during the creation of collections. This way, you can effectively intervene in case of unexpected issues.

By automating the creation of your collections using the Directus API, you optimize your workflow, simplify data management, and significantly increase productivity. You now have a reliable, scalable solution tailored to the needs of your future projects.

Ready to get started?

From scoping to prototype, to AI integration.

We support your business software projects from start to finish.

Develop my project
Automate the Creation of Your Collections with Directus