> ## Documentation Index
> Fetch the complete documentation index at: https://buttercms.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Bulk Operations

> Guide for performing bulk create, update, and delete operations using the ButterCMS Write API.

## Overview

For Collections, `POST /v2/content/` accepts multiple items in a single request by passing an array of item objects in `fields`. This is the most efficient way to bulk-create Collection items, since it's one HTTP call instead of one per item. Pages and Blog Posts don't have an equivalent multi-item endpoint, so bulk operations on those content types (and any per-item update/delete/publish on Collections) still require orchestrating multiple Write API calls. This guide covers patterns and best practices for both.

> [!WARNING]
>
> Write API access requires a **Write API Token**. It's a paid add-on for Advanced and Professional plans; purchase it from **Settings** > **Billing** in your dashboard. It isn't offered on Basic plans; upgrade your plan or contact support.

### Key Considerations

* **Request Pacing**: Add small delays between requests to keep bulk operations stable and reduce monthly usage spikes.
* **Error Handling**: Implement retry logic for transient failures.
* **Progress Tracking**: Track successful and failed operations for large imports.
* **Async Nature**: Write operations return `202 Accepted`—content typically appears within seconds but processing time may vary.

## Bulk Create Pattern

### Single-Request Batch Create (Collections)

The fastest way to bulk-create Collection items: pass every item as an entry in the `fields` array of one `POST /v2/content/` call. The collection key goes in the body as `key`, not in the URL. The response is a single `202 {"status": "pending"}` with no item IDs. Writes are asynchronous, so verify the created items via the Read API afterward.

```javascript theme={null}
async function batchCreate(collectionKey, items) {
  const response = await axios.post(
    'https://api.buttercms.com/v2/content/',
    {
      key: collectionKey,
      status: 'draft',
      fields: items // an array of item objects, even for a single item
    },
    {
      headers: {
        'Authorization': `Token ${WRITE_TOKEN}`,
        'Content-Type': 'application/json'
      }
    }
  );

  return response.data; // { status: "pending" }
}

// Usage
const items = [
  { name: 'Item 1', category: 'A' },
  { name: 'Item 2', category: 'B' },
  { name: 'Item 3', category: 'A' }
];

await batchCreate('products', items);
```

For very large imports, split items into chunks (e.g. 50-100 per request) and pace the chunked requests rather than sending one request per item.

### Sequential Creation with Request Pacing

Use a per-item loop when you need per-item error tracking, or for content types without a batch-create endpoint (Pages, Blog Posts):

```javascript theme={null}
async function bulkCreate(collectionKey, items, delayMs = 200) {
  const results = {
    success: [],
    failed: []
  };

  for (const item of items) {
    try {
      await axios.post(
        'https://api.buttercms.com/v2/content/',
        {
          key: collectionKey,
          status: 'draft',
          fields: [item]
        },
        {
          headers: {
            'Authorization': `Token ${WRITE_TOKEN}`,
            'Content-Type': 'application/json'
          }
        }
      );

      // The create response has no item id (async write) -- verify via the Read API if needed
      results.success.push({ item });
    } catch (error) {
      results.failed.push({
        item,
        error: error.response?.data || error.message
      });
    }

    // Rate limiting delay
    await new Promise(r => setTimeout(r, delayMs));
  }

  return results;
}

// Usage
const items = [
  { name: 'Item 1', category: 'A' },
  { name: 'Item 2', category: 'B' },
  { name: 'Item 3', category: 'A' }
];

const results = await bulkCreate('products', items);
console.log(`Created: ${results.success.length}, Failed: ${results.failed.length}`);
```

### Parallel Creation with Concurrency Control

For faster bulk operations, use controlled concurrency:

```javascript theme={null}
const pLimit = require('p-limit');

async function bulkCreateParallel(collectionKey, items, concurrency = 5) {
  const limit = pLimit(concurrency);
  const results = { success: [], failed: [] };

  const promises = items.map(item =>
    limit(async () => {
      try {
        await axios.post(
          'https://api.buttercms.com/v2/content/',
          { key: collectionKey, status: 'draft', fields: [item] },
          { headers: { 'Authorization': `Token ${WRITE_TOKEN}` } }
        );
        results.success.push({ item });
      } catch (error) {
        results.failed.push({ item, error: error.response?.data });
      }
    })
  );

  await Promise.all(promises);
  return results;
}
```

