# Create a batch ID

## API Overview

Using the Cancel Scheduled Sends API, you can cancel or pause sending one or more groups of emails. SendGrid defines these multiple scheduled send requests together as batches identified with a `batch_id`.

With this API, you can perform the following tasks on scheduled emails:

* Define and validate the ID for a batch of messages.
* Retrieve, update, pause, resume, or cancel a scheduled send.

Cancelling or pausing a batch of messages include the following conditions:

* You can't pause or cancel more than 10 different batches at one time.
* You can't pause or cancel a batch later than 10 minutes before the scheduled `send_at` time.
* When you cancel or pause a batch, all messages associated with that batch stay in your sending queue.
* When a cancelled batch reaches its `send_at` time, SendGrid discards the messages.
* When a paused batch reaches its `send_at` time, SendGrid retains the messages.
  When you resume a paused batch, SendGrid delivers your scheduled send.
* When a paused batch passes 72 hours after its `send_at` time, SendGrid discards the messages as *Expired*.

To cancel a scheduled send of a single message, consult [Canceling a Scheduled Send][cancel-send].

[cancel-send]: /docs/sendgrid/for-developers/sending-email/stopping-a-scheduled-send/

## Operation overview

```json
{"path":"https://api.sendgrid.com/v3/mail/batch","method":"post","servers":[{"url":"https://api.sendgrid.com","description":"for global users and subusers"},{"url":"https://api.eu.sendgrid.com","description":"for EU regional subusers"}]}
```

**This operation allows you to generate a new mail batch ID.**

Once a batch ID is created, you can associate it with a mail send by passing
it in the request body of the [Mail Send operation](/docs/sendgrid/api-reference/mail-send/mail-send).
This makes it possible to group multiple requests to the Mail Send operation
by assigning them the same batch ID.

A batch ID that's associated with a mail send can be used to access and modify the associated send. For example, you can pause or cancel a send using its batch ID. See the [Scheduled Sends API](/docs/sendgrid/api-reference/cancel-scheduled-sends) for more information about pausing and cancelling a mail send.

## Operation details

### Authentication

API Key

### Headers

```json
[{"in":"header","name":"Authorization","required":true,"default":"Bearer <<YOUR_API_KEY_HERE>>","schema":{"type":"string"}},{"name":"on-behalf-of","in":"header","description":"Use the `on-behalf-of` header to make API calls for a particular Subuser through the parent account. You can use this header to automate bulk updates or to administer a Subuser without changing the authentication in your code. You will use the parent account's API key when using this header.","required":false,"schema":{"type":"string"},"refName":"#/components/parameters/OnBehalfOf","modelName":"__components_parameters_OnBehalfOf"}]
```

### Responses

```json
[{"responseCode":"201","schema":{"description":"Batch ID success response.","content":{"application/json":{"schema":{"title":"Mail Batch and Batch ID Response Schema","type":"object","example":{"batch_id":"HkJ5yLYULb7Rj8GKSx7u025ouWVlMgAi"},"refName":"MailBatchResponse","modelName":"MailBatchResponse","properties":{"batch_id":{"type":"string","description":"A mail batch ID."}}},"examples":{"Success":{"summary":"A mail batch ID.","value":{"batch_id":"123abc456def789hij0"},"refName":"#/components/examples/MailBatch2xx","modelName":"__components_examples_MailBatch2xx"}}}},"refName":"#/components/responses/MailBatch2xx","modelName":"__components_responses_MailBatch2xx"}},{"responseCode":"400","schema":{"description":"Batch ID bad response.","content":{"application/json":{"schema":{"type":"object","example":{"errors":[{"field":"field_name","message":"error message"}]},"refName":"ErrorResponse","modelName":"ErrorResponse","properties":{"errors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"An error message."},"field":{"description":"When applicable, this property value will be the field that generated the error.","nullable":true,"type":"string"},"help":{"type":"object","description":"When applicable, this property value will be helper text or a link to documentation to help you troubleshoot the error."}}}},"id":{"type":"string","description":"When applicable, this property value will be an error ID."}}},"examples":{"Bad request":{"value":{"errors":[{"message":"invalid batch id","field":"null"}]}}}}},"refName":"#/components/responses/MailBatch400","modelName":"__components_responses_MailBatch400"}},{"responseCode":"401","schema":{"description":"Batch ID unauthorized response.","content":{"application/json":{"schema":{"type":"object","example":{"errors":[{"field":"field_name","message":"error message"}]},"refName":"ErrorResponse","modelName":"ErrorResponse","properties":{"errors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"An error message."},"field":{"description":"When applicable, this property value will be the field that generated the error.","nullable":true,"type":"string"},"help":{"type":"object","description":"When applicable, this property value will be helper text or a link to documentation to help you troubleshoot the error."}}}},"id":{"type":"string","description":"When applicable, this property value will be an error ID."}}},"examples":{"Unauthorized request":{"value":{"errors":[{"message":"authorization required","field":"null"}]}}}}},"refName":"#/components/responses/MailBatch401","modelName":"__components_responses_MailBatch401"}},{"responseCode":"403","schema":{"description":"Batch ID forbidden response.","content":{"application/json":{"schema":{"type":"object","example":{"errors":[{"field":"field_name","message":"error message"}]},"refName":"ErrorResponse","modelName":"ErrorResponse","properties":{"errors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"An error message."},"field":{"description":"When applicable, this property value will be the field that generated the error.","nullable":true,"type":"string"},"help":{"type":"object","description":"When applicable, this property value will be helper text or a link to documentation to help you troubleshoot the error."}}}},"id":{"type":"string","description":"When applicable, this property value will be an error ID."}}},"examples":{"Unauthorized request":{"value":{"errors":[{"message":"access forbidden","field":"null"}]}}}}},"refName":"#/components/responses/MailBatch403","modelName":"__components_responses_MailBatch403"}},{"responseCode":"404","schema":{"description":"Batch ID not found response.","content":{"application/json":{"schema":{"type":"object","example":{"errors":[{"field":"field_name","message":"error message"}]},"refName":"ErrorResponse","modelName":"ErrorResponse","properties":{"errors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"An error message."},"field":{"description":"When applicable, this property value will be the field that generated the error.","nullable":true,"type":"string"},"help":{"type":"object","description":"When applicable, this property value will be helper text or a link to documentation to help you troubleshoot the error."}}}},"id":{"type":"string","description":"When applicable, this property value will be an error ID."}}},"examples":{"Unauthorized request":{"value":{"errors":[{"message":"batch id not found","field":"null"}]}}}}},"refName":"#/components/responses/MailBatch404","modelName":"__components_responses_MailBatch404"}},{"responseCode":"405","schema":{"description":"Get batch ID method not allowed response.","content":{"application/json":{"schema":{"type":"object","example":{"errors":[{"field":"field_name","message":"error message"}]},"refName":"ErrorResponse","modelName":"ErrorResponse","properties":{"errors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"An error message."},"field":{"description":"When applicable, this property value will be the field that generated the error.","nullable":true,"type":"string"},"help":{"type":"object","description":"When applicable, this property value will be helper text or a link to documentation to help you troubleshoot the error."}}}},"id":{"type":"string","description":"When applicable, this property value will be an error ID."}}},"examples":{"Unauthorized request":{"value":{"errors":[{"message":"method not allowed","field":"null"}]}}}}},"refName":"#/components/responses/MailBatch405","modelName":"__components_responses_MailBatch405"}},{"responseCode":"500","schema":{"description":"Get batch ID internal server error response.","content":{"application/json":{"schema":{"type":"object","example":{"errors":[{"field":"field_name","message":"error message"}]},"refName":"ErrorResponse","modelName":"ErrorResponse","properties":{"errors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"An error message."},"field":{"description":"When applicable, this property value will be the field that generated the error.","nullable":true,"type":"string"},"help":{"type":"object","description":"When applicable, this property value will be helper text or a link to documentation to help you troubleshoot the error."}}}},"id":{"type":"string","description":"When applicable, this property value will be an error ID."}}},"examples":{"Unauthorized request":{"value":{"errors":[{"message":"internal server error","field":"null"}]}}}}},"refName":"#/components/responses/MailBatch500","modelName":"__components_responses_MailBatch500"}}]
```

