# Create a new record

> [!PROTIP] 📚 New to DatoCMS records?
> Before creating your first record, we strongly recommend reading the [Introduction to Records](https://www.datocms.com/docs/content-management-api/resources/item.md) 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](https://www.datocms.com/docs/content-management-api/resources/item-type.md) it's based on and the [fields](https://www.datocms.com/docs/content-management-api/resources/field.md) it contains.

Example Basic example

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.

###### Code

```javascript
import { buildClient, inspectItem } from "@datocms/cma-client-node";
import * as Schema from "./schema.js";

/*
 * Book
 * ├─ title: string
 * ├─ genre: string
 * ├─ synopsis: text
 * └─ pages: 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<Schema.Book>({
    item_type: Schema.Book.REF,
    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();
```

###### Returned output

```javascript
└ 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](https://www.datocms.com/docs/content-management-api/resources/item.md) offers a complete reference for every field type, there are several key rules that are especially important when **creating** a new record.

### TypeScript typing

Writing a create payload without typed schemas means writing blind: every field is `unknown`, typos compile fine, and mistakes only surface as `422`s from the API. The single biggest lever you have is passing a [generated `Schema.X` marker](https://www.datocms.com/cma-ts-schema.md) as the generic on `items.create`. TypeScript then enforces the model's field names, types, and allowed block shapes at compile time:

```ts
// ❌ Untyped: every field is `unknown`, typos compile.
await client.items.create({ /* … */ });

// ✅ Typed: field names, types, and block shapes enforced.
await client.items.create<Schema.Article>({ /* … */ });
```

When you need the actual TypeScript type of a single field — to annotate a helper, an intermediate variable, or a function parameter — reach for `FieldValueInRequest<T, 'field_key'>`. The first argument is the `Schema.X` marker for the model that owns the field:

> [!WARNING] ⚠️ A marker can't be indexed directly
> `Schema.Article` is a phantom *type marker*, not a record shape. Writing `Schema.Article["content"]` won't give you the field type.
> 
> ```ts
> // ❌ Markers aren't indexable
> type Content = Schema.Article["content"];
> 
> 
> // ✅ Use the helper instead
> type Content = NonNullable<FieldValueInRequest<Schema.Article, "content">>;
> ```

```ts
function buildSections(
  page: ApiTypes.ItemInNestedResponse,
): NonNullable<FieldValueInRequest<Schema.LandingPage, "sections">> {
  // …assemble and return the sections array…
}

await client.items.create<Schema.LandingPage>({
  item_type: Schema.LandingPage.REF,
  title: "Product Launch Landing Page",
  sections: buildSections(sourcePage),
});
```

The first argument also accepts an item-shaped value the CMA already produced — useful when you're cloning or migrating from an existing record:

```ts
const source = await client.items.find<Schema.Article>("source-id", { nested: true });

if (source.content) {
  const content: NonNullable<FieldValueInRequest<typeof source, "content">> =
    /* …transform source.content… */;
  await client.items.create<Schema.Article>({ item_type: Schema.Article.REF, content });
}
```

> [!WARNING] ⚠️ Field values are always nullable
> Even fields with a **required** validator are typed as `Nullable`, because the API may still accept/return `null` in some scenarios. Wrap the helper in `NonNullable<…>` when you need the non-null shape.

> [!PROTIP] 📖 Read-side counterparts
> `FieldValueInRequest` is the *write*\-side helper. For values coming back from the API, use `FieldValue<T, 'field_key'>` (regular responses) or `FieldValueInNestedResponse<T, 'field_key'>` (when you fetched with `nested: true`). All three follow the same `<marker-or-value, fieldKey>` shape — see the [Item resource overview](https://www.datocms.com/docs/content-management-api/resources/item.md) for the full helper family.

### 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](https://www.datocms.com/docs/content-management-api/resources/item.md#field-types-overview)** in our main records guide.

Example Managing simple fields

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**](https://www.datocms.com/docs/content-management-api/resources/item.md#field-types-overview) section.

###### Code

```javascript
import { buildClient, inspectItem } from "@datocms/cma-client-node";
import * as Schema from "./schema.js";

/*
 * Product
 * ├─ name: string
 * ├─ category: string
 * ├─ description: text
 * ├─ price: integer
 * ├─ weight: float
 * ├─ release_date: date_time
 * ├─ in_stock: boolean
 * ├─ warehouse_location: lat_lon
 * ├─ brand_color: color
 * └─ specifications: 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<Schema.Product>({
    item_type: Schema.Product.REF,
    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();
```

###### Returned output

```javascript
└ 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](https://www.datocms.com/docs/content-management-api/resources/item.md#creating-and-updating-blocks)**.

Example Modular content fields

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:

###### Code

```javascript
import {
  buildBlockRecord,
  buildClient,
  inspectItem,
} from "@datocms/cma-client-node";
import * as Schema from "./schema.js";

/*
 * LandingPage
 * ├─ title: string
 * └─ sections: rich_text
 *    ├─ HeroBlock: headline, subtitle, background_image
 *    └─ TestimonialBlock: quote, author_name
 */

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<Schema.LandingPage>({
    item_type: Schema.LandingPage.REF,
    title: "Product Launch Landing Page",
    sections: [
      // hero block
      buildBlockRecord<Schema.HeroBlock>({
        item_type: Schema.HeroBlock.REF,
        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<Schema.TestimonialBlock>({
        item_type: Schema.TestimonialBlock.REF,
        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<Schema.LandingPage>(record, {
    nested: true,
  });
  console.log(inspectItem(nestedRecord));
}

run();
```

###### Returned output

```javascript
-- 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"
```
Example Single block fields

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:

###### Code

```javascript
import {
  buildBlockRecord,
  buildClient,
  inspectItem,
} from "@datocms/cma-client-node";
import * as Schema from "./schema.js";

/*
 * 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
 */

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<Schema.ProductPage>({
    item_type: Schema.ProductPage.REF,
    title: "Premium Wireless Headphones",
    price: 299.99,
    hero_section: buildBlockRecord<Schema.HeroBlock>({
      item_type: Schema.HeroBlock.REF,
      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<Schema.ButtonBlock>({
        item_type: Schema.ButtonBlock.REF,
        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<Schema.ProductPage>(record, {
    nested: true,
  });
  console.log(inspectItem(nestedRecord));
}

run();
```

###### Returned output

```javascript
-- 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"
```
Example Structured text fields

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](https://www.datocms.com/docs/content-management-api/resources/upload/create.md) endpoint documentation.

###### Code

```javascript
import {
  buildBlockRecord,
  buildClient,
  inspectItem,
} from "@datocms/cma-client-node";
import * as Schema from "./schema.js";

/*
 * Article
 * ├─ title: string
 * └─ content: structured_text
 *    ├─ CtaBlock: title, description, button_text, button_url
 *    └─ ImageGalleryBlock: title, images
 */

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<Schema.Article>({
    item_type: Schema.Article.REF,
    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<Schema.ImageGalleryBlock>({
              item_type: Schema.ImageGalleryBlock.REF,
              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<Schema.CtaBlock>({
              item_type: Schema.CtaBlock.REF,
              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<Schema.Article>(record, {
    nested: true,
  });
  console.log(inspectItem(nestedRecord));
}

run();
```

###### Returned output

```javascript
-- 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](https://www.datocms.com/docs/content-management-api/resources/item.md#field-types-overview)** in our main records guide.

Example Linking assets to records

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](https://www.datocms.com/docs/content-management-api/resources/upload/create.md) endpoint documentation.

###### Code

```javascript
import { buildClient, inspectItem } from "@datocms/cma-client-node";
import * as Schema from "./schema.js";

/*
 * Portfolio
 * ├─ title: string
 * ├─ featured_image: file
 * └─ gallery: 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<Schema.Portfolio>({
    item_type: Schema.Portfolio.REF,
    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();
```

###### Returned output

```javascript
└ 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%
```
Example Linking records to other records

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.

###### Code

```javascript
import { buildClient, inspectItem } from "@datocms/cma-client-node";
import * as Schema from "./schema.js";

/*
 * Author
 * ├─ name: string
 * ├─ collaborators: links
 * └─ mentor: 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<Schema.Author>({
    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<Schema.Author>({
    item_type: Schema.Author.REF,
    name: "Sarah Johnson",
    collaborators: otherAuthors.map((author) => author.id),
    mentor: otherAuthors[0]!.id,
  });

  console.log(inspectItem(record));
}

run();
```

###### Returned output

```javascript
└ 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`](https://www.datocms.com/docs/content-management-api/resources/item-type.md#object-payload)), then the payload must include a key for every available locale for each localized field. The value of a field for a locale can be `null`, but the key itself is mandatory.

For a full explanation of how to structure localized data, refer to the [localization Guide](https://www.datocms.com/docs/content-management-api/resources/item.md#localization).

Example Managing localized fields

The code shows two scenarios:

1.  Providing content for a subset of available locales (`en`, `it`) with consistent locale keys across all localized fields
2.  Including all available locales (`en`, `it`, `fr`) even when some translations are `null`

###### Code

```javascript
import { buildClient, inspectItem } from "@datocms/cma-client-node";
import * as Schema from "./schema.js";

/*
 * Pet
 * ├─ name: string (localized)
 * ├─ description: string (localized)
 * └─ category: 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 });

  // Example 1: Basic localization - consistent locales across all localized fields
  const basicRecord = await client.items.create<Schema.Pet>({
    item_type: Schema.Pet.REF,
    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<Schema.Pet>({
    item_type: Schema.Pet.REF,
    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();
```

###### Returned output

```javascript
-- 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

id string Optional

RFC 4122 UUID of record expressed in URL-safe base64 format

Example: `"hWl-mnkWRYmMCSTq4z_piQ"`

meta.created\_at string Optional

Date of creation

meta.first\_published\_at null, string Optional

Date of first publication

item\_type Required

The record's model

Type: [ResourceLinkage<"item\_type"\>](https://www.datocms.com/docs/content-management-api/resources/item_type.md)

creator Optional

The entity (account/collaborator/access token/sso user) who created the record

Type: [ResourceLinkage<"account"\>](https://www.datocms.com/docs/content-management-api/resources/account.md), [ResourceLinkage<"access\_token"\>](https://www.datocms.com/docs/content-management-api/resources/access_token.md), [ResourceLinkage<"user"\>](https://www.datocms.com/docs/content-management-api/resources/user.md), [ResourceLinkage<"sso\_user"\>](https://www.datocms.com/docs/content-management-api/resources/sso_user.md), [ResourceLinkage<"organization"\>](https://www.datocms.com/docs/content-management-api/resources/organization.md)

## Returns

Returns a resource object of type [item](https://www.datocms.com/docs/content-management-api/resources/item.md)

## Other examples

Example Tree-like structure

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 hierarchy

-   **`position`**: Sets the ordering among sibling records

The example shows how to build a hierarchy by creating records that reference each other:

###### Code

```javascript
import { buildClient, inspectItem } from "@datocms/cma-client-node";
import * as Schema from "./schema.js";

/*
 * Category
 * ├─ name: string
 * ├─ position: integer
 * └─ parent_id: 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 });

  const parent = await client.items.create<Schema.Category>({
    item_type: Schema.Category.REF,
    name: "Parent",
  });

  console.log(inspectItem(parent));

  const child1 = await client.items.create<Schema.Category>({
    item_type: Schema.Category.REF,
    name: "Child 1",
    parent_id: parent.id,
    position: 1,
  });

  console.log(inspectItem(child1));

  const child2 = await client.items.create<Schema.Category>({
    item_type: Schema.Category.REF,
    name: "Child 2",
    parent_id: parent.id,
    position: 2,
  });

  console.log(inspectItem(child2));
}

run();
```

###### Returned output

```javascript
└ 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"
```

## Related content in "Content Management API"

- [Content Management API Overview](https://www.datocms.com/docs/content-management-api.md)

- [Using the JavaScript CMA client](https://www.datocms.com/docs/content-management-api/using-the-nodejs-clients.md)
- [API versioning](https://www.datocms.com/docs/content-management-api/api-versioning.md)

- [Authentication](https://www.datocms.com/docs/content-management-api/authentication.md)
- [Environments](https://www.datocms.com/docs/content-management-api/setting-the-environment.md)

- [Error codes & handling failures (CMA)](https://www.datocms.com/docs/content-management-api/errors.md)
- [Pagination](https://www.datocms.com/docs/content-management-api/pagination.md)

- [Asynchronous jobs](https://www.datocms.com/docs/content-management-api/async-jobs.md)
- [Technical Limits (CMA)](https://www.datocms.com/docs/content-management-api/technical-limits.md)

- [Record](https://www.datocms.com/docs/content-management-api/resources/item.md)
- [List all records](https://www.datocms.com/docs/content-management-api/resources/item/instances.md)

- [Create a new record](https://www.datocms.com/docs/content-management-api/resources/item/create.md)
- [Duplicate a record](https://www.datocms.com/docs/content-management-api/resources/item/duplicate.md)

- [Update a record](https://www.datocms.com/docs/content-management-api/resources/item/update.md)
- [Referenced records](https://www.datocms.com/docs/content-management-api/resources/item/references.md)

- [Retrieve a record](https://www.datocms.com/docs/content-management-api/resources/item/self.md)
- [Delete a record](https://www.datocms.com/docs/content-management-api/resources/item/destroy.md)

- [Publish a record](https://www.datocms.com/docs/content-management-api/resources/item/publish.md)
- [Unpublish a record](https://www.datocms.com/docs/content-management-api/resources/item/unpublish.md)

- [Publish items in bulk](https://www.datocms.com/docs/content-management-api/resources/item/bulk_publish.md)
- [Unpublish items in bulk](https://www.datocms.com/docs/content-management-api/resources/item/bulk_unpublish.md)

- [Destroy items in bulk](https://www.datocms.com/docs/content-management-api/resources/item/bulk_destroy.md)
- [Move items to stage in bulk](https://www.datocms.com/docs/content-management-api/resources/item/bulk_move_to_stage.md)

- [Scheduled publication](https://www.datocms.com/docs/content-management-api/resources/scheduled-publication.md)
- [Scheduled unpublishing](https://www.datocms.com/docs/content-management-api/resources/scheduled-unpublishing.md)

- [Upload](https://www.datocms.com/docs/content-management-api/resources/upload.md)
- [Site](https://www.datocms.com/docs/content-management-api/resources/site.md)

- [Model/Block model](https://www.datocms.com/docs/content-management-api/resources/item-type.md)
- [Field](https://www.datocms.com/docs/content-management-api/resources/field.md)

- [Fieldset](https://www.datocms.com/docs/content-management-api/resources/fieldset.md)
- [Record version](https://www.datocms.com/docs/content-management-api/resources/item-version.md)

- [Upload permission](https://www.datocms.com/docs/content-management-api/resources/upload-request.md)
- [Upload track](https://www.datocms.com/docs/content-management-api/resources/upload-track.md)

- [Manual tags](https://www.datocms.com/docs/content-management-api/resources/upload-tag.md)
- [Smart tags](https://www.datocms.com/docs/content-management-api/resources/upload-smart-tag.md)

- [Upload Collection](https://www.datocms.com/docs/content-management-api/resources/upload-collection.md)
- [Search Index](https://www.datocms.com/docs/content-management-api/resources/search-index.md)

- [Search result](https://www.datocms.com/docs/content-management-api/resources/search-result.md)
- [Search indexing activity](https://www.datocms.com/docs/content-management-api/resources/search-index-event.md)

- [Environment](https://www.datocms.com/docs/content-management-api/resources/environment.md)
- [Maintenance mode](https://www.datocms.com/docs/content-management-api/resources/maintenance-mode.md)

- [Menu Item](https://www.datocms.com/docs/content-management-api/resources/menu-item.md)
- [Schema Menu Item](https://www.datocms.com/docs/content-management-api/resources/schema-menu-item.md)

- [Uploads filter](https://www.datocms.com/docs/content-management-api/resources/upload-filter.md)
- [Model filter](https://www.datocms.com/docs/content-management-api/resources/item-type-filter.md)

- [Plugin](https://www.datocms.com/docs/content-management-api/resources/plugin.md)
- [Workflow](https://www.datocms.com/docs/content-management-api/resources/workflow.md)

- [Asynchronous job](https://www.datocms.com/docs/content-management-api/resources/job.md)
- [Job result](https://www.datocms.com/docs/content-management-api/resources/job-result.md)

- [Account](https://www.datocms.com/docs/content-management-api/resources/account.md)
- [Organization](https://www.datocms.com/docs/content-management-api/resources/organization.md)

- [Invitation](https://www.datocms.com/docs/content-management-api/resources/site-invitation.md)
- [Collaborator](https://www.datocms.com/docs/content-management-api/resources/user.md)

- [Role](https://www.datocms.com/docs/content-management-api/resources/role.md)
- [API token](https://www.datocms.com/docs/content-management-api/resources/access-token.md)

- [Webhook](https://www.datocms.com/docs/content-management-api/resources/webhook.md)
- [Webhook call](https://www.datocms.com/docs/content-management-api/resources/webhook-call.md)

- [Build trigger](https://www.datocms.com/docs/content-management-api/resources/build-trigger.md)
- [Deploy activity](https://www.datocms.com/docs/content-management-api/resources/build-event.md)

- [Subscription limit](https://www.datocms.com/docs/content-management-api/resources/subscription-limit.md)
- [Subscription feature](https://www.datocms.com/docs/content-management-api/resources/subscription-feature.md)

- [SSO Settings](https://www.datocms.com/docs/content-management-api/resources/sso-settings.md)
- [SSO User](https://www.datocms.com/docs/content-management-api/resources/sso-user.md)

- [SSO Group](https://www.datocms.com/docs/content-management-api/resources/sso-group.md)
- [White-label settings](https://www.datocms.com/docs/content-management-api/resources/white-label-settings.md)

- [Audit log event](https://www.datocms.com/docs/content-management-api/resources/audit-log-event.md)