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

# ENS Ads Integration Code: JavaScript & Python Examples

> Ready-to-use JavaScript and Python code for all three ENS Ads operations: fetching campaigns, recording impressions, and recording clicks from your server.

The examples below cover all three API operations you need to integrate ENS Ads: fetching campaigns, recording impressions, and recording clicks. Each section shows both JavaScript and Python implementations side by side so you can drop the relevant code directly into your server-side integration.

<Tip>
  Store your API key in an environment variable (for example, `process.env.ENS_API_KEY` in Node.js or `os.environ["ENS_API_KEY"]` in Python) rather than hardcoding it in your source code. This keeps the key out of version control and makes it easier to rotate without a code change.
</Tip>

## Fetch campaigns

Call this when you need to retrieve available campaigns for a specific placement. Pass `location` and `device` to target campaigns to your user's context.

<CodeGroup>
  ```javascript fetch-campaigns.js theme={null}
  const BASE_URL = 'https://ads.enslive.live/api/v1';
  const API_KEY = 'YOUR_API_KEY';

  // Fetch campaigns
  async function fetchCampaigns(placement, location, device) {
    try {
      const response = await fetch(
        `${BASE_URL}/campaigns/fetch?placement=${placement}&location=${location}&device=${device}`,
        {
          headers: {
            'Authorization': `Bearer ${API_KEY}`
          }
        }
      );
      
      if (!response.ok) {
        throw new Error(`Error: ${response.status}`);
      }
      
      const data = await response.json();
      return data.data;
    } catch (error) {
      console.error('Failed to fetch campaigns:', error);
    }
  }
  ```

  ```python fetch_campaigns.py theme={null}
  import requests

  BASE_URL = 'https://ads.enslive.live/api/v1'
  API_KEY = 'YOUR_API_KEY'

  headers = {
      'Authorization': f'Bearer {API_KEY}',
      'Content-Type': 'application/json'
  }

  def fetch_campaigns(placement, location=None, device=None):
      """Fetch available campaigns"""
      try:
          params = {'placement': placement}
          if location:
              params['location'] = location
          if device:
              params['device'] = device
          
          response = requests.get(
              f'{BASE_URL}/campaigns/fetch',
              params=params,
              headers=headers
          )
          response.raise_for_status()
          return response.json()['data']
      except requests.exceptions.RequestException as e:
          print(f'Error fetching campaigns: {e}')
          return []
  ```
</CodeGroup>

## Track impression

Call this immediately after a campaign becomes visible to the user. Use the `id` field from the fetched campaign object as `campaignId`.

<CodeGroup>
  ```javascript track-impression.js theme={null}
  const BASE_URL = 'https://ads.enslive.live/api/v1';
  const API_KEY = 'YOUR_API_KEY';

  // Track impression
  async function trackImpression(campaignId, placement, location, device) {
    try {
      const response = await fetch(`${BASE_URL}/campaigns/impression`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${API_KEY}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          campaignId,
          placement,
          location,
          device
        })
      });
      
      if (!response.ok) {
        throw new Error(`Error: ${response.status}`);
      }
    } catch (error) {
      console.error('Failed to track impression:', error);
    }
  }
  ```

  ```python track_impression.py theme={null}
  import requests

  BASE_URL = 'https://ads.enslive.live/api/v1'
  API_KEY = 'YOUR_API_KEY'

  headers = {
      'Authorization': f'Bearer {API_KEY}',
      'Content-Type': 'application/json'
  }

  def track_impression(campaign_id, placement, location=None, device=None):
      """Track campaign impression"""
      try:
          data = {
              'campaignId': campaign_id,
              'placement': placement
          }
          if location:
              data['location'] = location
          if device:
              data['device'] = device
          
          response = requests.post(
              f'{BASE_URL}/campaigns/impression',
              json=data,
              headers=headers
          )
          response.raise_for_status()
      except requests.exceptions.RequestException as e:
          print(f'Error tracking impression: {e}')
  ```
</CodeGroup>

## Track click

Call this when the user clicks or otherwise interacts with the campaign. Pass the same `campaignId`, `placement`, `location`, and `device` values you used for the impression call.

<CodeGroup>
  ```javascript track-click.js theme={null}
  const BASE_URL = 'https://ads.enslive.live/api/v1';
  const API_KEY = 'YOUR_API_KEY';

  // Track click
  async function trackClick(campaignId, placement, location, device) {
    try {
      const response = await fetch(`${BASE_URL}/campaigns/click`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${API_KEY}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          campaignId,
          placement,
          location,
          device
        })
      });
      
      if (!response.ok) {
        throw new Error(`Error: ${response.status}`);
      }
    } catch (error) {
      console.error('Failed to track click:', error);
    }
  }
  ```

  ```python track_click.py theme={null}
  import requests

  BASE_URL = 'https://ads.enslive.live/api/v1'
  API_KEY = 'YOUR_API_KEY'

  headers = {
      'Authorization': f'Bearer {API_KEY}',
      'Content-Type': 'application/json'
  }

  def track_click(campaign_id, placement, location=None, device=None):
      """Track campaign click"""
      try:
          data = {
              'campaignId': campaign_id,
              'placement': placement
          }
          if location:
              data['location'] = location
          if device:
              data['device'] = device
          
          response = requests.post(
              f'{BASE_URL}/campaigns/click',
              json=data,
              headers=headers
          )
          response.raise_for_status()
      except requests.exceptions.RequestException as e:
          print(f'Error tracking click: {e}')
  ```
</CodeGroup>
