# Batch

The `Batch` object allows you to perform operations on multiple `Shipments` at once.
This includes scheduling a `Pickup`, creating a `ScanForm`, and consolidating labels.
Operations performed on `Batches` are asynchronous and take advantage of our webhook infrastructure.

---

## Batch object

| Property | Type | Description |
|----------|------|-------------|
| id | string | Unique, begins with "batch_" |
| reference | string | An optional field that may be used in place of ID in some API endpoints |
| object | string | "Batch" |
| state | string | The overall state. Possible values: "creating" "creation_failed" "created" "purchasing" "purchase_failed" "purchased" "label_generating" "label_generated" |
| num_shipments | integer | The number of shipments added |
| shipments | BatchShipment array | An array of batch shipments |
| status | object | A map of statuses to the count of BatchShipment objects with that status. Valid statuses: "postage_purchased" "postage_purchase_failed" "queued_for_purchase" "creation_failed" |
| label_url | string | The label image URL |
| scan_form | ScanForm | The created ScanForm |
| pickup | Pickup | The created Pickup |
| created_at | datetime | When the Batch was created |
| updated_at | datetime | When the Batch was last updated |

Example Object:

```json
{
  "id": "batch_b148b3715785487597be3f3c56f04884",
  "object": "Batch",
  "mode": "test",
  "state": "creating",
  "num_shipments": 1,
  "reference": null,
  "created_at": "2025-05-09T20:38:21Z",
  "updated_at": "2025-05-09T20:38:21Z",
  "scan_form": null,
  "shipments": [],
  "status": {
    "created": 0,
    "queued_for_purchase": 0,
    "creation_failed": 0,
    "postage_purchased": 0,
    "postage_purchase_failed": 0
  },
  "pickup": null,
  "label_url": null
}
```

---

## BatchShipment object

| Property | Type | Description |
|----------|------|-------------|
| id | string | The id of the Shipment. Unique, begins with "shp_" |
| reference | string | An optional field that may be used in place of ID in some API endpoints |
| batch_status | string | The current status. Possible values are "postage_purchased", "postage_purchase_failed", "queued_for_purchase", and "creation_failed" |
| batch_message | string | A human readable message for any errors that occurred during the Batch's life cycle |

Example Object:

```json
{
  "id": "batch_9c0d5626d0fd4b90868dbaaf4cc147cc",
  "object": "Batch",
  "mode": "test",
  "state": "creating",
  "num_shipments": 1,
  "reference": null,
  "created_at": "2025-05-09T20:38:21Z",
  "updated_at": "2025-05-09T20:38:21Z",
  "scan_form": null,
  "shipments": [
    {
      "batch_status": "created",
      "batch_message": null,
      "reference": null,
      "tracking_code": null,
      "id": "shp_309a07be648b4df59ee7a85a2c2ed64f"
    }
  ],
  "status": {
    "created": 1,
    "queued_for_purchase": 0,
    "creation_failed": 0,
    "postage_purchased": 0,
    "postage_purchase_failed": 0
  },
  "pickup": null,
  "label_url": null
}
```

---

## Create a Batch

### Example: POST /batches

#### cURL

```shell
curl -X POST https://api.easypost.com/v2/batches \
  -u "EASYPOST_API_KEY": \
  -H 'Content-Type: application/json' \
  -d '{
    "batch": {
      "shipments": [
        {
          "id": "shp_..."
        },
        {
          "id": "shp_..."
        }
      ]
    }
  }'
```

#### Go

```go
package example

import (
	"fmt"

	"github.com/EasyPost/easypost-go/v5"
)

func create() {
	client := easypost.New("EASYPOST_API_KEY")

	shipment, _ := client.GetShipment("shp_...")

	batch, _ := client.CreateBatch(shipment)

	fmt.Println(batch)
}
```

#### Java

