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

# Code Examples

> Integration examples for Platform users

## Quick Start

Choose your integration path:

<CardGroup cols={2}>
  <Card title="Backend Integration" icon="server" href="#backend">
    Get upload tokens and call verify-pot-sizes
  </Card>

  <Card title="Frontend Integration" icon="upload" href="#frontend">
    Upload files with Uppy
  </Card>
</CardGroup>

## Backend Examples

### Get Upload Token

<CodeGroup>
  ```javascript get-upload-token.js theme={"theme":"github-dark"}
  async function getUploadToken(merchantId, platformApiKey) {
    const response = await fetch('https://api.superseeded.ai/v1/auth/delegate-upload', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${platformApiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ merchant_id: merchantId })
    });
    
    if (!response.ok) {
      throw new Error(`Failed to get upload token: ${response.statusText}`);
    }
    
    const data = await response.json();
    return data.token;
  }
  ```

  ```python get-upload-token.py theme={"theme":"github-dark"}
  import requests

  def get_upload_token(merchant_id: str, platform_api_key: str) -> str:
      response = requests.post(
          'https://api.superseeded.ai/v1/auth/delegate-upload',
          headers={
              'Authorization': f'Bearer {platform_api_key}',
              'Content-Type': 'application/json'
          },
          json={'merchant_id': merchant_id}
      )
      response.raise_for_status()
      return response.json()['token']
  ```
</CodeGroup>

### Call Verify Pot Sizes

After a successful upload, call the verify-pot-sizes endpoint with the delegation token and file URL to process the file and retrieve enriched data.

<CodeGroup>
  ```javascript validate-pot-sizes.js theme={"theme":"github-dark"}
  async function validatePotSizes(delegationToken, fileUrl) {
    const response = await fetch('https://api.superseeded.ai/v1/verify/pot-sizes', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${delegationToken}`, // Same token used for upload
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ file_url: fileUrl })
    });
    
    if (!response.ok) {
      throw new Error(`Failed to resolve specs: ${response.statusText}`);
    }
    
    const data = await response.json();
    
    console.log(`Processed ${data.usage.rows_processed} rows`);
    console.log(`Billable: ${data.usage.is_billable}`);
    
    // Save enriched_data to your database
    await saveEnrichedData(data.enriched_data);
    
    return data;
  }
  ```

  ```python verify-pot-sizes.py theme={"theme":"github-dark"}
  import requests

  def validate_pot_sizes(delegation_token: str, file_url: str) -> dict:
      response = requests.post(
          'https://api.superseeded.ai/v1/verify/pot-sizes',
          headers={
              'Authorization': f'Bearer {delegation_token}',  # Same token used for upload
              'Content-Type': 'application/json'
          },
          json={'file_url': file_url}
      )
      response.raise_for_status()
      
      data = response.json()
      
      print(f"Processed {data['usage']['rows_processed']} rows")
      print(f"Billable: {data['usage']['is_billable']}")
      
      # Save enriched_data to your database
      save_enriched_data(data['enriched_data'])
      
      return data
  ```
</CodeGroup>

## Frontend Examples

### Upload with Uppy (Framework-Agnostic)

```javascript theme={"theme":"github-dark"}
import Uppy from '@uppy/core'
import Tus from '@uppy/tus'

function createUppyUploader(uploadToken, onUploadComplete) {
  const uppy = new Uppy({
    autoProceed: true,
    restrictions: {
      allowedFileTypes: ['.csv', '.xlsx', '.xls', '.json']
    }
  });
  
  uppy.use(Tus, {
    endpoint: 'https://secure.superseeded.ai/files/',
    headers: {
      'Authorization': `Bearer ${uploadToken}`
    },
    chunkSize: 5 * 1024 * 1024, // 5MB
    retryDelays: [0, 1000, 3000, 5000]
  });
  
  uppy.on('complete', (result) => {
    onUploadComplete(result.successful[0]);
  });
  
  return uppy;
}
```

## Complete Flow

Here's the complete end-to-end integration:

```javascript theme={"theme":"github-dark"}
async function completeUploadFlow(merchantId, file) {
  // 1. Get delegation token from your backend
  const token = await fetch('/api/get-upload-token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ merchant_id: merchantId })
  }).then(r => r.json()).then(d => d.token);
  
  // 2. Upload file with Uppy
  const uppy = new Uppy({ autoProceed: true })
    .use(Tus, {
      endpoint: 'https://secure.superseeded.ai/files/',
      headers: { 'Authorization': `Bearer ${token}` }
    });
  
  uppy.addFile(file);
  const uploadResult = await uppy.upload();
  
  // 3. Get the file URL from the upload result
  const fileUrl = uploadResult.successful[0].uploadURL;
  
  // 4. Call validate-pot-sizes with the same delegation token and file URL
  const response = await fetch('https://api.superseeded.ai/v1/verify/pot-sizes', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`, // Same token used for upload
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ file_url: fileUrl })
  });
  
  const enrichedData = await response.json();
  
  console.log('Processing complete:', enrichedData);
  console.log(`Rows processed: ${enrichedData.usage.rows_processed}`);
  
  return enrichedData;
}
```

## All Examples

For the complete set of examples, see the [examples repository](https://github.com/superseeded/platform-example).

<Accordion>
  <AccordionItem title="Backend Examples">
    <ul>
      <li><code>get-upload-token.js</code> - JavaScript token request</li>
      <li><code>get-upload-token.py</code> - Python token request</li>
      <li><code>verify-pot-sizes.js</code> - JavaScript verify-pot-sizes call</li>
      <li><code>verify-pot-sizes.py</code> - Python verify-pot-sizes call</li>
    </ul>
  </AccordionItem>

  <AccordionItem title="Frontend Examples">
    <ul>
      <li><code>upload-with-uppy.js</code> - Framework-agnostic integration</li>
    </ul>
  </AccordionItem>

  <AccordionItem title="Complete Flow">
    <ul>
      <li><code>complete-flow\.js</code> - End-to-end example with token, upload, and verify-pot-sizes</li>
    </ul>
  </AccordionItem>
</Accordion>
