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

# Validate Access Token

> Validate your API key and get account information

## Overview

The validate endpoint allows you to verify that your API key is valid and retrieve information about the associated account and key permissions.

<Info>
  This endpoint is useful for verifying API key validity during application
  startup or after key rotation.
</Info>

## Response

<ResponseField name="success" type="boolean" required>
  `true` if validation succeeded
</ResponseField>

<ResponseField name="data" type="object" required>
  <Expandable title="properties">
    <ResponseField name="username" type="string">
      Username associated with the API key
    </ResponseField>

    <ResponseField name="apiKey" type="object">
      API key details

      <Expandable title="properties">
        <ResponseField name="key" type="string">
          Your API key
        </ResponseField>

        <ResponseField name="isEnabled" type="boolean">
          Whether the key is currently active
        </ResponseField>

        <ResponseField name="type" type="string">
          Key type: `"SANDBOX"` or `"PRODUCTION"`
        </ResponseField>

        <ResponseField name="allowedips" type="array">
          Array of whitelisted IP addresses,
          empty `[]` means all IPs allowed.
        </ResponseField>

        <ResponseField name="scope" type="string">
          Access level: `"READ-WRITE"` or `"READ-ONLY"`
        </ResponseField>
      </Expandable>
    </ResponseField>
  </Expandable>
</ResponseField>

## Example Request

<CodeGroup>
  ```bash cURL theme={null}
  curl --request GET \
    --url https://api.oneclickdz.com/v3/validate \
    --header 'X-Access-Token: YOUR_API_KEY'
  ```

  ```javascript Node.js theme={null}
  const response = await fetch("https://api.oneclickdz.com/v3/validate", {
    headers: {
      "X-Access-Token": process.env.ONECLICKDZ_API_KEY,
    },
  });

  const data = await response.json();

  if (data.success) {
    console.log("✓ API key is valid");
    console.log("Account:", data.data.username);
    console.log("Type:", data.data.apiKey.type);
  } else {
    console.error("✗ API key validation failed");
  }
  ```

  ```python Python theme={null}
  import requests
  import os

  response = requests.get(
      'https://api.oneclickdz.com/v3/validate',
      headers={'X-Access-Token': os.getenv('ONECLICKDZ_API_KEY')}
  )

  data = response.json()

  if data['success']:
      print('✓ API key is valid')
      print(f"Account: {data['data']['username']}")
      print(f"Type: {data['data']['apiKey']['type']}")
  else:
      print('✗ API key validation failed')
  ```

  ```php PHP theme={null}
  <?php
  $ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, 'https://api.oneclickdz.com/v3/validate');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, [
      'X-Access-Token: ' . getenv('ONECLICKDZ_API_KEY')
  ]);

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

  $data = json_decode($response, true);

  if ($data['success']) {
      echo "✓ API key is valid\n";
      echo "Account: " . $data['data']['username'] . "\n";
      echo "Type: " . $data['data']['apiKey']['type'] . "\n";
  } else {
      echo "✗ API key validation failed\n";
  }
  ?>
  ```
</CodeGroup>

## Example Response

```json theme={null}
{
  "success": true,
  "data": {
    "username": "+213665983439",
    "apiKey": {
      "key": "ea27b376-9f5c-4b09-883f-1b96cd7b541c",
      "isEnabled": true,
      "type": "SANDBOX",
      "allowedips": [],
      "scope": "READ-WRITE"
    }
  }
}
```

## Error Responses

<AccordionGroup>
  <Accordion title="400 - Missing Access Token">
    ```json theme={null}
    {
      "success": false,
      "error": {
        "code": "MISSING_ACCESS_TOKEN",
        "message": "Access token is required"
      },
      "requestId": "req_abc123"
    }
    ```
  </Accordion>

  <Accordion title="401 - Invalid Access Token">
    ```json theme={null}
    {
      "success": false,
      "error": {
        "code": "INVALID_ACCESS_TOKEN",
        "message": "The provided access token is invalid",
        "details": {
          "attemptsLeft": 3
        }
      },
      "requestId": "req_abc123"
    }
    ```

    <Warning>
      After 5 failed attempts, your IP will be temporarily blocked for 15 minutes.
    </Warning>
  </Accordion>

  <Accordion title="403 - IP Blocked">
    ```json theme={null}
    {
      "success": false,
      "error": {
        "code": "IP_BLOCKED",
        "message": "Your IP has been temporarily blocked due to too many invalid attempts"
      },
      "requestId": "req_abc123"
    }
    ```
  </Accordion>
</AccordionGroup>

## Use Cases