```java
package batches;

import com.easypost.exception.EasyPostException;
import com.easypost.model.Batch;
import com.easypost.service.EasyPostClient;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Create {
    public static void main(String[] args) throws EasyPostException {
        EasyPostClient client = new EasyPostClient("EASYPOST_API_KEY");

        List<HashMap<String, Object>> shipmentsList = new ArrayList<HashMap<String, Object>>();
        HashMap<String, Object> shipmentMap = new HashMap<String, Object>();

        shipmentMap.put("id", "shp_...");

        shipmentsList.add(shipmentMap);

        HashMap<String, Object> params = new HashMap<String, Object>();

        params.put("shipment", shipmentsList);

        Batch batch = client.batch.create(params);

        System.out.println(batch);
    }
}
```

#### C#

```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using EasyPost;
using Newtonsoft.Json;

namespace EasyPostExamples
{
    public class Examples
    {
        public static async Task Main()
        {
            var client = new EasyPost.Client(new EasyPost.ClientConfiguration("EASYPOST_API_KEY"));

            EasyPost.Models.API.Shipment shipment = await client.Shipment.Retrieve("shp_...");

            EasyPost.Parameters.Batch.Create parameters = new()
            {
                Shipments = new List<EasyPost.Parameters.IShipmentParameter>()
                {
                    shipment
                }
            };

            EasyPost.Models.API.Batch batch = await client.Batch.Create(parameters);

            Console.WriteLine(JsonConvert.SerializeObject(batch, Formatting.Indented));
        }
    }
}
```

#### Node.js

```javascript
const EasyPostClient = require('@easypost/api');

const client = new EasyPostClient('EASYPOST_API_KEY');

(async () => {
  const batch = await client.Batch.create({
    shipments: [{ id: 'shp_...' }, { id: 'shp_...' }],
  });

  console.log(batch);
})();
```

#### PHP

```php
<?php

$client = new \EasyPost\EasyPostClient('EASYPOST_API_KEY');

$batch = $client->batch->create([
    'shipments' => [
        ['id' => 'shp_...'],
        ['id' => 'shp_...'],
    ]
]);

echo $batch;
```

#### Python

```python
import easypost

client = easypost.EasyPostClient("EASYPOST_API_KEY")

batch = client.batch.create(
    shipments=[
        {"id": "shp_..."},
        {"id": "shp_..."},
    ],
)

print(batch)
```

#### Ruby

```ruby
require 'easypost'

client = EasyPost::Client.new(api_key: 'EASYPOST_API_KEY')

batch = client.batch.create(
  shipments: [
    { id: 'shp_...' },
    { id: 'shp_...' },
  ],
)

puts batch
```

A `Batch` can be created with or without `Shipments`.
When created with `Shipments`, the initial `state` will be "creating".
Once the `state` changes to "created", a webhook `Event` will be sent.
When created with no `Shipments`, the initial state will be "created" and webhook will be sent.

> Note: It is recommended to keep each batch under 1,000 shipments. This best practice helps avoid timeout errors
  during the batch buying process.

---

## Add Shipments to a Batch

### Example: POST /batches/:id/add_shipments

#### cURL

```shell
curl -X POST https://api.easypost.com/v2/batches/batch_.../add_shipments \
  -u "EASYPOST_API_KEY": \
  -H 'Content-Type: application/json' \
  -d '{
    "shipments": [
      {
        "id": "shp_..."
      },
      {
        "id": "shp_..."
      }
    ]
  }'
```

#### Go

```go
package example

import (
	"fmt"

	"github.com/EasyPost/easypost-go/v5"
)

func addShipments() {
	client := easypost.New("EASYPOST_API_KEY")

	shipment, _ := client.GetShipment("shp_...")

	batch, _ := client.AddShipmentsToBatch("batch_...", shipment)

	fmt.Println(batch)
}
```

#### Java

