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

# Generate Access Token

> Generate access tokens for external API authentication using client credentials

# Generate Access Token

Generate access tokens for external API authentication using basic authentication with client credentials.

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST 'https://api.weir.ai/auth/token' \
    -H 'Content-Type: application/json' \
    -u 'your_client_id:your_secret_key'
  ```
</RequestExample>

<ResponseExample>
  ```json Success Response theme={null}
  {
    "data": {
      "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",
      "expiresIn": 3600,
      "tokenType": "Bearer"
    },
    "message": "Access token generated successfully",
    "status": "success"
  }
  ```
</ResponseExample>

## Authentication

This endpoint uses basic authentication with your client credentials.

<ParamField header="Authorization" type="string" required>
  Basic authentication header with base64-encoded client credentials. Format: `Basic base64(client_id:secret_key)`
</ParamField>

## Request Parameters

No request body parameters are required for this endpoint.

## Response Fields

<ResponseField name="data" type="object" required>
  Token data object containing authentication information.

  <Expandable title="Token Data Properties">
    <ResponseField name="data.accessToken" type="string" required>
      JWT access token for authenticated API requests. Valid for 1 hour (3600 seconds).
    </ResponseField>

    <ResponseField name="data.expiresIn" type="integer" required>
      Token expiration time in seconds. Always 3600 (1 hour) for access tokens.
    </ResponseField>

    <ResponseField name="data.tokenType" type="string" required>
      Token type. Always "Bearer" for this API.
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="message" type="string" required>
  Human-readable message describing the result of the operation.
</ResponseField>

<ResponseField name="status" type="string" required>
  Operation status. Always "success" for successful token generation.
</ResponseField>

## Error Responses

<AccordionGroup>
  <Accordion title="401 Unauthorized" icon="exclamation-triangle">
    ```json theme={null}
    {
      "error": {
        "code": "INVALID_CREDENTIALS",
        "message": "Invalid client credentials",
        "details": "The provided client ID or secret key is invalid"
      },
      "status": "error"
    }
    ```

    **Causes**:

    * Invalid client ID
    * Invalid secret key
    * Missing or malformed Authorization header
  </Accordion>

  <Accordion title="429 Too Many Requests" icon="clock">
    ```json theme={null}
    {
      "error": {
        "code": "RATE_LIMIT_EXCEEDED",
        "message": "Too many token generation requests",
        "details": "Rate limit of 10 requests per minute exceeded"
      },
      "status": "error"
    }
    ```

    **Solution**: Wait for the rate limit window to reset before making another request.
  </Accordion>
</AccordionGroup>

## Usage Examples

<CodeGroup>
  ```javascript JavaScript theme={null}
  const generateAccessToken = async (clientId, secretKey) => {
    const credentials = btoa(`${clientId}:${secretKey}`);
    
    const response = await fetch('https://api.weir.ai/auth/token', {
      method: 'POST',
      headers: {
        'Authorization': `Basic ${credentials}`,
        'Content-Type': 'application/json'
      }
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const data = await response.json();
    return data.data.accessToken;
  };

  // Usage
  const accessToken = await generateAccessToken('your_client_id', 'your_secret_key');
  console.log('Access Token:', accessToken);
  ```

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

  def generate_access_token(client_id, secret_key):
      # Encode credentials
      credentials = base64.b64encode(f"{client_id}:{secret_key}".encode()).decode()
      
      # Make request
      response = requests.post(
          'https://api.weir.ai/auth/token',
          headers={
              'Authorization': f'Basic {credentials}',
              'Content-Type': 'application/json'
          }
      )
      
      response.raise_for_status()
      data = response.json()
      return data['data']['accessToken']

  # Usage
  access_token = generate_access_token('your_client_id', 'your_secret_key')
  print(f'Access Token: {access_token}')
  ```

  ```php PHP theme={null}
  function generateAccessToken($clientId, $secretKey) {
      $credentials = base64_encode($clientId . ':' . $secretKey);
      
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, 'https://api.weir.ai/auth/token');
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, [
          'Authorization: Basic ' . $credentials,
          'Content-Type: application/json'
      ]);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      
      $response = curl_exec($ch);
      $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      curl_close($ch);
      
      if ($httpCode !== 200) {
          throw new Exception("HTTP error: $httpCode");
      }
      
      $data = json_decode($response, true);
      return $data['data']['accessToken'];
  }

  // Usage
  $accessToken = generateAccessToken('your_client_id', 'your_secret_key');
  echo "Access Token: $accessToken";
  ```

  ```go Go theme={null}
  package main

  import (
      "encoding/base64"
      "encoding/json"
      "fmt"
      "net/http"
      "strings"
  )

  type TokenResponse struct {
      Data struct {
          AccessToken string `json:"accessToken"`
          ExpiresIn   int    `json:"expiresIn"`
          TokenType   string `json:"tokenType"`
      } `json:"data"`
      Message string `json:"message"`
      Status  string `json:"status"`
  }

  func generateAccessToken(clientID, secretKey string) (string, error) {
      credentials := base64.StdEncoding.EncodeToString([]byte(clientID + ":" + secretKey))
      
      req, err := http.NewRequest("POST", "https://api.weir.ai/auth/token", nil)
      if err != nil {
          return "", err
      }
      
      req.Header.Set("Authorization", "Basic "+credentials)
      req.Header.Set("Content-Type", "application/json")
      
      client := &http.Client{}
      resp, err := client.Do(req)
      if err != nil {
          return "", err
      }
      defer resp.Body.Close()
      
      if resp.StatusCode != http.StatusOK {
          return "", fmt.Errorf("HTTP error: %d", resp.StatusCode)
      }
      
      var tokenResp TokenResponse
      if err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {
          return "", err
      }
      
      return tokenResp.Data.AccessToken, nil
  }

  // Usage
  func main() {
      accessToken, err := generateAccessToken("your_client_id", "your_secret_key")
      if err != nil {
          panic(err)
      }
      fmt.Printf("Access Token: %s\n", accessToken)
  }
  ```
</CodeGroup>

## Rate Limits

* **Rate Limit**: 10 requests per minute per client
* **Burst Limit**: 20 requests per 5-minute window

## Security Considerations

<Warning>
  **Important**: Never expose your client credentials in client-side code or public repositories. Always use secure storage mechanisms.
</Warning>

<AccordionGroup>
  <Accordion title="Credential Security" icon="lock">
    * Store client credentials in environment variables or secure key management systems
    * Use different credentials for different environments (development, staging, production)
    * Rotate credentials regularly for enhanced security
    * Never log or expose credentials in error messages or logs
  </Accordion>

  <Accordion title="Token Security" icon="shield">
    * Store access tokens securely and never expose them in client-side code
    * Implement automatic token refresh before expiration
    * Use HTTPS for all API requests
    * Monitor token usage and implement proper error handling
  </Accordion>
</AccordionGroup>

## Best Practices

<Steps>
  <Step title="Implement Token Caching" icon="database">
    Cache access tokens in memory or secure storage to avoid unnecessary token generation requests.
  </Step>

  <Step title="Handle Token Expiration" icon="clock">
    Implement automatic token refresh before expiration to ensure uninterrupted API access.
  </Step>

  <Step title="Monitor Rate Limits" icon="eye">
    Monitor rate limit headers and implement proper backoff strategies when limits are reached.
  </Step>

  <Step title="Error Handling" icon="exclamation-triangle">
    Implement comprehensive error handling for authentication failures and network issues.
  </Step>
</Steps>

<Tip>
  **Pro Tip**: Implement a token manager class that handles token generation, caching, and automatic refresh to simplify your integration.
</Tip>