## Bulk Update Pattern

### Update Multiple Items by ID

```javascript theme={null}
async function bulkUpdate(collectionKey, updates, delayMs = 200) {
  const results = { success: [], failed: [] };

  for (const { id, fields } of updates) {
    try {
      await axios.patch(
        `https://api.buttercms.com/v2/content/${collectionKey}/${id}/`,
        { status: 'published', fields },
        {
          headers: {
            'Authorization': `Token ${WRITE_TOKEN}`,
            'Content-Type': 'application/json'
          }
        }
      );
      results.success.push({ id });
    } catch (error) {
      results.failed.push({ id, error: error.response?.data });
    }

    await new Promise(r => setTimeout(r, delayMs));
  }

  return results;
}

// Usage
const updates = [
  { id: 123, fields: { status: 'active' } },
  { id: 124, fields: { status: 'active' } },
  { id: 125, fields: { status: 'inactive' } }
];

await bulkUpdate('products', updates);
```

> [!NOTE]
>
> Include `status: 'published'` in every update. Without it, the changes are saved as a draft revision and the live content does not change.

### Publishing Draft Items

The Write API cannot publish a collection item that was created as a draft. A PUT or PATCH with `status: 'published'` publishes the new field values, but the item itself stays hidden from production reads. Publish draft items from the Collections dashboard, which supports selecting several items at once. A PATCH that sends only `status` without `fields` returns `400`.

## Bulk Delete Pattern

```javascript theme={null}
async function bulkDelete(collectionKey, itemIds, delayMs = 200) {
  const results = { success: [], failed: [] };

  for (const id of itemIds) {
    try {
      await axios.delete(
        `https://api.buttercms.com/v2/content/${collectionKey}/${id}/`,
        { headers: { 'Authorization': `Token ${WRITE_TOKEN}` } }
      );
      results.success.push(id);
    } catch (error) {
      results.failed.push({ id, error: error.response?.data });
    }

    await new Promise(r => setTimeout(r, delayMs));
  }

  return results;
}
```

## Content Migration Example

### WordPress to ButterCMS Migration

```javascript theme={null}
const axios = require('axios');

const WRITE_TOKEN = 'your-write-token';
const READ_TOKEN = 'your-read-token';
const API_BASE = 'https://api.buttercms.com/v2';

async function migrateWordPressPosts(wpPosts) {
  console.log(`Starting migration of ${wpPosts.length} posts...`);

  const results = {
    success: [],
    failed: [],
    skipped: []
  };

  for (let i = 0; i < wpPosts.length; i++) {
    const post = wpPosts[i];
    console.log(`[${i + 1}/${wpPosts.length}] Processing: ${post.title}`);

    // Skip if slug already exists
    try {
      await axios.get(
        `${API_BASE}/posts/${post.slug}/?auth_token=${READ_TOKEN}`
      );
      results.skipped.push({ slug: post.slug, reason: 'Already exists' });
      continue;
    } catch (e) {
      // Post doesn't exist, proceed with creation
    }

    try {
      const butterPost = {
        title: post.title,
        slug: post.slug,
        body: post.content,
        summary: post.excerpt || '',
        seo_title: post.seo_title || post.title,
        meta_description: post.meta_description || post.excerpt || '',
        featured_image: post.featured_image || '',
        status: post.status === 'publish' ? 'published' : 'draft',
        categories: post.categories?.map(c => c.name) || [],
        tags: post.tags?.map(t => t.name) || []
      };

      await axios.post(
        `${API_BASE}/posts/`,
        butterPost,
        { headers: { 'Authorization': `Token ${WRITE_TOKEN}` } }
      );

      results.success.push({ slug: post.slug });
    } catch (error) {
      results.failed.push({
        slug: post.slug,
        error: error.response?.data || error.message
      });
    }

    // Rate limiting
    await new Promise(r => setTimeout(r, 300));
  }

  console.log('\nMigration complete:');
  console.log(`  Success: ${results.success.length}`);
  console.log(`  Failed: ${results.failed.length}`);
  console.log(`  Skipped: ${results.skipped.length}`);

  return results;
}
```

## Handling 429 Responses

A `429` from the Write/Read API means your account's **monthly** API call limit has been exceeded (Free/Trial plans). `Retry-After` reflects the time until your next monthly reset, which can be hours or weeks away, so a quick retry loop won't resolve it. Stop the bulk operation, surface the limit to a human, and either reduce call volume or upgrade your plan.

```javascript theme={null}
async function runWithQuotaCheck(fn) {
  try {
    return await fn();
  } catch (error) {
    if (error.response?.status === 429) {
      const retryAfter = Number(error.response.headers?.['retry-after'] || 0);
      throw new Error(
        `Monthly API call limit reached. Resets in ~${Math.round(retryAfter / 3600)}h. ` +
        `Stopping bulk operation — upgrade your plan or wait for the reset.`
      );
    }
    throw error;
  }
}

