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

# Data Exports

> Export your messaging data for analysis, compliance, or backup purposes

Data exports allow you to download your messaging data in bulk for analysis, compliance audits, or backup purposes. Export links are valid for 24 hours after generation.

## Exportable Data Types

| Data Type           | Description                                         |
| ------------------- | --------------------------------------------------- |
| `messages`          | All sent and received messages with delivery status |
| `conversations`     | Conversation threads grouped by contact             |
| `webhookDeliveries` | Webhook delivery attempts and responses             |
| `agentExecutions`   | AI agent execution logs and responses               |
| `activities`        | Account activity and audit logs                     |

## Creating an Export

<CodeGroup>
  ```typescript TypeScript theme={null}
  import Zavudev from '@zavudev/sdk';

  const zavu = new Zavudev();

  const exportJob = await zavu.exports.create({
    dataTypes: ["messages", "conversations"],
    dateFrom: "2024-01-01T00:00:00Z",
    dateTo: "2024-12-31T23:59:59Z",
  });

  console.log(`Export ID: ${exportJob.id}`);
  console.log(`Status: ${exportJob.status}`); // "pending"
  ```

  ```python Python theme={null}
  from zavudev import Zavudev

  zavu = Zavudev()

  export_job = zavu.exports.create(
      data_types=["messages", "conversations"],
      date_from="2024-01-01T00:00:00Z",
      date_to="2024-12-31T23:59:59Z"
  )

  print(f"Export ID: {export_job.id}")
  print(f"Status: {export_job.status}")  # "pending"
  ```

  ```ruby Ruby theme={null}
  require "zavudev"

  client = Zavudev::Client.new(api_key: ENV["ZAVUDEV_API_KEY"])

  export_job = client.exports.create(
    data_types: ["messages", "conversations"],
    date_from: "2024-01-01T00:00:00Z",
    date_to: "2024-12-31T23:59:59Z"
  )

  puts "Export ID: #{export_job.id}"
  puts "Status: #{export_job.status}" # "pending"
  ```

  ```go Go theme={null}
  client := zavudev.NewClient(zavudev.WithAPIKey(os.Getenv("ZAVUDEV_API_KEY")))

  exportJob, _ := client.Exports.Create(context.TODO(), zavudev.ExportCreateParams{
  	DataTypes: []string{"messages", "conversations"},
  	DateFrom:  zavudev.String("2024-01-01T00:00:00Z"),
  	DateTo:    zavudev.String("2024-12-31T23:59:59Z"),
  })

  fmt.Printf("Export ID: %s\n", exportJob.ID)
  fmt.Printf("Status: %s\n", exportJob.Status) // "pending"
  ```

  ```php PHP theme={null}
  $client = new Zavudev\Client(apiKey: getenv('ZAVUDEV_API_KEY'));

  $exportJob = $client->exports->create([
      'dataTypes' => ['messages', 'conversations'],
      'dateFrom' => '2024-01-01T00:00:00Z',
      'dateTo' => '2024-12-31T23:59:59Z',
  ]);

  echo "Export ID: {$exportJob->id}\n";
  echo "Status: {$exportJob->status}\n"; // "pending"
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.zavu.dev/v1/exports \
    -H "Authorization: Bearer $ZAVU_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "dataTypes": ["messages", "conversations"],
      "dateFrom": "2024-01-01T00:00:00Z",
      "dateTo": "2024-12-31T23:59:59Z"
    }'
  ```
</CodeGroup>

### Response

```json theme={null}
{
  "export": {
    "id": "exp_abc123",
    "status": "pending",
    "dataTypes": ["messages", "conversations"],
    "dateFrom": "2024-01-01T00:00:00.000Z",
    "dateTo": "2024-12-31T23:59:59.000Z",
    "expiresAt": "2024-01-16T10:30:00.000Z",
    "createdAt": "2024-01-15T10:30:00.000Z"
  }
}
```

## Export Status

| Status       | Description                                 |
| ------------ | ------------------------------------------- |
| `pending`    | Export job created, waiting to be processed |
| `processing` | Export is being generated                   |
| `completed`  | Export ready for download                   |
| `failed`     | Export failed (check `errorMessage`)        |

## Checking Export Status

Exports are processed asynchronously. Poll the status until it's `completed`:

<CodeGroup>
  ```typescript TypeScript theme={null}
  async function waitForExport(exportId: string) {
    let exportJob;

    do {
      await new Promise(r => setTimeout(r, 5000)); // Wait 5 seconds
      exportJob = await zavu.exports.get(exportId);
      console.log(`Status: ${exportJob.status}`);
    } while (exportJob.status === "pending" || exportJob.status === "processing");

    if (exportJob.status === "completed") {
      console.log(`Download URL: ${exportJob.downloadUrl}`);
      console.log(`File size: ${exportJob.fileSize} bytes`);
    } else {
      console.error(`Export failed: ${exportJob.errorMessage}`);
    }

    return exportJob;
  }
  ```

  ```python Python theme={null}
  import time

  def wait_for_export(export_id: str):
      while True:
          time.sleep(5)  # Wait 5 seconds
          export_job = zavu.exports.get(export_id)
          print(f"Status: {export_job.status}")

          if export_job.status not in ["pending", "processing"]:
              break

      if export_job.status == "completed":
          print(f"Download URL: {export_job.download_url}")
          print(f"File size: {export_job.file_size} bytes")
      else:
          print(f"Export failed: {export_job.error_message}")

      return export_job
  ```

  ```ruby Ruby theme={null}
  def wait_for_export(export_id)
    loop do
      sleep 5 # Wait 5 seconds
      export_job = client.exports.get(export_id)
      puts "Status: #{export_job.status}"

      break unless ["pending", "processing"].include?(export_job.status)
    end

    if export_job.status == "completed"
      puts "Download URL: #{export_job.download_url}"
      puts "File size: #{export_job.file_size} bytes"
    else
      puts "Export failed: #{export_job.error_message}"
    end

    export_job
  end
  ```

  ```go Go theme={null}
  func waitForExport(client *zavudev.Client, exportID string) {
  	for {
  		time.Sleep(5 * time.Second)
  		exportJob, _ := client.Exports.Get(context.TODO(), exportID)
  		fmt.Println("Status:", exportJob.Status)

  		if exportJob.Status != "pending" && exportJob.Status != "processing" {
  			if exportJob.Status == "completed" {
  				fmt.Println("Download URL:", exportJob.DownloadURL)
  				fmt.Println("File size:", exportJob.FileSize, "bytes")
  			} else {
  				fmt.Println("Export failed:", exportJob.ErrorMessage)
  			}
  			break
  		}
  	}
  }
  ```

  ```php PHP theme={null}
  function waitForExport($client, string $exportId) {
      do {
          sleep(5); // Wait 5 seconds
          $exportJob = $client->exports->get($exportId);
          echo "Status: {$exportJob->status}\n";
      } while (in_array($exportJob->status, ['pending', 'processing']));

      if ($exportJob->status === 'completed') {
          echo "Download URL: {$exportJob->downloadUrl}\n";
          echo "File size: {$exportJob->fileSize} bytes\n";
      } else {
          echo "Export failed: {$exportJob->errorMessage}\n";
      }

      return $exportJob;
  }
  ```

  ```bash cURL theme={null}
  curl https://api.zavu.dev/v1/exports/{exportId} \
    -H "Authorization: Bearer $ZAVU_API_KEY"
  ```
</CodeGroup>

### Completed Export Response

```json theme={null}
{
  "export": {
    "id": "exp_abc123",
    "status": "completed",
    "dataTypes": ["messages", "conversations"],
    "dateFrom": "2024-01-01T00:00:00.000Z",
    "dateTo": "2024-12-31T23:59:59.000Z",
    "downloadUrl": "https://storage.zavu.dev/exports/exp_abc123.zip?token=...",
    "fileSize": 1048576,
    "expiresAt": "2024-01-16T10:30:00.000Z",
    "completedAt": "2024-01-15T10:32:00.000Z",
    "createdAt": "2024-01-15T10:30:00.000Z"
  }
}
```

## Downloading the Export

Once the export is complete, download the file using the `downloadUrl`:

```typescript theme={null}
import { writeFile } from 'fs/promises';

const exportJob = await zavu.exports.get(exportId);

if (exportJob.downloadUrl) {
  const response = await fetch(exportJob.downloadUrl);
  const buffer = await response.arrayBuffer();
  await writeFile('export.zip', Buffer.from(buffer));
  console.log('Export downloaded successfully!');
}
```

<Warning>
  Download URLs expire 24 hours after the export is created. After expiration, you'll need to create a new export.
</Warning>

## Listing Exports