```java
package batches;

import com.easypost.exception.EasyPostException;
import com.easypost.model.Batch;
import com.easypost.service.EasyPostClient;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class AddShipments {
    public static void main(String[] args) throws EasyPostException {
        EasyPostClient client = new EasyPostClient("EASYPOST_API_KEY");

        HashMap<String, Object> shipment1 = new HashMap<String, Object>();
        shipment1.put("id", "shp_...");

        HashMap<String, Object> shipment2 = new HashMap<String, Object>();
        shipment2.put("id", "shp_...");

        List<HashMap<String, Object>> shipments = new ArrayList<HashMap<String, Object>>();
        shipments.add(shipment1);
        shipments.add(shipment2);

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("shipments", shipments);

        Batch batch = client.batch.addShipments("batch_...", params);

        System.out.println(batch);
    }
}
```

#### C#

```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using EasyPost;
using Newtonsoft.Json;

namespace EasyPostExamples
{
    public class Examples
    {
        public static async Task Main()
        {
            var client = new EasyPost.Client(new EasyPost.ClientConfiguration("EASYPOST_API_KEY"));

            EasyPost.Models.API.Shipment shipment = await client.Shipment.Retrieve("shp_...");

            EasyPost.Parameters.Batch.AddShipments parameters = new()
            {
                Shipments = new List<Models.API.Shipment> { shipment },
            };

            EasyPost.Models.API.Batch batch = await client.Batch.AddShipments("batch_...", parameters);

            Console.WriteLine(JsonConvert.SerializeObject(batch, Formatting.Indented));
        }
    }
}
```

#### Node.js

```javascript
const EasyPostClient = require('@easypost/api');

const client = new EasyPostClient('EASYPOST_API_KEY');

(async () => {
  const batch = await client.Batch.addShipments('batch_...', ['shp_...', 'shp_...']);

  console.log(batch);
})();
```

#### PHP

```php
<?php

$client = new \EasyPost\EasyPostClient('EASYPOST_API_KEY');

$batch = $client->batch->addShipments(
    'batch_...',
    [
        'shipments' => [
            ['id' => 'shp_...'],
            ['id' => 'shp_...'],
        ]
    ]
);

echo $batch;
```

#### Python

```python
import easypost

client = easypost.EasyPostClient("EASYPOST_API_KEY")

batch = client.batch.add_shipments(
    "batch_...",
    shipments=[
        {"id": "shp_..."},
        {"id": "shp_..."},
    ],
)

print(batch)
```

#### Ruby

```ruby
require 'easypost'

client = EasyPost::Client.new(api_key: 'EASYPOST_API_KEY')

batch = client.batch.add_shipments(
  'batch_...',
  shipments: [
    { id: 'shp_...' },
    { id: 'shp_...' },
  ],
)

puts batch
```

Shipments can be added to a `Batch` throughout its life cycle. Just remember that the
state change of a `Batch` is asynchronous and will fire a webhook Event when the state change
is completed.

---

## Remove Shipments from a Batch

### Example: POST /batches/:id/remove_shipments

#### cURL

```shell
curl -X POST https://api.easypost.com/v2/batches/batch_.../remove_shipments \
  -u "EASYPOST_API_KEY": \
  -H 'Content-Type: application/json' \
  -d '{
    "shipments": [
      {
        "id": "shp_..."
      }
    ]
  }'
```

#### Go

```go
package example

import (
	"fmt"

	"github.com/EasyPost/easypost-go/v5"
)

func removeShipments() {
	client := easypost.New("EASYPOST_API_KEY")

	shipment, _ := client.GetShipment("shp_...")

	batch, _ := client.RemoveShipmentsFromBatch("batch_...", shipment)

	fmt.Println(batch)
}
```

#### Java

```java
package batches;

import com.easypost.exception.EasyPostException;
import com.easypost.model.Batch;
import com.easypost.service.EasyPostClient;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class RemoveShipments {
    public static void main(String[] args) throws EasyPostException {
        EasyPostClient client = new EasyPostClient("EASYPOST_API_KEY");

        HashMap<String, Object> shipment1 = new HashMap<String, Object>();
        shipment1.put("id", "shp_...");

        List<HashMap<String, Object>> shipments = new ArrayList<HashMap<String, Object>>();
        shipments.add(shipment1);

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("shipments", shipments);

        Batch batch = client.batch.removeShipments("batch_...", params);

        System.out.println(batch);
    }
}
```

