Importing data into the Contentful headless CMS

Importing data into the Contentful headless CMS

28 Aug 2021 contentful headless javascript

TL;DR: Importing into Contentful isn't straightforward. Instead, you might want to try my cfimp tool.

Headless CMS's are increasingly used these days. Contentful is one such CMS. It comes with an attractive free package, and has thus proved popular. One problem, though, is that it lacks any decent means to import data.

The problem 🔗

There's no GUI for importing data on their website, and instead you have to use the import functionality that comes bundled with the contentful-cli packge.

There's two problems with that. First, you have to munge your data, which is probably coming out of a spreadsheet, into JSON somehow. Second, the docs on this feature are really sparse; they don't make explicit precisely what that JSON structure should be.

Instead, you're supposed to run an export (via the same package), inspect the generated JSON structure, and derive your import data from that. But that's horrible; you obviously have to strip out all the data/fields that relate to extant data, as opposed to data you want to create.

Contentful say they used to have a simple GUI on their site for importing data, but that they discontinued it because it didn't work well for all models. I'm not sure I understand that; all that's needed is a way to assign values to fields, and that's what this CLI import tool does, after all.

The solution 🔗

Anyway, I decided I wasn't going to mess about munging data into JSON each time I wanted to import data, so I created cfimp. It's a CLI-based tool that acts as an intermediary between you and contentful-cli, and allows you to import spreadsheet-derived, separated-variable data into Contentful, and comes with a host of options.

You can also use it to update existing items, or link items to tags, assets or foreign items.

A simple example looks like:

npx cfimp -space-id:12345 -model:67890 -locale:en-GB -input:data.csv

Check the project page for full usage/examples.

The contentful-cli way 🔗

If you don't want to use my tool and would rather use contentful-cli natively, you'll need to know the JSON structure. This largely depends on whether you're importing entries (content), schema (models), tags or whatever. (cfimp is used only with content, nothing else.)

But if you want to just import entries, the structure looks like this:

{ "entries": [{ "sys": { "contentType": { "sys": { "type": "Link", "linkType": "ContentType", "id": "<contentTypeId>" } } }, "fields": { "<field1Name>": { "<locale>": "<value>" } } }] }

You can run that via:

contentful import --space-id 12345 --content-file mydata.json

It looks a little different if you want to link to references or tags, so do an export to see what that looks like. Or just use cfimp!

Did I help you? Feel free to be amazing and buy me a coffee on Ko-fi!