<CodeGroup>
  ```typescript TypeScript theme={null}
  const { items, nextCursor } = await zavu.exports.list({
    status: "completed",
    limit: 50,
  });

  for (const exportJob of items) {
    console.log(`${exportJob.id}: ${exportJob.status}`);
  }
  ```

  ```python Python theme={null}
  result = zavu.exports.list(
      status="completed",
      limit=50
  )

  for export_job in result.items:
      print(f"{export_job.id}: {export_job.status}")
  ```

  ```ruby Ruby theme={null}
  result = client.exports.list(
    status: "completed",
    limit: 50
  )

  result.items.each do |export_job|
    puts "#{export_job.id}: #{export_job.status}"
  end
  ```

  ```go Go theme={null}
  result, _ := client.Exports.List(context.TODO(), zavudev.ExportListParams{
  	Status: zavudev.String("completed"),
  	Limit:  zavudev.Int(50),
  })

  for _, exportJob := range result.Items {
  	fmt.Printf("%s: %s\n", exportJob.ID, exportJob.Status)
  }
  ```

  ```php PHP theme={null}
  $result = $client->exports->list([
      'status' => 'completed',
      'limit' => 50,
  ]);

  foreach ($result->items as $exportJob) {
      echo "{$exportJob->id}: {$exportJob->status}\n";
  }
  ```

  ```bash cURL theme={null}
  curl "https://api.zavu.dev/v1/exports?status=completed&limit=50" \
    -H "Authorization: Bearer $ZAVU_API_KEY"
  ```
</CodeGroup>

## Export File Format

Exports are delivered as a ZIP file containing JSON files for each data type:

```
export_exp_abc123.zip
├── messages.json
├── conversations.json
└── metadata.json
```

Each JSON file contains an array of records:

```json theme={null}
// messages.json
[
  {
    "id": "msg_abc123",
    "to": "+14155551234",
    "from": "+13125551212",
    "channel": "sms",
    "status": "delivered",
    "text": "Your order has shipped!",
    "createdAt": "2024-01-15T10:30:00.000Z"
  }
]
```

## Date Range Filtering

Use `dateFrom` and `dateTo` to export data from a specific time period:

```typescript theme={null}
// Export last 30 days
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

const exportJob = await zavu.exports.create({
  dataTypes: ["messages"],
  dateFrom: thirtyDaysAgo.toISOString(),
  dateTo: new Date().toISOString(),
});
```

<Info>
  If you omit date filters, the export includes all available data. For large datasets, consider filtering by date to reduce export time.
</Info>

## Use Cases

<CardGroup cols={2}>
  <Card title="Compliance Audits" icon="shield-check">
    Export message logs for regulatory compliance (GDPR, HIPAA, etc.)
  </Card>

  <Card title="Analytics" icon="chart-bar">
    Analyze messaging patterns and delivery rates in your BI tools
  </Card>

  <Card title="Backup" icon="database">
    Create regular backups of your messaging history
  </Card>

  <Card title="Migration" icon="arrow-right-arrow-left">
    Export data when switching platforms or archiving projects
  </Card>
</CardGroup>

## Rate Limits

| Limit              | Value                                                               |
| ------------------ | ------------------------------------------------------------------- |
| Concurrent exports | 3 per project                                                       |
| Export requests    | 10 per hour                                                         |
| Data retention     | Based on your plan (see [Data Retention](/concepts/data-retention)) |

## Complete Example

```typescript theme={null}
import Zavudev from '@zavudev/sdk';
import { writeFile } from 'fs/promises';

const zavu = new Zavudev();

async function exportMessagingData() {
  // 1. Create the export
  const exportJob = await zavu.exports.create({
    dataTypes: ["messages", "conversations", "webhookDeliveries"],
    dateFrom: "2024-01-01T00:00:00Z",
    dateTo: "2024-12-31T23:59:59Z",
  });

  console.log(`Export created: ${exportJob.id}`);

  // 2. Wait for completion
  let status = exportJob.status;
  while (status === "pending" || status === "processing") {
    await new Promise(r => setTimeout(r, 5000));
    const updated = await zavu.exports.get(exportJob.id);
    status = updated.status;
    console.log(`Status: ${status}`);
  }

  // 3. Download if successful
  const completed = await zavu.exports.get(exportJob.id);

  if (completed.status === "completed" && completed.downloadUrl) {
    const response = await fetch(completed.downloadUrl);
    const buffer = await response.arrayBuffer();
    await writeFile(`export_${exportJob.id}.zip`, Buffer.from(buffer));
    console.log(`Downloaded: export_${exportJob.id}.zip (${completed.fileSize} bytes)`);
  } else {
    console.error(`Export failed: ${completed.errorMessage}`);
  }
}

exportMessagingData();
```
