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

# VideoBGRemoverClient - Complete SDK API Reference

> Master the VideoBGRemoverClient SDK for seamless API integration. Learn authentication, credit management, background removal, and error handling.

## Overview

The `VideoBGRemoverClient` handles all communication with the VideoBGRemover API for background removal operations. This is the **API layer** of the SDK - it handles authentication, job management, and credit tracking.

<Info>
  **API Layer**: This class makes HTTP requests to our servers and consumes credits. For local video composition (no credits), see [Composition](/api-reference/sdk-reference/composition).
</Info>

## Constructor

<Tabs group="code-examples">
  <Tab title="Node.js">
    ```typescript theme={"dark"}
    import { VideoBGRemoverClient } from '@videobgremover/sdk'

    // Basic initialization
    const client = new VideoBGRemoverClient('vbr_your_api_key')

    // With custom options
    const client = new VideoBGRemoverClient('vbr_your_api_key', {
      baseUrl: 'https://api.videobgremover.com', // Custom API endpoint
      timeout: 60000, // 60 second timeout
      headers: { 'Custom-Header': 'value' }
    })
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={"dark"}
    from videobgremover import VideoBGRemoverClient

    # Basic initialization
    client = VideoBGRemoverClient('vbr_your_api_key')

    # With custom options
    client = VideoBGRemoverClient(
        'vbr_your_api_key',
        base_url='https://api.videobgremover.com',  # Custom API endpoint
        timeout=60.0  # 60 second timeout
    )
    ```
  </Tab>
</Tabs>

### Parameters

| Parameter         | Type     | Description                                                   |
| ----------------- | -------- | ------------------------------------------------------------- |
| `api_key`         | `string` | Your VideoBGRemover API key (format: `vbr_` + 32 characters)  |
| `options.baseUrl` | `string` | API base URL (default: production)                            |
| `options.timeout` | `number` | Request timeout in milliseconds (Node.js) or seconds (Python) |
| `options.headers` | `object` | Additional HTTP headers                                       |

## Methods

### credits()

Check your current credit balance.

<Tabs group="code-examples">
  <Tab title="Node.js">
    ```typescript theme={"dark"}
    const credits = await client.credits()

    console.log(`Total: ${credits.totalCredits}`)
    console.log(`Remaining: ${credits.remainingCredits}`)
    console.log(`Used: ${credits.usedCredits}`)
    ```

    **Returns**: `Promise<Credits>`

    ```typescript theme={"dark"}
    interface Credits {
      totalCredits: number
      remainingCredits: number
      usedCredits: number
    }
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={"dark"}
    credits = client.credits()

    print(f"Total: {credits.total_credits}")
    print(f"Remaining: {credits.remaining_credits}")
    print(f"Used: {credits.used_credits}")
    ```

    **Returns**: `CreditBalance`

    ```python theme={"dark"}
    class CreditBalance:
        total_credits: int
        remaining_credits: int
        used_credits: int
    ```
  </Tab>
</Tabs>

### Low-Level API Methods

These methods provide direct access to the REST API. Most users should use the high-level `Video.removeBackground()` method instead.

#### createJobFile()

Create a job for file upload.

<Tabs group="code-examples">
  <Tab title="Node.js">
    ```typescript theme={"dark"}
    const job = await client.createJobFile({
      filename: 'my-video.mp4',
      content_type: 'video/mp4'
    })

    console.log('Job ID:', job.id)
    console.log('Upload URL:', job.upload_url)
    console.log('Expires:', job.expires_at)
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={"dark"}
    from videobgremover.client.models import CreateJobFileUpload

    job = client.create_job_file(CreateJobFileUpload(
        filename='my-video.mp4',
        content_type='video/mp4'
    ))

    print(f"Job ID: {job['id']}")
    print(f"Upload URL: {job['upload_url']}")
    ```
  </Tab>
</Tabs>

#### createJobUrl()

Create a job for URL download.

<Tabs group="code-examples">
  <Tab title="Node.js">
    ```typescript theme={"dark"}
    const job = await client.createJobUrl({
      video_url: 'https://example.com/video.mp4'
    })

    console.log('Job ID:', job.id)
    // Video downloads automatically
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={"dark"}
    from videobgremover.client.models import CreateJobUrlDownload

    job = client.create_job_url(CreateJobUrlDownload(
        video_url='https://example.com/video.mp4'
    ))

    print(f"Job ID: {job['id']}")
    ```
  </Tab>
</Tabs>

#### startJob()

Start processing a job.

<Tabs group="code-examples">
  <Tab title="Node.js">
    ```typescript theme={"dark"}
    // Start with default settings (green screen)
    const result = await client.startJob(jobId)

    // Start with transparent output
    const result = await client.startJob(jobId, {
      background: {
        type: 'transparent',
        transparent_format: 'webm_vp9'
      }
    })

    // Start with color background
    const result = await client.startJob(jobId, {
      background: {
        type: 'color',
        color: '#FF0000'
      }
    })
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={"dark"}
    from videobgremover.client.models import StartJobRequest, BackgroundOptions

    # Start with default settings (green screen)
    result = client.start_job(job_id)

    # Start with transparent output
    result = client.start_job(job_id, StartJobRequest(
        background=BackgroundOptions(
            type='transparent',
            transparent_format='webm_vp9'
        )
    ))

    # Start with color background
    result = client.start_job(job_id, StartJobRequest(
        background=BackgroundOptions(
            type='color',
            color='#FF0000'
        )
    ))
    ```
  </Tab>
</Tabs>

#### status()

Check job processing status.

