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

# Authentication

> Learn how to authenticate your requests to the Taxo API

## API Keys

All requests to the Taxo API require authentication using an API key. This must be included in the `Authorization` header of each request.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://api.taxo.co/v1/extractions" \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json"
  ```

  ```javascript Node.js theme={null}
  const headers = {
    'Authorization': `Bearer ${process.env.TAXO_API_KEY}`,
    'Content-Type': 'application/json'
  };

  const response = await fetch('https://api.taxo.co/v1/extractions', {
    method: 'GET',
    headers: headers
  });
  ```

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

  headers = {
      'Authorization': f'Bearer {os.environ["TAXO_API_KEY"]}',
      'Content-Type': 'application/json'
  }

  response = requests.get('https://api.taxo.co/v1/extractions', headers=headers)
  ```

  ```java Java theme={null}
  HttpHeaders headers = new HttpHeaders();
  headers.set("Authorization", "Bearer " + System.getenv("TAXO_API_KEY"));
  headers.set("Content-Type", "application/json");

  HttpEntity<String> entity = new HttpEntity<>(headers);
  ResponseEntity<String> response = restTemplate.exchange(
      "https://api.taxo.co/v1/extractions",
      HttpMethod.GET,
      entity,
      String.class
  );
  ```
</CodeGroup>

## Getting your API Key

<Steps>
  <Step title="Sign in">
    Access the [Taxo Dashboard](https://dashboard.taxo.co) with your business account
  </Step>

  <Step title="Go to settings">
    Navigate to **Settings** → **API Keys** in the sidebar menu
  </Step>

  <Step title="Create new API Key">
    Click on **"Create API Key"** and assign a descriptive name
  </Step>

  <Step title="Configure permissions">
    Select the necessary permissions for your integration
  </Step>

  <Step title="Copy and save">
    Copy the generated API key and store it securely
  </Step>
</Steps>

<Warning>
  **Important!** The API key is only shown once during creation. Save it immediately in a secure location.
</Warning>

## Environments

Taxo provides two environments for development and production:

<Tabs>
  <Tab title="Production">
    **Base URL:** `https://api.taxo.co`

    * Use for production applications
    * Real SAT data
    * 99.9% availability SLA
    * Production rate limits applied
  </Tab>

  <Tab title="Staging">
    **Base URL:** `https://api-staging.taxo.co`

    * Use for testing and development
    * Simulated test data
    * No guaranteed SLA
    * Relaxed rate limits for testing
  </Tab>
</Tabs>

## Security best practices

<AccordionGroup>
  <Accordion title="Environment variables" icon="shield-check">
    **Never hardcode** your API key in source code. Use environment variables:

    ```bash theme={null}
    # .env
    TAXO_API_KEY=your_api_key_here
    TAXO_BASE_URL=https://api.taxo.co
    ```

    ```javascript theme={null}
    // Correct ✅
    const apiKey = process.env.TAXO_API_KEY;

    // Incorrect ❌
    const apiKey = "txo_live_abc123...";
    ```
  </Accordion>

  <Accordion title="Key rotation" icon="arrows-rotate">
    * Rotate your API keys regularly (recommended: every 90 days)
    * Create new keys before revoking old ones
    * Use multiple keys for different services when possible
    * Monitor key usage from the dashboard
  </Accordion>

  <Accordion title="IP restrictions" icon="network-wired">
    For additional security, you can restrict API key usage to specific IPs:

    1. Go to **Settings** → **API Keys** in the dashboard
    2. Select the key you want to restrict
    3. Add allowed IPs in **IP Restrictions**
    4. Save changes
  </Accordion>

  <Accordion title="Monitoring and alerts" icon="bell">
    Configure alerts to detect anomalous usage:

    * Requests from unauthorized IPs
    * Unusual spikes in API usage
    * Multiple authentication errors
    * Usage exceeding normal limits
  </Accordion>
</AccordionGroup>

## Handling authentication errors

<CodeGroup>
  ```javascript Node.js theme={null}
  try {
    const response = await fetch('https://api.taxo.co/v1/extractions', {
      headers: {
        'Authorization': `Bearer ${apiKey}`
      }
    });
    
    if (response.status === 401) {
      throw new Error('Invalid or expired API key');
    }
    
    if (response.status === 403) {
      throw new Error('Insufficient permissions for this endpoint');
    }
    
  } catch (error) {
    console.error('Authentication error:', error.message);
    // Implement retry logic or notification
  }
  ```

  ```python Python theme={null}
  import requests
  from requests.exceptions import HTTPError

  try:
      response = requests.get(
          'https://api.taxo.co/v1/extractions',
          headers={'Authorization': f'Bearer {api_key}'}
      )
      response.raise_for_status()
      
  except HTTPError as e:
      if e.response.status_code == 401:
          print("Invalid or expired API key")
      elif e.response.status_code == 403:
          print("Insufficient permissions for this endpoint")
      else:
          print(f"Error HTTP: {e.response.status_code}")
  ```
</CodeGroup>

## Common error codes

| Code  | Error             | Description                                                 |
| ----- | ----------------- | ----------------------------------------------------------- |
| `401` | Unauthorized      | Missing, invalid, or expired API key                        |
| `403` | Forbidden         | Valid API key but insufficient permissions for the resource |
| `429` | Too Many Requests | You have exceeded your plan's rate limit                    |

<Tip>
  **Tip:** Implement retry logic with exponential backoff for 429 and 5xx errors, but never for 401 or 403 errors.
</Tip>

## Verify authentication

You can verify that your API key works correctly using this endpoint:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://api.taxo.co/v1/auth/verify" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```javascript Node.js theme={null}
  const response = await fetch('https://api.taxo.co/v1/auth/verify', {
    headers: {
      'Authorization': `Bearer ${process.env.TAXO_API_KEY}`
    }
  });

  const data = await response.json();
  console.log('Valid API key:', data.valid);
  ```
</CodeGroup>

**Successful response:**

```json theme={null}
{
  "valid": true,
  "organization": {
    "id": "org_123456",
    "name": "Mi Empresa S.A. de C.V."
  },
  "permissions": [
    "extractions:create",
    "extractions:read",
    "documents:download"
  ],
  "rateLimit": {
    "plan": "enterprise",
    "requestsPerHour": 1000,
    "remaining": 997
  }
}
```
