The Message Batches API supports the same set of features as the Messages API. While this page focuses on how to use the Message Batches API, see Messages API examples for examples of the Messages API featureset.

Creating a Message Batch

JSON
{
  "id": "msgbatch_013Zva2CMHLNnXjNJJKqJ2EF",
  "type": "message_batch",
  "processing_status": "in_progress",
  "request_counts": {
    "processing": 2,
    "succeeded": 0,
    "errored": 0,
    "canceled": 0,
    "expired": 0
  },
  "ended_at": null,
  "created_at": "2024-09-24T18:37:24.100435Z",
  "expires_at": "2024-09-25T18:37:24.100435Z",
  "cancel_initiated_at": null,
  "results_url": null
}

Polling for Message Batch completion

To poll a Message Batch, you’ll need its id, which is provided in the response when creating request or by listing batches. Example id: msgbatch_013Zva2CMHLNnXjNJJKqJ2EF.

Listing all Message Batches in a Workspace

Output
{
  "id": "msgbatch_013Zva2CMHLNnXjNJJKqJ2EF",
  "type": "message_batch",
  ...
}
{
  "id": "msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d",
  "type": "message_batch",
  ...
}

Retrieving Message Batch Results

Once your Message Batch status is ended, you will be able to view the results_url of the batch and retrieve results in the form of a .jsonl file.

Output
{
  "id": "my-second-request",
  "result": {
    "type": "succeeded",
    "message": {
      "id": "msg_018gCsTGsXkYJVqYPxTgDHBU",
      "type": "message",
      ...
    }
  }
}
{
  "custom_id": "my-first-request",
  "result": {
    "type": "succeeded",
    "message": {
      "id": "msg_01XFDUDYJgAACzvnptvVoYEL",
      "type": "message",
      ...
    }
  }
}

Canceling a Message Batch

Immediately after cancellation, a batch’s processing_status will be canceling. You can use the same polling for batch completion technique to poll for when cancellation is finalized as canceled batches also end up ended and may contain results.

JSON
{
  "id": "msgbatch_013Zva2CMHLNnXjNJJKqJ2EF",
  "type": "message_batch",
  "processing_status": "canceling",
  "request_counts": {
    "processing": 2,
    "succeeded": 0,
    "errored": 0,
    "canceled": 0,
    "expired": 0
  },
  "ended_at": null,
  "created_at": "2024-09-24T18:37:24.100435Z",
  "expires_at": "2024-09-25T18:37:24.100435Z",
  "cancel_initiated_at": "2024-09-24T18:39:03.114875Z",
  "results_url": null
}