Create a new record
Before creating your first record, we strongly recommend reading the Introduction to Records guide. It covers fundamental concepts about field types, block manipulation, and localization that are essential for building a valid creation payload.
The payload required to create a new record is determined by the specific model it's based on and the fields it contains.
This example demonstrates the basic process of creating a new record using the DatoCMS Content Management API. The example shows how to specify the item type and provide values for the record's fields.
import { buildClient, inspectItem, type ItemTypeDefinition,} from "@datocms/cma-client-node";
type EnvironmentSettings = { locales: "en" };
// 👇 Definitions can be generated automatically using CLI: https://www.datocms.com/cma-ts-schema
type Book = ItemTypeDefinition< EnvironmentSettings, "UZyfjdBES8y2W2ruMEHSoA", { title: { type: "string" }; genre: { type: "string" }; synopsis: { type: "text" }; pages: { type: "integer" }; }>;
async function run() { // Make sure the API token has access to the CMA, and is stored securely const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN });
const record = await client.items.create<Book>({ item_type: { type: "item_type", id: "UZyfjdBES8y2W2ruMEHSoA" }, title: "The JavaScript Guide", genre: "Programming", synopsis: "A comprehensive guide to modern JavaScript.\nPerfect for beginners and experts alike.", pages: 450, });
console.log(inspectItem(record));}
run();
└ Item "E3eHzSH6QSGbTDmlKlSusw" (item_type: "UZyfjdBES8y2W2ruMEHSoA") ├ title: "The JavaScript Guide" ├ genre: "Programming" ├ synopsis: "A comprehensive guide to modern JavaScript.\nPerfect for beginners and experts..." └ pages: 450
When creating a record, you don't need to specify a value for every field. Any field you omit will be set to its configured default value, or null
if no default is set.
While the Introduction to Records guide offers a complete reference for every field type, there are several key rules that are especially important when creating a new record.
Field value formatting
Every field in your payload must be formatted according to its type. This can range from a simple string or number to a structured object. For a comprehensive breakdown of the expected format for every field type, please refer to the Field Types Overview in our main records guide.
This example demonstrates how to create records with various simple field types, including text, numbers, dates, booleans, and more complex types like geo-location and color fields.
Key considerations when working with different field types:
- Geo-location fields: Provide latitude and longitude as an object with both properties
- Color fields: Specify RGBA values as an object with red, green, blue, and alpha components
- JSON fields: Must be provided as a JSON-serialized string, not a JavaScript object
- Date/time fields: Use ISO 8601 format strings for precise timestamps
For complete details on field value formats, see the Field types overview section.
import { buildClient, inspectItem, type ItemTypeDefinition,} from "@datocms/cma-client-node";
type EnvironmentSettings = { locales: "en" };
// 👇 Definitions can be generated automatically using CLI: https://www.datocms.com/cma-ts-schema
type Product = ItemTypeDefinition< EnvironmentSettings, "UZyfjdBES8y2W2ruMEHSoA", { name: { type: "string" }; category: { type: "string" }; description: { type: "text" }; price: { type: "integer" }; weight: { type: "float" }; release_date: { type: "date_time" }; in_stock: { type: "boolean" }; warehouse_location: { type: "lat_lon" }; brand_color: { type: "color" }; specifications: { type: "json" }; }>;
async function run() { // Make sure the API token has access to the CMA, and is stored securely const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN });
const record = await client.items.create<Product>({ item_type: { type: "item_type", id: "UZyfjdBES8y2W2ruMEHSoA" }, name: "Premium Wireless Headphones", category: "Electronics", description: "High-quality noise-cancelling wireless headphones.\nPerfect for music and calls.", price: 299, weight: 0.25, release_date: "2024-03-15T10:30:00", in_stock: true, warehouse_location: { latitude: 45.0703393, longitude: 7.686864, }, brand_color: { alpha: 255, blue: 156, green: 208, red: 239, }, specifications: JSON.stringify({ bluetooth: "5.0", battery_life: "30h", warranty: "2y", }), });
console.log(inspectItem(record));}
run();
└ Item "NZwcu3wYSgWeAbqVCJVToQ" (item_type: "UZyfjdBES8y2W2ruMEHSoA") ├ name: "Premium Wireless Headphones" ├ category: "Electronics" ├ description: "High-quality noise-cancelling wireless headphones.\nPerfect for music and calls." ├ price: 299 ├ weight: 0.25 ├ release_date: 2024-03-15T10:30:00+00:00 ├ in_stock: true ├ warehouse_location │ ├ latitude: 45.0703393 │ └ longitude: 7.686864 ├ brand_color: #EFD09C └ specifications: {"bluetooth":"5.0","battery_life":"30h","warranty":"2y"}
Block Fields
When creating a record, any new blocks (for Modular Content, Single Block, or Structured Text fields) must be provided as full block objects. This object must include the item_type
in its relationships
to specify which Block Model to use. For a deeper dive into manipulating blocks, see the guide on Creating and Updating Blocks.
This example shows how to create records with modular content fields, which allow you to compose rich, dynamic content by combining multiple blocks of different types. Each block can have its own set of fields and can be repeated as needed.
The example uses the buildBlockRecord()
helper function to create blocks more easily. You specify the block model ID and provide values for all the block's fields, similar to creating a regular record:
import { buildBlockRecord, buildClient, inspectItem, type ItemTypeDefinition,} from "@datocms/cma-client-node";
type EnvironmentSettings = { locales: "en" };
/* * LandingPage * ├─ title: string * └─ sections: rich_text * ├─ HeroBlock: headline, subtitle, background_image * └─ TestimonialBlock: quote, author_name */
// 👇 Definitions can be generated automatically using CLI: https://www.datocms.com/cma-ts-schema
type LandingPage = ItemTypeDefinition< EnvironmentSettings, "UZyfjdBES8y2W2ruMEHSoA", { title: { type: "string" }; sections: { type: "rich_text"; blocks: HeroBlock | TestimonialBlock; }; }>;
type HeroBlock = ItemTypeDefinition< EnvironmentSettings, "T4m4tPymSACFzsqbZS65WA", { headline: { type: "string" }; subtitle: { type: "text" }; background_image: { type: "file" }; }>;
type TestimonialBlock = ItemTypeDefinition< EnvironmentSettings, "JItInCQJSIeCLX3oGPvN1w", { quote: { type: "text" }; author_name: { type: "string" }; }>;
async function run() { // Make sure the API token has access to the CMA, and is stored securely const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN });
// Create asset by using a local file: const upload = await client.uploads.createFromLocalFile({ localPath: "./2018-10-17-194326.jpg", });
const record = await client.items.create<LandingPage>({ item_type: { type: "item_type", id: "UZyfjdBES8y2W2ruMEHSoA" }, title: "Product Launch Landing Page", sections: [ // hero block buildBlockRecord<HeroBlock>({ item_type: { type: "item_type", id: "T4m4tPymSACFzsqbZS65WA" }, headline: "Revolutionary New Product", subtitle: "Transform your workflow with our cutting-edge solution.\nBuilt for modern teams.", background_image: { upload_id: upload.id }, }), // testimonial block buildBlockRecord<TestimonialBlock>({ item_type: { type: "item_type", id: "JItInCQJSIeCLX3oGPvN1w" }, quote: "This product completely transformed our business operations.", author_name: "Sarah Johnson, CEO", }), ], });
console.log("-- Regular mode --"); console.log(inspectItem(record));
console.log("-- Nested mode --"); const nestedRecord = await client.items.find(record, { nested: true }); console.log(inspectItem(nestedRecord));}
run();
-- Regular mode --└ Item "Qw3wP3n8Qf286PjYiYzgXw" (item_type: "UZyfjdBES8y2W2ruMEHSoA") ├ title: "Product Launch Landing Page" └ sections ├ [0]: "XhYlJCL5Rv-2UN2kRXnPcA" └ [1]: "S3hGBEOXTyKfOs6ac4o37Q"
-- Nested mode --└ Item "Qw3wP3n8Qf286PjYiYzgXw" (item_type: "UZyfjdBES8y2W2ruMEHSoA") ├ title: "Product Launch Landing Page" └ sections ├ [0] Item "XhYlJCL5Rv-2UN2kRXnPcA" (item_type: "T4m4tPymSACFzsqbZS65WA") │ ├ headline: "Revolutionary New Product" │ ├ subtitle: "Transform your workflow with our cutting-edge solution.\nBuilt for modern teams." │ └ background_image │ └ upload_id: "VUkBZ214TnK1UeHbJuoAmw" └ [1] Item "S3hGBEOXTyKfOs6ac4o37Q" (item_type: "JItInCQJSIeCLX3oGPvN1w") ├ quote: "This product completely transformed our business operations." └ author_name: "Sarah Johnson, CEO"
This example shows how to create records with single block fields, which allow you to add exactly one block to a field. Unlike modular content fields that can contain multiple blocks, single block fields hold either a single block instance or null
.
The example uses the buildBlockRecord()
helper function to create the block. You specify the block model ID and provide values for all the block's fields, similar to creating a regular record:
import { buildBlockRecord, buildClient, inspectItem, type ItemTypeDefinition,} from "@datocms/cma-client-node";
type EnvironmentSettings = { locales: "en" };
/* * ProductPage * ├─ title: string * ├─ price: float * └─ hero_section: single_block * └─ HeroBlock * ├─ headline: string * ├─ description: text * ├─ button: single_block * │ └─ ButtonBlock * │ ├─ text: string * │ └─ url: string * └─ background_image: file */
// 👇 Definitions can be generated automatically using CLI: https://www.datocms.com/cma-ts-schema
type ProductPage = ItemTypeDefinition< EnvironmentSettings, "UZyfjdBES8y2W2ruMEHSoA", { title: { type: "string" }; price: { type: "float" }; hero_section: { type: "single_block"; blocks: HeroBlock; }; }>;
type HeroBlock = ItemTypeDefinition< EnvironmentSettings, "T4m4tPymSACFzsqbZS65WA", { headline: { type: "string" }; description: { type: "text" }; button: { type: "single_block"; blocks: ButtonBlock }; background_image: { type: "file" }; }>;
type ButtonBlock = ItemTypeDefinition< EnvironmentSettings, "d-CHYg-rShOt3kiL6ZN1yA", { text: { type: "string" }; url: { type: "string" }; }>;
async function run() { // Make sure the API token has access to the CMA, and is stored securely const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN });
// Create asset by using a local file: const upload = await client.uploads.createFromLocalFile({ localPath: "./hero-background.jpg", });
const record = await client.items.create<ProductPage>({ item_type: { type: "item_type", id: "UZyfjdBES8y2W2ruMEHSoA" }, title: "Premium Wireless Headphones", price: 299.99, hero_section: buildBlockRecord<HeroBlock>({ item_type: { type: "item_type", id: "T4m4tPymSACFzsqbZS65WA" }, headline: "Experience Audio Excellence", description: "Immerse yourself in crystal-clear sound with our premium wireless headphones.\nFeatures noise cancellation and 30-hour battery life.", button: buildBlockRecord<ButtonBlock>({ item_type: { type: "item_type", id: "d-CHYg-rShOt3kiL6ZN1yA" }, text: "Learn more", url: "/details", }), background_image: { upload_id: upload.id }, }), });
console.log("-- Regular mode --"); console.log(inspectItem(record));
console.log("-- Nested mode --"); const nestedRecord = await client.items.find(record, { nested: true }); console.log(inspectItem(nestedRecord));}
run();
-- Regular mode --└ Item "M54UhYRfQsSz62F1lTMHig" (item_type: "UZyfjdBES8y2W2ruMEHSoA") ├ title: "Premium Wireless Headphones" ├ price: 299.99 └ hero_section: "R9Gt9gafTyaRSa8IFwWJEw"
-- Nested mode --└ Item "M54UhYRfQsSz62F1lTMHig" (item_type: "UZyfjdBES8y2W2ruMEHSoA") ├ title: "Premium Wireless Headphones" ├ price: 299.99 └ hero_section └ Item "R9Gt9gafTyaRSa8IFwWJEw" (item_type: "T4m4tPymSACFzsqbZS65WA") ├ headline: "Experience Audio Excellence" ├ description: "Immerse yourself in crystal-clear sound with our premium wireless headphones...." ├ button │ └ Item "aSFe8RhtThyajM5W3DEUPQ" (item_type: "d-CHYg-rShOt3kiL6ZN1yA") │ ├ text: "Learn more" │ └ url: "/details" └ background_image └ upload_id: "JP0pXTl3S0SFP42PYK2Mug"
This example demonstrates how to create records with structured text fields that combine rich formatted text with embedded blocks. Structured text is perfect for editorial content where you need to mix paragraphs, headings, and interactive elements seamlessly.
The buildBlockRecord()
helper function simplifies creating embedded blocks, and the example shows how to create upload resources for media content. For more upload creation methods, see the Create a new upload endpoint documentation.
import { buildBlockRecord, buildClient, inspectItem, type ItemTypeDefinition,} from "@datocms/cma-client-node";
type EnvironmentSettings = { locales: "en" };
/* * Article * ├─ title: string * └─ content: structured_text * ├─ CtaBlock: title, description, button_text, button_url * └─ ImageGalleryBlock: title, images */
// 👇 Definitions can be generated automatically using CLI: https://www.datocms.com/cma-ts-schema
type Article = ItemTypeDefinition< EnvironmentSettings, "UZyfjdBES8y2W2ruMEHSoA", { title: { type: "string" }; content: { type: "structured_text"; blocks: CtaBlock | ImageGalleryBlock; }; }>;
type CtaBlock = ItemTypeDefinition< EnvironmentSettings, "T4m4tPymSACFzsqbZS65WA", { title: { type: "string" }; description: { type: "text" }; button_text: { type: "string" }; button_url: { type: "string" }; }>;
type ImageGalleryBlock = ItemTypeDefinition< EnvironmentSettings, "cSxBMd9XRWGGvq6xQ0qYDg", { title: { type: "string" }; images: { type: "gallery" }; }>;
async function run() { // Make sure the API token has access to the CMA, and is stored securely const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN });
// Create upload resources from URLs (or return existing uploads if already present in the media area): const upload1 = await client.uploads.createFromUrl({ url: "https://picsum.photos/800/600?random=1", skipCreationIfAlreadyExists: true, });
const upload2 = await client.uploads.createFromUrl({ url: "https://picsum.photos/800/600?random=2", skipCreationIfAlreadyExists: true, });
const record = await client.items.create<Article>({ item_type: { type: "item_type", id: "UZyfjdBES8y2W2ruMEHSoA" }, title: "The Future of Web Development", content: { schema: "dast", document: { type: "root", children: [ // article introduction { type: "paragraph", children: [ { type: "span", marks: [], value: "Web development is rapidly evolving, and new technologies are reshaping how we build digital experiences. In this article, we'll explore the latest trends and tools that are defining the future.", }, ], }, // heading { type: "heading", level: 2, children: [ { type: "span", marks: [], value: "Key Technologies to Watch", }, ], }, // paragraph with formatting { type: "paragraph", children: [ { type: "span", marks: [], value: "From ", }, { type: "span", marks: ["strong"], value: "serverless architectures", }, { type: "span", marks: [], value: " to ", }, { type: "span", marks: ["emphasis"], value: "edge computing", }, { type: "span", marks: [], value: ", developers now have unprecedented tools for building scalable applications.", }, ], }, // image gallery block { type: "block", item: buildBlockRecord<ImageGalleryBlock>({ item_type: { type: "item_type", id: "cSxBMd9XRWGGvq6xQ0qYDg" }, title: "Modern Development Environments", images: [ { upload_id: upload1.id, alt: "Modern IDE setup", title: "Development Environment", }, { upload_id: upload2.id, alt: "Code collaboration tools", title: "Team Collaboration", }, ], }), }, // another paragraph { type: "paragraph", children: [ { type: "span", marks: [], value: "As we look ahead, the integration of AI-powered tools and improved developer experiences will continue to accelerate innovation in our field.", }, ], }, // call-to-action block { type: "block", item: buildBlockRecord<CtaBlock>({ item_type: { type: "item_type", id: "T4m4tPymSACFzsqbZS65WA" }, title: "Ready to Level Up Your Skills?", description: "Join our community of forward-thinking developers and stay ahead of the curve with cutting-edge tutorials, tools, and insights.", button_text: "Join the Community", button_url: "https://example.com/join", }), }, ], }, }, });
console.log("-- Regular mode --"); console.log(inspectItem(record));
console.log("-- Nested mode --"); const nestedRecord = await client.items.find(record, { nested: true }); console.log(inspectItem(nestedRecord));}
run();
-- Regular mode --└ Item "F50TH6XjSiqyMfezCmra0w" (item_type: "UZyfjdBES8y2W2ruMEHSoA") ├ title: "The Future of Web Development" └ content ├ paragraph │ └ span "Web development is rapidly evolving, and new technologies are reshapi..." ├ heading (level: 2) │ └ span "Key Technologies to Watch" ├ paragraph │ ├ span "From " │ ├ span (marks: strong) "serverless architectures" │ ├ span " to " │ ├ span (marks: emphasis) "edge computing" │ └ span ", developers now have unprecedented tools for building scalable appli..." ├ block "WWVn5YmfRfmwWr9rANi_Gg" ├ paragraph │ └ span "As we look ahead, the integration of AI-powered tools and improved de..." └ block "aciFN9_oRvWNjy7XIcm-9A"
-- Nested mode --└ Item "F50TH6XjSiqyMfezCmra0w" (item_type: "UZyfjdBES8y2W2ruMEHSoA") ├ title: "The Future of Web Development" └ content ├ paragraph │ └ span "Web development is rapidly evolving, and new technologies are reshapi..." ├ heading (level: 2) │ └ span "Key Technologies to Watch" ├ paragraph │ ├ span "From " │ ├ span (marks: strong) "serverless architectures" │ ├ span " to " │ ├ span (marks: emphasis) "edge computing" │ └ span ", developers now have unprecedented tools for building scalable appli..." ├ block │ └ Item "WWVn5YmfRfmwWr9rANi_Gg" (item_type: "cSxBMd9XRWGGvq6xQ0qYDg") │ ├ title: "Modern Development Environments" │ └ images │ ├ [0] │ │ ├ upload_id: "LkyN_T-oTq-o0RGt9EDUMQ" │ │ ├ alt: "Modern IDE setup" │ │ └ title: "Development Environment" │ └ [1] │ ├ upload_id: "YptkFcGyRXi3QOTUymmm2A" │ ├ alt: "Code collaboration tools" │ └ title: "Team Collaboration" ├ paragraph │ └ span "As we look ahead, the integration of AI-powered tools and improved de..." └ block └ Item "aciFN9_oRvWNjy7XIcm-9A" (item_type: "T4m4tPymSACFzsqbZS65WA") ├ title: "Ready to Level Up Your Skills?" ├ description: "Join our community of forward-thinking developers and stay ahead of the curve..." ├ button_text: "Join the Community" └ button_url: "https://example.com/join"
Asset & Link Fields
These reference fields require specific formats. For a comprehensive breakdown of the expected format for every field type, please refer to the Field Types Overview in our main records guide.
This example shows how to create records that include image or file assets. You can work with both single assets and asset galleries by referencing existing uploads or creating new ones.
The example demonstrates two approaches:
- Single asset field: Reference an upload with optional metadata overrides
- Asset gallery field: Create arrays of asset objects with custom properties like alt text, title, focal points, and custom data
You can create new uploads from URLs using client.uploads.createFromUrl()
or reference existing uploads from your media library. For more upload creation methods, see the Create a new upload endpoint documentation.
import { buildClient, inspectItem, type ItemTypeDefinition,} from "@datocms/cma-client-node";
type EnvironmentSettings = { locales: "en" };
// 👇 Definitions can be generated automatically using CLI: https://www.datocms.com/cma-ts-schema
type Portfolio = ItemTypeDefinition< EnvironmentSettings, "UZyfjdBES8y2W2ruMEHSoA", { title: { type: "string" }; featured_image: { type: "file" }; gallery: { type: "gallery" }; }>;
async function run() { // Make sure the API token has access to the CMA, and is stored securely const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN });
// create upload resource using URL (or return an existing upload if it's already present in the media area): const upload1 = await client.uploads.createFromUrl({ url: "https://picsum.photos/800/600?random=3", skipCreationIfAlreadyExists: true, });
// create upload resource using local file (or return an existing upload if it's already present in the media area): const upload2 = await client.uploads.createFromLocalFile({ localPath: "./local.jpg", skipCreationIfAlreadyExists: true, });
const record = await client.items.create<Portfolio>({ item_type: { type: "item_type", id: "UZyfjdBES8y2W2ruMEHSoA" }, title: "Architecture Photography", featured_image: { // in this case we're just passing the upload ID, as the // upload resource's defaults for alt, title, etc. are fine: upload_id: upload1.id, }, gallery: [ // here we want to override the upload resource's defaults: { upload_id: upload2.id, alt: "Modern architecture", title: "Urban Design", focal_point: { x: 0.3, y: 0.2, }, custom_data: { add_watermark: true, }, }, ], });
console.log(inspectItem(record));}
run();
└ Item "LXN7jVhLTKaui_1dD9gLXA" (item_type: "UZyfjdBES8y2W2ruMEHSoA") ├ title: "Architecture Photography" ├ featured_image │ └ upload_id: "HWhE3MhgTxCfqRfIMGW7Jg" └ gallery └ [0] ├ upload_id: "KJQT9BgrRjKJPALM9fsXgA" ├ alt: "Modern architecture" ├ title: "Urban Design" ├ custom_data: {"add_watermark":true} └ focal_point: x=30% y=20%
This example shows how to create records that reference other existing records through link fields. The process involves first retrieving the records you want to link to, then referencing them by their IDs when creating the new record.
Link fields can be either single links (referencing one record) or multiple links (referencing an array of records). The example demonstrates both scenarios and shows how to query for existing records before creating the relationships.
import { buildClient, inspectItem, type ItemTypeDefinition,} from "@datocms/cma-client-node";
type EnvironmentSettings = { locales: "en" };
// 👇 Definitions can be generated automatically using CLI: https://www.datocms.com/cma-ts-schema
type Author = ItemTypeDefinition< EnvironmentSettings, "UZyfjdBES8y2W2ruMEHSoA", { name: { type: "string" }; collaborators: { type: "links" }; mentor: { type: "link" }; }>;
async function run() { // Make sure the API token has access to the CMA, and is stored securely const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN });
// Let's retrieve some other authors first const otherAuthors = await client.items.list({ filter: { type: "author" }, version: "current", });
if (otherAuthors.length === 0) { throw new Error("This example expects at least one record!"); }
const record = await client.items.create<Author>({ item_type: { type: "item_type", id: "UZyfjdBES8y2W2ruMEHSoA" }, name: "Sarah Johnson", collaborators: otherAuthors.map((author) => author.id), mentor: otherAuthors[0]!.id, });
console.log(inspectItem(record));}
run();
└ Item "Eukon4pbSrGyuYPWbmDiPQ" (item_type: "UZyfjdBES8y2W2ruMEHSoA") ├ name: "Sarah Johnson" ├ collaborators │ ├ [0]: "EF-CHNzIRAeFbt2ACY-K2Q" │ ├ [1]: "MeYQG9_HTEi0ZwhQi7kffA" │ └ [2]: "fHgaJ1AaTZm-U6hFdEthgw" └ mentor: "EF-CHNzIRAeFbt2ACY-K2Q"
Localization
If the record's model contains localized fields, your creation payload must adhere to specific rules:
- All localized fields in a single payload must specify the same set of locales to ensure consistency.
- If the model is configured to require all locales (
all_locales_required
), then the payload must include a key for every available locale for each localized field. The value of a field for a locale can benull
, but the key itself is mandatory.
For a full explanation of how to structure localized data, refer to the localization Guide.
The code shows two scenarios:
- Providing content for a subset of available locales (
en
,it
) with consistent locale keys across all localized fields - Including all available locales (
en
,it
,fr
) even when some translations arenull
import { buildClient, inspectItem, type ItemTypeDefinition,} from "@datocms/cma-client-node";
type EnvironmentSettings = { locales: "en" | "it" | "fr" };
// 👇 Definitions can be generated automatically using CLI: https://www.datocms.com/cma-ts-schema
type Pet = ItemTypeDefinition< EnvironmentSettings, "UZyfjdBES8y2W2ruMEHSoA", { name: { type: "string"; localized: true }; description: { type: "string"; localized: true }; category: { type: "string"; localized: false }; }>;
async function run() { // Make sure the API token has access to the CMA, and is stored securely const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN });
// Example 1: Basic localization - consistent locales across all localized fields const basicRecord = await client.items.create<Pet>({ item_type: { type: "item_type", id: "UZyfjdBES8y2W2ruMEHSoA" }, name: { en: "Sir Fluffington McWhiskers", it: "Signor Pelosetto Baffetti", }, description: { en: "A noble cat with an impeccable mustache.", it: "Un gatto nobile con baffi impeccabili.", }, // Non-localized field - single value for all locales category: "indoor", });
console.log("-- Basic record --"); console.log(inspectItem(basicRecord));
// Example 2: When all_locales_required is true - must include all locales // even if some values are null const allLocalesRecord = await client.items.create<Pet>({ item_type: { type: "item_type", id: "UZyfjdBES8y2W2ruMEHSoA" }, name: { en: "Luna", it: "Luna", fr: null, // Translation not ready yet, but key is required }, description: { en: "A mysterious black cat that appears at midnight.", it: "Un gatto nero misterioso che appare a mezzanotte.", fr: null, // Translation not ready yet, but key is required }, category: "outdoor", });
console.log("-- All locales record --"); console.log(inspectItem(allLocalesRecord));}
run();
-- Basic record --└ Item "PHz_ILZNR7uJ-r4PQsHEqg" (item_type: "UZyfjdBES8y2W2ruMEHSoA") ├ name │ ├ en: "Sir Fluffington McWhiskers" │ └ it: "Signor Pelosetto Baffetti" ├ description │ ├ en: "A noble cat with an impeccable mustache." │ └ it: "Un gatto nobile con baffi impeccabili." └ category: "indoor"
-- All locales record --└ Item "OBvZ6gKbTOSGY7NGB_9fqA" (item_type: "UZyfjdBES8y2W2ruMEHSoA") ├ name │ ├ en: "Luna" │ ├ fr: "" │ └ it: "Luna" ├ description │ ├ en: "A mysterious black cat that appears at midnight." │ ├ fr: "" │ └ it: "Un gatto nero misterioso che appare a mezzanotte." └ category: "outdoor"
Body parameters
RFC 4122 UUID of record expressed in URL-safe base64 format
"hWl-mnkWRYmMCSTq4z_piQ"
Date of creation
Date of first publication
The entity (account/collaborator/access token/sso user) who created the record
Returns
Returns a resource object of type item
Other examples
This example demonstrates how to create records in tree-structured collections, where records can form hierarchical relationships with parent-child connections. Tree structures are useful for navigation menus, category hierarchies, organizational charts, and any content that needs nested organization.
When creating records in tree-like collections, you can specify:
parent_id
: Links the record to its parent in the hierarchyposition
: Sets the ordering among sibling records
The example shows how to build a hierarchy by creating records that reference each other:
import { buildClient, inspectItem, type ItemTypeDefinition,} from "@datocms/cma-client-node";
type EnvironmentSettings = { locales: "en" };
// 👇 Definitions can be generated automatically using CLI: https://www.datocms.com/cma-ts-schema
type Category = ItemTypeDefinition< EnvironmentSettings, "UZyfjdBES8y2W2ruMEHSoA", { name: { type: "string" }; parent_id: { type: "string" }; position: { type: "integer" }; }>;
async function run() { // Make sure the API token has access to the CMA, and is stored securely const client = buildClient({ apiToken: process.env.DATOCMS_API_TOKEN });
const parent = await client.items.create<Category>({ item_type: { type: "item_type", id: "UZyfjdBES8y2W2ruMEHSoA" }, name: "Parent", });
console.log(inspectItem(parent));
const child1 = await client.items.create<Category>({ item_type: { type: "item_type", id: "UZyfjdBES8y2W2ruMEHSoA" }, name: "Child 1", parent_id: parent.id, position: 1, });
console.log(inspectItem(child1));
const child2 = await client.items.create<Category>({ item_type: { type: "item_type", id: "UZyfjdBES8y2W2ruMEHSoA" }, name: "Child 2", parent_id: parent.id, position: 2, });
console.log(inspectItem(child2));}
run();
└ Item "Ov5N1h4_QwW89_IzbUBb4g" (item_type: "UZyfjdBES8y2W2ruMEHSoA") ├ name: "Parent" ├ position: 1 └ parent_id: null
└ Item "a8A-nl0cRXCqBNniQMAxog" (item_type: "UZyfjdBES8y2W2ruMEHSoA") ├ name: "Child 1" ├ position: 1 └ parent_id: "Ov5N1h4_QwW89_IzbUBb4g"
└ Item "d6Gl9tPMSTqSF2bOMIcOYw" (item_type: "UZyfjdBES8y2W2ruMEHSoA") ├ name: "Child 2" ├ position: 2 └ parent_id: "Ov5N1h4_QwW89_IzbUBb4g"