#### C#

```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using EasyPost;
using Newtonsoft.Json;

namespace EasyPostExamples
{
    public class Examples
    {
        public static async Task Main()
        {
            var client = new EasyPost.Client(new EasyPost.ClientConfiguration("EASYPOST_API_KEY"));

            EasyPost.Models.API.Shipment shipment = await client.Shipment.Retrieve("shp_...");

            EasyPost.Parameters.Batch.RemoveShipments parameters = new()
            {
                Shipments = new List<Models.API.Shipment> { shipment },
            };

            EasyPost.Models.API.Batch batch = await client.Batch.RemoveShipments("batch_...", parameters);

            Console.WriteLine(JsonConvert.SerializeObject(batch, Formatting.Indented));
        }
    }
}
```

#### Node.js

```javascript
const EasyPostClient = require('@easypost/api');

const client = new EasyPostClient('EASYPOST_API_KEY');

(async () => {
  const batch = await client.Batch.removeShipments('batch_...', ['shp_...']);

  console.log(batch);
})();
```

#### PHP

```php
<?php

$client = new \EasyPost\EasyPostClient('EASYPOST_API_KEY');

$batch = $client->batch->removeShipments(
    'batch_...',
    [
        'shipments' => [
            ['id' => 'shp_...']
        ]
    ]
);

echo $batch;
```

#### Python

```python
import easypost

client = easypost.EasyPostClient("EASYPOST_API_KEY")

batch = batch.remove_shipments(
    "batch_...",
    shipments=[
        {
            "id": "shp_...",
        }
    ],
)

print(batch)
```

#### Ruby

```ruby
require 'easypost'

client = EasyPost::Client.new(api_key: 'EASYPOST_API_KEY')

batch = client.batch.remove_shipments(
  'batch_...',
  shipments: [
    { id: 'shp_...' },
  ],
)

puts batch
```

There could be times when a `Shipment` needs to be removed from the `Batch` during its life cycle.
Removing a `Shipment` does not remove it from the consolidated label or `ScanForm`.

---

## Buy a Batch

### Example: POST /batches/:id/buy

#### cURL

```shell
curl -X POST https://api.easypost.com/v2/batches \
  -u "EASYPOST_API_KEY": \
  -H 'Content-Type: application/json' \
  -d '{
    "batch": {
      "shipments": [
        "from_address": {"id": "adr_..."},
        "to_address": {"id": "adr_..."},
        "parcel": {"id": "prcl_..."},
        "service": "First",
        "carrier": "USPS",
        "carrier_accounts": ["ca_..."]
      ]
    }
  }'

curl -X POST https://api.easypost.com/v2/batches/batch_.../buy \
  -u "EASYPOST_API_KEY":
```

#### Go

```go
package example

import (
	"fmt"

	"github.com/EasyPost/easypost-go/v5"
)

func buy() {
	client := easypost.New("EASYPOST_API_KEY")

	createdBatch, _ := client.CreateBatch(
		&easypost.Shipment{
			FromAddress: &easypost.Address{
				ID: "adr_...",
			},
			ToAddress: &easypost.Address{
				ID: "adr_...",
			},
			Parcel: &easypost.Parcel{
				ID: "prcl_...",
			},
			Service:           "First",
			Carrier:           "USPS",
			CarrierAccountIDs: []string{"ca_..."},
		},
	)

	batch, _ := client.BuyBatch(createdBatch.ID)

	fmt.Println(batch)
}
```

#### Java

