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

# Code Samples

> Ready-to-use code examples in multiple languages

## Basic Screenshot

<Tabs>
  <Tab title="cURL">
    ```bash theme={null}
    curl -X POST https://api.snapopa.com/capture \
      -H "Authorization: Bearer $SNAPOPA_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{"url": "https://example.com"}'
    ```
  </Tab>

  <Tab title="Node.js">
    ```javascript theme={null}
    const SNAPOPA_API_KEY = process.env.SNAPOPA_API_KEY;

    async function captureScreenshot(url) {
      const response = await fetch('https://api.snapopa.com/capture', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${SNAPOPA_API_KEY}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ url }),
      });

      if (!response.ok) {
        throw new Error(`Capture failed: ${response.status}`);
      }

      return response.json();
    }

    // Usage
    const result = await captureScreenshot('https://example.com');
    console.log(result.data.fileUrl);
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import os
    import requests

    SNAPOPA_API_KEY = os.environ['SNAPOPA_API_KEY']

    def capture_screenshot(url):
        response = requests.post(
            'https://api.snapopa.com/capture',
            headers={
                'Authorization': f'Bearer {SNAPOPA_API_KEY}',
                'Content-Type': 'application/json',
            },
            json={'url': url}
        )
        response.raise_for_status()
        return response.json()

    # Usage
    result = capture_screenshot('https://example.com')
    print(result['data']['fileUrl'])
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    package main

    import (
        "bytes"
        "encoding/json"
        "fmt"
        "net/http"
        "os"
    )

    type CaptureRequest struct {
        URL string `json:"url"`
    }

    type CaptureResponse struct {
        Success bool `json:"success"`
        Data    struct {
            FileURL string `json:"fileUrl"`
        } `json:"data"`
    }

    func captureScreenshot(url string) (*CaptureResponse, error) {
        apiKey := os.Getenv("SNAPOPA_API_KEY")

        reqBody, _ := json.Marshal(CaptureRequest{URL: url})
        req, _ := http.NewRequest("POST", "https://api.snapopa.com/capture", bytes.NewBuffer(reqBody))
        req.Header.Set("Authorization", "Bearer "+apiKey)
        req.Header.Set("Content-Type", "application/json")

        client := &http.Client{}
        resp, err := client.Do(req)
        if err != nil {
            return nil, err
        }
        defer resp.Body.Close()

        var result CaptureResponse
        json.NewDecoder(resp.Body).Decode(&result)
        return &result, nil
    }

    func main() {
        result, _ := captureScreenshot("https://example.com")
        fmt.Println(result.Data.FileURL)
    }
    ```
  </Tab>

  <Tab title="PHP">
    ```php theme={null}
    <?php

    $apiKey = getenv('SNAPOPA_API_KEY');

    function captureScreenshot($url) {
        global $apiKey;

        $ch = curl_init('https://api.snapopa.com/capture');
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $apiKey,
                'Content-Type: application/json',
            ],
            CURLOPT_POSTFIELDS => json_encode(['url' => $url]),
        ]);

        $response = curl_exec($ch);
        curl_close($ch);

        return json_decode($response, true);
    }

    // Usage
    $result = captureScreenshot('https://example.com');
    echo $result['data']['fileUrl'];
    ```
  </Tab>
</Tabs>

## Full Configuration