<Tabs group="code-examples">
  <Tab title="Node.js">
    ```typescript theme={"dark"}
    const status = await client.status(jobId)

    console.log('Status:', status.status) // 'created', 'processing', 'completed', 'failed'
    console.log('Message:', status.message)

    if (status.status === 'completed') {
      console.log('Download URL:', status.processed_video_url)
    }
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={"dark"}
    status = client.status(job_id)

    print(f'Status: {status.status}')  # 'created', 'processing', 'completed', 'failed'
    print(f'Message: {status.message}')

    if status.status == 'completed':
        print(f'Download URL: {status.processed_video_url}')
    ```
  </Tab>
</Tabs>

#### wait()

Wait for a job to complete with polling.

<Tabs group="code-examples">
  <Tab title="Node.js">
    ```typescript theme={"dark"}
    // Wait with default settings
    const finalStatus = await client.wait(jobId)

    // Wait with custom options
    const finalStatus = await client.wait(jobId, {
      pollSeconds: 3.0,     // Check every 3 seconds
      timeout: 300,         // 5 minute timeout
      onStatus: (status) => {
        console.log(`Current status: ${status}`)
      }
    })
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={"dark"}
    # Wait with default settings
    final_status = client.wait(job_id)

    # Wait with custom options
    def status_callback(status):
        print(f'Current status: {status}')

    final_status = client.wait(
        job_id,
        poll_seconds=3.0,     # Check every 3 seconds
        timeout=300,          # 5 minute timeout
        on_status=status_callback
    )
    ```
  </Tab>
</Tabs>

#### deleteJob()

Delete a job and all associated files.

<Warning>
  This action is permanent and cannot be undone. No credit refunds are provided.
</Warning>

<Tabs group="code-examples">
  <Tab title="Node.js">
    ```typescript theme={"dark"}
    const result = await client.deleteJob(jobId)

    console.log('Deleted:', result.id)
    console.log('Message:', result.message)
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={"dark"}
    result = client.delete_job(job_id)

    print(f"Deleted: {result['id']}")
    print(f"Message: {result['message']}")
    ```
  </Tab>
</Tabs>

**Returns**: `{ id: string, message: string }`

| Field     | Type     | Description           |
| --------- | -------- | --------------------- |
| `id`      | `string` | ID of the deleted job |
| `message` | `string` | Confirmation message  |

## Error Handling

The client throws specific exceptions for different error conditions:

<Tabs group="code-examples">
  <Tab title="Node.js">
    ```typescript theme={"dark"}
    import { 
      ApiError, 
      InsufficientCreditsError, 
      JobNotFoundError, 
      ProcessingError 
    } from '@videobgremover/sdk'

    try {
      const transparent = await video.removeBackground({ client })
    } catch (error) {
      if (error instanceof InsufficientCreditsError) {
        console.log('❌ Not enough credits')
        console.log('Remaining:', error.remainingCredits)
      } else if (error instanceof JobNotFoundError) {
        console.log('❌ Job not found')
      } else if (error instanceof ProcessingError) {
        console.log('❌ Processing failed:', error.message)
      } else if (error instanceof ApiError) {
        console.log('❌ API error:', error.message)
      }
    }
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={"dark"}
    from videobgremover.client.models import (
        InsufficientCreditsError,
        JobNotFoundError, 
        ProcessingError,
        ApiError
    )

    try:
        transparent = video.remove_background(client)
    except InsufficientCreditsError as e:
        print('❌ Not enough credits')
        print(f'Remaining: {e.remaining_credits}')
    except JobNotFoundError:
        print('❌ Job not found')
    except ProcessingError as e:
        print(f'❌ Processing failed: {e}')
    except ApiError as e:
        print(f'❌ API error: {e}')
    ```
  </Tab>
</Tabs>

## Usage with Video Class

The recommended way to use the client is through the `Video` class:

<Tabs group="code-examples">
  <Tab title="Node.js">
    ```typescript theme={"dark"}
    import { VideoBGRemoverClient, Video, RemoveBGOptions, Prefer } from '@videobgremover/sdk'

    const client = new VideoBGRemoverClient('your_api_key')
    const video = Video.open('path/to/video.mp4')

    // High-level method (recommended)
    const transparent = await video.removeBackground({ client })

    // With options
    const options = new RemoveBGOptions(Prefer.WEBM_VP9)
    const transparent = await video.removeBackground({ client, options })
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={"dark"}
    from videobgremover import VideoBGRemoverClient, Video, RemoveBGOptions, Prefer

    client = VideoBGRemoverClient('your_api_key')
    video = Video.open('path/to/video.mp4')

    # High-level method (recommended)
    transparent = video.remove_background(client)

    # With options
    options = RemoveBGOptions(prefer=Prefer.WEBM_VP9)
    transparent = video.remove_background(client, options)
    ```
  </Tab>
</Tabs>

## Best Practices

### Credit Management

```typescript theme={"dark"}
// Always check credits before processing
const credits = await client.credits()
if (credits.remainingCredits < videoLengthInSeconds) {
  throw new Error('Not enough credits for this video')
}
```

### Error Recovery

```typescript theme={"dark"}
// Implement retry logic for network issues
async function removeBackgroundWithRetry(video, client, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await video.removeBackground({ client })
    } catch (error) {
      if (error instanceof InsufficientCreditsError) {
        throw error // Don't retry credit issues
      }
      if (i === maxRetries - 1) throw error
      await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)))
    }
  }
}
```

### Timeout Handling

```typescript theme={"dark"}
// Use appropriate timeouts for long videos
const client = new VideoBGRemoverClient('your_key', {
  timeout: 120000 // 2 minutes for long videos
})
```

## Related Classes

* **[Video](/api-reference/sdk-reference/video)**: Video loading and background removal
* **[Composition](/api-reference/sdk-reference/composition)**: Local video composition
* **[EncoderProfile](/api-reference/sdk-reference/encoders)**: Export format configuration