```java
package batches;

import com.easypost.exception.EasyPostException;
import com.easypost.model.Batch;
import com.easypost.service.EasyPostClient;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Buy {
    public static void main(String[] args) throws EasyPostException {
        EasyPostClient client = new EasyPostClient("EASYPOST_API_KEY");

        List<HashMap<String, Object>> shipmentsList = new ArrayList<HashMap<String, Object>>();
        HashMap<String, Object> shipmentMap = new HashMap<String, Object>();

        HashMap<String, Object> fromAddress = new HashMap<String, Object>();
        fromAddress.put("id", "adr_...");
        shipmentMap.put("from_address", fromAddress);

        HashMap<String, Object> toAddress = new HashMap<String, Object>();
        toAddress.put("id", "adr_...");
        shipmentMap.put("to_address", toAddress);

        HashMap<String, Object> parcel = new HashMap<String, Object>();
        parcel.put("id", "prcl_...");
        shipmentMap.put("parcel", parcel);

        shipmentMap.put("service", "First");
        shipmentMap.put("carrier", "USPS");

        String[] carrierAccounts = { "ca_..." };
        shipmentMap.put("carrier_accounts", carrierAccounts);

        shipmentsList.add(shipmentMap);

        HashMap<String, Object> params = new HashMap<String, Object>();

        params.put("shipment", shipmentsList);

        Batch createdBatch = client.batch.create(params);

        Batch batch = client.batch.buy(createdBatch.getId());

        System.out.println(batch);
    }
}
```

#### C#

```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using EasyPost;
using Newtonsoft.Json;

namespace EasyPostExamples
{
    public class Examples
    {
        public static async Task Main()
        {
            var client = new EasyPost.Client(new EasyPost.ClientConfiguration("EASYPOST_API_KEY"));

            EasyPost.Parameters.Shipment.Create shipmentParameters = new()
            {
                ToAddress = new EasyPost.Parameters.Address.Create
                {
                    Id = "adr_..."
                },
                FromAddress = new EasyPost.Parameters.Address.Create
                {
                    Id = "adr_..."
                },
                Parcel = new EasyPost.Parameters.Parcel.Create
                {
                    Id = "prcl_..."
                },
                Service = "First",
                Carrier = "USPS",
                CarrierAccountIds = new List<string> { "ca_..." }
            };

            EasyPost.Parameters.Batch.Create parameters = new()
            {
                Shipments = new List<EasyPost.Parameters.IShipmentParameter>()
                {
                    shipmentParameters
                }
            };

            EasyPost.Models.API.Batch batch = await client.Batch.Create(parameters);

            EasyPost.Models.API.Batch batch = await client.Batch.Buy(batch.Id);

            Console.WriteLine(JsonConvert.SerializeObject(batch, Formatting.Indented));
        }
    }
}
```

#### Node.js

```javascript
const EasyPostClient = require('@easypost/api');

const client = new EasyPostClient('EASYPOST_API_KEY');

(async () => {
  const createdBatch = await client.Batch.create({
    shipments: [
      {
        from_address: { id: 'adr_...' },
        to_address: { id: 'adr_...' },
        parcel: { id: 'prcl_...' },
        service: 'First',
        carrier: 'USPS',
        carrier_accounts: ['ca_...'],
      },
    ],
  });

  const batch = await client.Batch.buy(createdBatch.id);

  console.log(batch);
})();
```

#### PHP

```php
<?php

$client = new \EasyPost\EasyPostClient('EASYPOST_API_KEY');

$createdBatch = $client->batch->create([
    'shipments' => [
        ['from_address' => ['id' => 'adr_...']],
        ['to_address' => ['id' => 'adr_...']],
        ['parcel' => ['id' => 'prcl_...']],
        ['service' => 'First'],
        ['carrier' => 'USPS'],
        ['carrier_accounts' => ['ca_...']],
    ]
]);

$batch = $client->batch->buy($createdBatch['id']);

echo $batch;
```

#### Python