<Tabs>
  <Tab title="Node.js">
    ```javascript theme={null}
    async function captureWithOptions(options) {
      const response = await fetch('https://api.snapopa.com/capture', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${process.env.SNAPOPA_API_KEY}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          url: options.url,
          format: options.format || 'png',
          viewport: {
            width: options.width || 1920,
            height: options.height || 1080,
          },
          isFullPage: options.fullPage || false,
          quality: options.quality || 95,
          waitUntil: options.waitUntil || 'domcontentloaded',
          responseCache: {
            enabled: options.cache || false,
            ttl: options.cacheTtl || 86400,
          },
        }),
      });

      return response.json();
    }

    // Usage
    const result = await captureWithOptions({
      url: 'https://example.com',
      format: 'webp',
      width: 1280,
      height: 720,
      fullPage: true,
      cache: true,
    });
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    def capture_with_options(
        url,
        format='png',
        width=1920,
        height=1080,
        full_page=False,
        quality=95,
        wait_until='domcontentloaded',
        cache=False,
        cache_ttl=86400,
    ):
        response = requests.post(
            'https://api.snapopa.com/capture',
            headers={
                'Authorization': f'Bearer {os.environ["SNAPOPA_API_KEY"]}',
                'Content-Type': 'application/json',
            },
            json={
                'url': url,
                'format': format,
                'viewport': {
                    'width': width,
                    'height': height,
                },
                'isFullPage': full_page,
                'quality': quality,
                'waitUntil': wait_until,
                'responseCache': {
                    'enabled': cache,
                    'ttl': cache_ttl,
                },
            }
        )
        return response.json()

    # Usage
    result = capture_with_options(
        url='https://example.com',
        format='webp',
        width=1280,
        height=720,
        full_page=True,
        cache=True,
    )
    ```
  </Tab>
</Tabs>

## Download to File

<Tabs>
  <Tab title="Node.js">
    ```javascript theme={null}
    import { writeFile } from 'fs/promises';

    async function downloadScreenshot(url, outputPath) {
      const response = await fetch('https://api.snapopa.com/capture', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${process.env.SNAPOPA_API_KEY}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          url,
          responseType: 'file',
        }),
      });

      const buffer = await response.arrayBuffer();
      await writeFile(outputPath, Buffer.from(buffer));
    }

    // Usage
    await downloadScreenshot('https://example.com', './screenshot.png');
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    def download_screenshot(url, output_path):
        response = requests.post(
            'https://api.snapopa.com/capture',
            headers={
                'Authorization': f'Bearer {os.environ["SNAPOPA_API_KEY"]}',
                'Content-Type': 'application/json',
            },
            json={
                'url': url,
                'responseType': 'file',
            }
        )

        with open(output_path, 'wb') as f:
            f.write(response.content)

    # Usage
    download_screenshot('https://example.com', './screenshot.png')
    ```
  </Tab>
</Tabs>

## Error Handling

<Tabs>
  <Tab title="Node.js">
    ```javascript theme={null}
    async function captureWithRetry(url, maxRetries = 3) {
      for (let attempt = 0; attempt < maxRetries; attempt++) {
        try {
          const response = await fetch('https://api.snapopa.com/capture', {
            method: 'POST',
            headers: {
              'Authorization': `Bearer ${process.env.SNAPOPA_API_KEY}`,
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({ url }),
          });

          if (response.status === 429) {
            const resetTime = response.headers.get('X-RateLimit-Reset');
            const waitMs = Math.max((resetTime * 1000) - Date.now(), 1000);
            await new Promise(r => setTimeout(r, waitMs));
            continue;
          }

          if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
          }

          return response.json();
        } catch (error) {
          if (attempt === maxRetries - 1) throw error;
          await new Promise(r => setTimeout(r, Math.pow(2, attempt) * 1000));
        }
      }
    }
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import time

    def capture_with_retry(url, max_retries=3):
        for attempt in range(max_retries):
            try:
                response = requests.post(
                    'https://api.snapopa.com/capture',
                    headers={
                        'Authorization': f'Bearer {os.environ["SNAPOPA_API_KEY"]}',
                        'Content-Type': 'application/json',
                    },
                    json={'url': url}
                )

                if response.status_code == 429:
                    reset_time = int(response.headers.get('X-RateLimit-Reset', 0))
                    wait_time = max(reset_time - time.time(), 1)
                    time.sleep(wait_time)
                    continue

                response.raise_for_status()
                return response.json()

            except requests.RequestException:
                if attempt == max_retries - 1:
                    raise
                time.sleep(2 ** attempt)
    ```
  </Tab>
</Tabs>