<CardGroup cols={2}>
  <Card title="Startup Validation" icon="rocket">
    Verify API key during application initialization
  </Card>

  {" "}

  <Card title="Health Checks" icon="heart-pulse">
    Include in application health check routines
  </Card>

  {" "}

  <Card title="Environment Verification" icon="check-circle">
    Confirm you're using the correct key (sandbox vs production)
  </Card>

  <Card title="Permission Checking" icon="shield-check">
    Verify key scope and permissions before operations
  </Card>
</CardGroup>

## Integration Example

```javascript theme={null}
class OneClickDzClient {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseUrl = "https://api.oneclickdz.com";
    this.validated = false;
  }

  async validate() {
    const response = await fetch(`${this.baseUrl}/v3/validate`, {
      headers: { "X-Access-Token": this.apiKey },
    });

    const data = await response.json();

    if (!data.success) {
      throw new Error(`API key validation failed: ${data.error.message}`);
    }

    this.username = data.data.username;
    this.keyType = data.data.apiKey.type;
    this.scope = data.data.apiKey.scope;
    this.validated = true;

    console.log(`✓ Authenticated as ${this.username} (${this.keyType})`);

    return data.data;
  }

  async request(endpoint, options = {}) {
    if (!this.validated) {
      await this.validate();
    }

    // Check if operation requires write access
    if (
      options.method &&
      options.method !== "GET" &&
      this.scope === "READ-ONLY"
    ) {
      throw new Error("This operation requires READ-WRITE access");
    }

    return fetch(`${this.baseUrl}${endpoint}`, {
      ...options,
      headers: {
        ...options.headers,
        "X-Access-Token": this.apiKey,
      },
    });
  }
}

// Usage
const client = new OneClickDzClient(process.env.ONECLICKDZ_API_KEY);
await client.validate();

// Now make requests
const response = await client.request("/v3/account/balance");
```

## Best Practices

<AccordionGroup>
  <Accordion title="Validate on Startup" icon="play">
    Always validate your API key when your application starts

    ```javascript theme={null}
    // During app initialization
    async function initializeApp() {
      try {
        await client.validate();
        console.log('✓ API client initialized');
      } catch (error) {
        console.error('✗ Failed to initialize API client:', error);
        process.exit(1);
      }
    }
    ```
  </Accordion>

  <Accordion title="Cache Validation Result" icon="database">
    Don't validate on every request - cache the result

    ```javascript theme={null}
    let validationCache = {
      validated: false,
      timestamp: 0,
      data: null
    };

    async function getValidatedClient() {
      const now = Date.now();
      const cacheExpiry = 5 * 60 * 1000; // 5 minutes
      
      if (validationCache.validated && (now - validationCache.timestamp) < cacheExpiry) {
        return validationCache.data;
      }
      
      const response = await fetch('https://api.oneclickdz.com/v3/validate', {
        headers: { 'X-Access-Token': API_KEY }
      });
      
      const data = await response.json();
      
      if (data.success) {
        validationCache = {
          validated: true,
          timestamp: now,
          data: data.data
        };
      }
      
      return data.data;
    }
    ```
  </Accordion>

  <Accordion title="Check Environment" icon="flask">
    Verify you're using the correct environment

    ```javascript theme={null}
    const data = await validateApiKey();

    const isProduction = process.env.NODE_ENV === 'production';
    const keyType = data.apiKey.type;

    if (isProduction && keyType === 'SANDBOX') {
      throw new Error('⚠️ Using SANDBOX key in production environment!');
    }

    if (!isProduction && keyType === 'PRODUCTION') {
      console.warn('⚠️ Using PRODUCTION key in development environment!');
    }
    ```
  </Accordion>

  <Accordion title="Handle Gracefully" icon="shield-check">
    Implement proper error handling

    ```javascript theme={null}
    async function validateWithRetry(maxRetries = 3) {
      for (let i = 0; i < maxRetries; i++) {
        try {
          const response = await fetch('https://api.oneclickdz.com/v3/validate', {
            headers: { 'X-Access-Token': API_KEY }
          });
          
          const data = await response.json();
          
          if (data.success) {
            return data.data;
          }
          
          if (data.error.code === 'INVALID_ACCESS_TOKEN') {
            throw new Error('Invalid API key - check your configuration');
          }
          
          if (data.error.code === 'IP_BLOCKED') {
            throw new Error('IP blocked - too many failed attempts');
          }
          
        } catch (error) {
          if (i === maxRetries - 1) throw error;
          
          await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
        }
      }
    }
    ```
  </Accordion>
</AccordionGroup>

## Related Endpoints

<CardGroup cols={2}>
  <Card title="Health Check" icon="heart-pulse" href="/en/api-reference/core/health-check">
    Check API service status
  </Card>

  <Card title="Get Balance" icon="wallet" href="/en/api-reference/account/get-balance">
    Check your account balance
  </Card>
</CardGroup>