```python
import easypost

client = easypost.EasyPostClient("EASYPOST_API_KEY")

createdBatch = client.batch.create(
    shipments=[
        {
            "from_address": {"id": "adr_..."},
            "to_address": {"id": "adr_..."},
            "parcel": {"id": "prcl_..."},
            "service": "First",
            "carrier": "USPS",
            "carrier_accounts": ["ca_..."],
        },
    ],
)

batch = client.batch.buy(createdBatch.id)

print(batch)
```

#### Ruby

```ruby
require 'easypost'

client = EasyPost::Client.new(api_key: 'EASYPOST_API_KEY')

created_batch = client.batch.create(
  shipments: [
    {
      from_address: { id: 'adr_...' },
      to_address: { id: 'adr_...' },
      parcel: { id: 'prcl_...' },
      service: 'First',
      carrier: 'USPS',
      carrier_accounts: ['ca_...'],
    },
  ],
)

batch = client.batch.buy(created_batch.id)

puts batch
```

Once you have added all of your `Shipments` to a `Batch`, issue a buy request to enqueue a background job to purchase the shipments and generate all necessary labels.

**Batch Buying Criteria:** To buy a batch, all shipment data must be passed to the batch at the same time the batch is created. Each shipment of a batch **must have** a `from_address`, `to_address`, `parcel`, `service`, `carrier`, and `carrier_accounts` array with the single carrier account ID associated with the service.

Purchasing may take anywhere from a few seconds to an hour, depending on the size of the batch, the carrier, and Internet weather.

---

## Batch Labels

### Example: POST /batches/:id/label

#### cURL

```shell
curl -X POST https://api.easypost.com/v2/batches/batch_.../label \
  -u "EASYPOST_API_KEY": \
  -H 'Content-Type: application/json' \
  -d '{
    "file_format": "PDF"
  }'
```

#### Go

```go
package example

import (
	"fmt"

	"github.com/EasyPost/easypost-go/v5"
)

func label() {
	client := easypost.New("EASYPOST_API_KEY")

	batch, _ := client.GetBatchLabels("batch_...", "PDF")

	fmt.Println(batch)
}
```

#### Java

```java
package batches;

import com.easypost.exception.EasyPostException;
import com.easypost.model.Batch;
import com.easypost.service.EasyPostClient;

import java.util.HashMap;

public class Label {
    public static void main(String[] args) throws EasyPostException {
        EasyPostClient client = new EasyPostClient("EASYPOST_API_KEY");

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("file_format", "PDF");

        Batch batch = client.batch.label("batch_...", params);

        System.out.println(batch);
    }
}
```

#### C#

```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using EasyPost;
using Newtonsoft.Json;

namespace EasyPostExamples
{
    public class Examples
    {
        public static async Task Main()
        {
            var client = new EasyPost.Client(new EasyPost.ClientConfiguration("EASYPOST_API_KEY"));

            EasyPost.Parameters.Batch.GenerateLabel parameters = new()
            {
                FileFormat = "PDF",
            };

            EasyPost.Models.API.Batch batch = await client.Batch.GenerateLabel("batch_...", parameters);

            Console.WriteLine(JsonConvert.SerializeObject(batch, Formatting.Indented));
        }
    }
}
```

#### Node.js

```javascript
const EasyPostClient = require('@easypost/api');

const client = new EasyPostClient('EASYPOST_API_KEY');

(async () => {
  const batch = await client.Batch.generateLabel('batch_...', 'PDF');

  console.log(batch);
})();
```

#### PHP

```php
<?php

$client = new \EasyPost\EasyPostClient('EASYPOST_API_KEY');

$batchWithLabel = $client->batch->label(
    'batch_...',
    ['file_format' => 'PDF']
);

echo $batchWithLabel;
```

#### Python

```python
import easypost

client = easypost.EasyPostClient("EASYPOST_API_KEY")

batch = client.batch.label("batch_...", file_format="PDF")

print(batch)
```

#### Ruby

```ruby
require 'easypost'

client = EasyPost::Client.new(api_key: 'EASYPOST_API_KEY')

batch = client.batch.label(
  'batch_...',
  file_format: 'PDF',
)

puts batch
```