// Usage in bulk operations
async function createItemWithRetry(collectionKey, fields) {
  return runWithQuotaCheck(() =>
    axios.post(
      'https://api.buttercms.com/v2/content/',
      { key: collectionKey, status: 'draft', fields: [fields] },
      { headers: { 'Authorization': `Token ${WRITE_TOKEN}` } }
    )
  );
}
```

## Progress Tracking and Logging

```javascript theme={null}
class BulkOperationTracker {
  constructor(totalItems) {
    this.total = totalItems;
    this.processed = 0;
    this.success = 0;
    this.failed = 0;
    this.startTime = Date.now();
  }

  recordSuccess() {
    this.processed++;
    this.success++;
    this.logProgress();
  }

  recordFailure(error) {
    this.processed++;
    this.failed++;
    this.logProgress();
  }

  logProgress() {
    const elapsed = (Date.now() - this.startTime) / 1000;
    const rate = this.processed / elapsed;
    const remaining = (this.total - this.processed) / rate;

    console.log(
      `Progress: ${this.processed}/${this.total} ` +
      `(${this.success} success, ${this.failed} failed) ` +
      `ETA: ${Math.round(remaining)}s`
    );
  }

  getSummary() {
    return {
      total: this.total,
      success: this.success,
      failed: this.failed,
      duration: (Date.now() - this.startTime) / 1000
    };
  }
}

// Usage
const tracker = new BulkOperationTracker(items.length);

for (const item of items) {
  try {
    await createItem(item);
    tracker.recordSuccess();
  } catch (error) {
    tracker.recordFailure(error);
  }
}

console.log('Summary:', tracker.getSummary());
```

## Best Practices

> [card] Request Pacing
>
> Add 200-500ms delay between requests to keep bulk operations stable and reduce monthly API usage spikes.

> [card] Idempotency
>
> Check if content exists before creating to avoid duplicates during retries.

> [card] Error Logging
>
> Log failed operations for manual review and retry.

> [card] Batch Verification
>
> After bulk operations, verify content via Read API.

## Suggested Starting Points

ButterCMS doesn't enforce a concurrency cap or minimum delay between requests for most accounts. These values are guidance to keep your own bulk jobs stable and avoid using up your monthly API call quota too quickly.

| Operation Type | Suggested Concurrency | Delay Between Requests |
| - | - | - |
| Create | 3-5 parallel | 200ms |
| Update | 5-10 parallel | 100ms |
| Delete | 5-10 parallel | 100ms |
| Migration | 1-3 parallel | 300ms |

> [!NOTE]
>
> Free/Trial accounts can be blocked for the rest of the billing month when their monthly API call limit is exceeded. See [Handling 429 Responses](#handling-429-responses).

## Next Steps

> [card] [Pages - Write](https://buttercms.com/docs/api-reference/pages/create-page-via-write-api.md)
>
> Create and update pages

> [card] [Collections - Write](https://buttercms.com/docs/api-reference/collections/create-collection-item.md)
>
> Create collection items

> [card] [Blog Posts - Write](https://buttercms.com/docs/api-reference/blog-posts/create-blog-post-via-write-api.md)
>
> Create blog posts

> [card] [Rate Limits](https://buttercms.com/docs/api/concepts/rate-limits-throttling.md)
>
> API rate limiting


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.