Create a batch ID

```js
const client = require("@sendgrid/client");
client.setApiKey(process.env.SENDGRID_API_KEY);

const request = {
  url: `/v3/mail/batch`,
  method: "POST",
};

client
  .request(request)
  .then(([response, body]) => {
    console.log(response.statusCode);
    console.log(response.body);
  })
  .catch((error) => {
    console.error(error);
  });
```

```python
import os
from sendgrid import SendGridAPIClient


sg = SendGridAPIClient(os.environ.get("SENDGRID_API_KEY"))


response = sg.client.mail.batch.post()

print(response.status_code)
print(response.body)
print(response.headers)
```

```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using SendGrid;

public class Program {
    public static async Task Main() {
        string apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
        var client = new SendGridClient(apiKey);

        var response =
            await client.RequestAsync(method: SendGridClient.Method.POST, urlPath: "mail/batch");

        Console.WriteLine(response.StatusCode);
        Console.WriteLine(response.Body.ReadAsStringAsync().Result);
        Console.WriteLine(response.Headers.ToString());
    }
}
```

```java
import com.sendgrid.*;
import java.io.IOException;

public class Example {
    public static void main(String[] args) throws IOException {
        try {
            SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
            Request request = new Request();
            request.setMethod(Method.POST);
            request.setEndpoint("/mail/batch");
            Response response = sg.api(request);
            System.out.println(response.getStatusCode());
            System.out.println(response.getBody());
            System.out.println(response.getHeaders());
        } catch (IOException ex) {
            throw ex;
        }
    }
}
```

```go
package main

import (
	"fmt"
	"github.com/sendgrid/sendgrid-go"
	"os"
)

func main() {
	apiKey := os.Getenv("SENDGRID_API_KEY")
	host := "https://api.sendgrid.com"
	request := sendgrid.GetRequest(apiKey, "/v3/mail/batch", host)
	request.Method = "POST"
	response, err := sendgrid.API(request)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	} else {
		fmt.Println(response.StatusCode)
		fmt.Println(response.Body)
		fmt.Println(response.Headers)
	}
}
```

```php
<?php
// Uncomment the next line if you're using a dependency loader (such as Composer) (recommended)
// require 'vendor/autoload.php';

// Uncomment next line if you're not using a dependency loader (such as Composer)
// require_once '<PATH TO>/sendgrid-php.php';

$apiKey = getenv("SENDGRID_API_KEY");
$sg = new \SendGrid($apiKey);

try {
    $response = $sg->client
        ->mail()
        ->batch()
        ->post();
    print $response->statusCode() . "\n";
    print_r($response->headers());
    print $response->body() . "\n";
} catch (Exception $ex) {
    echo "Caught exception: " . $ex->getMessage();
}
```

```ruby
require 'sendgrid-ruby'
include SendGrid

sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])

response = sg.client.mail.batch.post()
puts response.status_code
puts response.headers
puts response.body
```

```bash
curl -X POST "https://api.sendgrid.com/v3/mail/batch" \
--header "Authorization: Bearer $SENDGRID_API_KEY"
```