One of the advantages of processing `Shipments` in batches is the ability to consolidate the `PostageLabel` into one file.
This can only be done once for each batch and all `Shipments` must have a status of "postage_purchased".

Available label formats are "PDF", "ZPL" and "EPL2". Like converting a `PostageLabel` format, if this process will change the format of the labels, they must have been created as PNG files.

---

## Manifesting (Scan Form)

### Example: POST /batches/:id/scan_form

#### cURL

```shell
curl -X POST https://api.easypost.com/v2/batches/batch_.../scan_form \
  -u "EASYPOST_API_KEY":
```

#### Go

```go
package example

import (
	"fmt"

	"github.com/EasyPost/easypost-go/v5"
)

func scanForms() {
	client := easypost.New("EASYPOST_API_KEY")

	batch, _ := client.CreateBatchScanForms("batch_...", "pdf")

	fmt.Println(batch)
}
```

#### Java

```java
package batches;

import com.easypost.exception.EasyPostException;
import com.easypost.model.Batch;
import com.easypost.service.EasyPostClient;

public class ScanForms {
    public static void main(String[] args) throws EasyPostException {
        EasyPostClient client = new EasyPostClient("EASYPOST_API_KEY");

        Batch batch = client.batch.createScanForm("batch_...");

        System.out.println(batch);
    }
}
```

#### C#

```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using EasyPost;
using Newtonsoft.Json;

namespace EasyPostExamples
{
    public class Examples
    {
        public static async Task Main()
        {
            var client = new EasyPost.Client(new EasyPost.ClientConfiguration("EASYPOST_API_KEY"));

            EasyPost.Parameters.Batch.GenerateScanForm parameters = new()
            {
                FileFormat = "ZPL",
            };

            EasyPost.Models.API.Batch batch = await client.Batch.GenerateScanForm("batch_...", parameters);

            Console.WriteLine(JsonConvert.SerializeObject(batch, Formatting.Indented));
        }
    }
}
```

#### Node.js

```javascript
const EasyPostClient = require('@easypost/api');

const client = new EasyPostClient('EASYPOST_API_KEY');

(async () => {
  const batch = await client.Batch.createScanForm('batch_...');

  console.log(batch);
})();
```

#### PHP

```php
<?php

$client = new \EasyPost\EasyPostClient('EASYPOST_API_KEY');

$batch = $client->batch->createScanForm('batch_...');

echo $batch;
```

#### Python

```python
import easypost

client = easypost.EasyPostClient("EASYPOST_API_KEY")

batch = client.batch.create_scan_form("batch_...")

print(batch)
```

#### Ruby

```ruby
require 'easypost'

client = EasyPost::Client.new(api_key: 'EASYPOST_API_KEY')

batch = client.batch.create_scan_form('batch_...')

puts batch
```

A `ScanForm` can be created for a `Batch` by its `id`.

---

## Retrieve all Batches

### Example: GET /batches

#### cURL

```shell
curl -X GET "https://api.easypost.com/v2/batches?page_size=5" \
  -u "EASYPOST_API_KEY":
```

#### Go

```go
package example

import (
	"fmt"

	"github.com/EasyPost/easypost-go/v5"
)

func list() {
	client := easypost.New("EASYPOST_API_KEY")

	batches, _ := client.ListBatches(
		&easypost.ListOptions{
			PageSize: 5,
		},
	)

	fmt.Println(batches)
}
```

#### Java

```java
package batches;

import com.easypost.exception.EasyPostException;
import com.easypost.model.BatchCollection;
import com.easypost.service.EasyPostClient;

import java.util.HashMap;

public class All {
    public static void main(String[] args) throws EasyPostException {
        EasyPostClient client = new EasyPostClient("EASYPOST_API_KEY");

        HashMap<String, Object> params = new HashMap<>();
        params.put("page_size", 5);

        BatchCollection batches = client.batch.all(params);

        System.out.println(batches);
    }
}
```

#### C#

```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using EasyPost;
using Newtonsoft.Json;

namespace EasyPostExamples
{
    public class Examples
    {
        public static async Task Main()
        {
            var client = new EasyPost.Client(new EasyPost.ClientConfiguration("EASYPOST_API_KEY"));

            EasyPost.Parameters.Batch.All parameters = new()
            {
                PageSize = 5
            };

            EasyPost.Models.API.BatchCollection batchCollection = await client.Batch.All(parameters);

            Console.WriteLine(JsonConvert.SerializeObject(batchCollection, Formatting.Indented));
        }
    }
}
```

#### Node.js

```javascript
const EasyPostClient = require('@easypost/api');

const client = new EasyPostClient('EASYPOST_API_KEY');

(async () => {
  const batches = await client.Batch.all({ page_size: 5 });

  console.log(batches);
})();
```

#### PHP

```php
<?php

$client = new \EasyPost\EasyPostClient('EASYPOST_API_KEY');

$batches = $client->batch->all([
    'page_size' => 5,
]);

echo $batches;
```

#### Python

```python
import easypost

client = easypost.EasyPostClient("EASYPOST_API_KEY")

batches = client.batch.all(page_size=5)

print(batches)
```

#### Ruby

```ruby
require 'easypost'

client = EasyPost::Client.new(api_key: 'EASYPOST_API_KEY')

batches = client.batch.all(
  page_size: 5,
)

puts batches
```

A list of all `Batch` objects associated with the given `API Key` can also be retrieved.
See the Pagination section of our docs for more details on retrieving all records when multiple pages are available.

---

## Retrieve Batch

### Example: GET /batches/:id

#### cURL

```shell
curl -X GET https://api.easypost.com/v2/batches/batch_... \
  -u "EASYPOST_API_KEY":
```

#### Go

```go
package example

import (
	"fmt"

	"github.com/EasyPost/easypost-go/v5"
)

func retrieve() {
	client := easypost.New("EASYPOST_API_KEY")

	batch, _ := client.GetBatch("batch_...")

	fmt.Println(batch)
}
```

#### Java

```java
package batches;

import com.easypost.exception.EasyPostException;
import com.easypost.model.Batch;
import com.easypost.service.EasyPostClient;

public class Retrieve {
    public static void main(String[] args) throws EasyPostException {
        EasyPostClient client = new EasyPostClient("EASYPOST_API_KEY");

        Batch batch = client.batch.retrieve("batch_...");

        System.out.println(batch);
    }
}
```

#### C#

```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using EasyPost;
using Newtonsoft.Json;

namespace EasyPostExamples
{
    public class Examples
    {
        public static async Task Main()
        {
            var client = new EasyPost.Client(new EasyPost.ClientConfiguration("EASYPOST_API_KEY"));

            Batch batch = await client.Batch.Retrieve("batch_...");

            Console.WriteLine(JsonConvert.SerializeObject(batch, Formatting.Indented));
        }
    }
}
```

#### Node.js

```javascript
const EasyPostClient = require('@easypost/api');

const client = new EasyPostClient('EASYPOST_API_KEY');

(async () => {
  const batch = await client.Batch.retrieve('batch_...');

  console.log(batch);
})();
```

#### PHP

```php
<?php

$client = new \EasyPost\EasyPostClient('EASYPOST_API_KEY');

$batch = $client->batch->retrieve('batch_...');

echo $batch;
```

#### Python

```python
import easypost

client = easypost.EasyPostClient("EASYPOST_API_KEY")

batch = client.batch.retrieve("batch_...")

print(batch)
```

#### Ruby

```ruby
require 'easypost'

client = EasyPost::Client.new(api_key: 'EASYPOST_API_KEY')

batch = client.batch.retrieve('batch_...')

puts batch
```

A `Batch` can be retrieved by either its `id` or `reference`.
However it is recommended to use EasyPost's provided identifiers because uniqueness on `reference` is not enforced.