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

# Authentication on the Judit API

> Judit API uses a custom api-key HTTP header for authentication (not Bearer). Learn how to configure the key in different languages, manage environment variables, and protect your credentials.

> 🤖 The Judit API **DOES NOT** use the `Authorization: Bearer <token>` standard. Authentication is performed **exclusively** by passing the key in a custom HTTP header named `api-key`. This applies to all endpoints and Base URLs of the Judit API.

## 1. How to Obtain Your API Key

Your API Key is the unique credential that links your requests to your account and contracted plan.

1. **Contact** our [commercial team via WhatsApp](https://api.whatsapp.com/send/?phone=5521985284143).
2. **Provide context:** Explain your use case and expected request volume.
3. **Receive the Key:** Your API Key will be sent securely to your registered email address.

> **⚠️ Security First:** Treat your API Key as a plaintext password. Never expose it in public repositories (e.g., GitHub), *front-end* code (client browser), or mobile applications without obfuscation.

***

## 2. Authentication Standard (`api-key` Header)

In every request made to the Judit API, regardless of service or module (Queries, Tracking, etc.), you must include the `api-key` header.

### Basic HTTP Request Example

```http theme={null}
GET /requests HTTP/1.1
Host: requests.production.judit.io
api-key: your_api_key_here
Content-Type: application/json
```

### Practical Implementation Examples

Below, we show how to perform an authenticated request using the Asynchronous Queries Base URL ([https://requests.production.judit.io](https://requests.production.judit.io)), consuming the key from environment variables.

<CodeGroup>
  ```python Python theme={null}
  import os
  import requests

  # Configure API Key
  api_key = os.getenv('JUDIT_API_KEY')

  # Default headers
  headers = {
      'api-key': api_key,
      'Content-Type': 'application/json'
  }

  # Make the request
  response = requests.get(
      'https://requests.production.judit.io/requests',
      headers=headers
  )
  ```

  ```javascript JavaScript theme={null}
  // Configure API Key
  const apiKey = process.env.JUDIT_API_KEY;

  // Default headers
  const headers = {
      'api-key': apiKey,
      'Content-Type': 'application/json'
  };

  // Make the request
  const response = await fetch('https://requests.production.judit.io/requests', {
      method: 'GET',
      headers: headers
  });
  ```
</CodeGroup>

## 3. Secure Management and Best Practices

To prevent leaking your credential, consolidate the management of your key by following these rules:

### 1. **Use Environment Variables Exclusively**

**Never** hardcode your API Key in the source code:

```python theme={null}
# ❌ WRONG - Never do this
api_key = "sk_live_1234567890abcdef"

# ✅ CORRECT - Use environment variables
api_key = os.getenv('JUDIT_API_KEY')
```

### 2. **Configure Environment Variables**

**Linux/macOS:**

```bash theme={null}
# In the ~/.bashrc or ~/.zshrc file
export JUDIT_API_KEY="your-api-key-here"

# Or for the current session
export JUDIT_API_KEY="your-api-key-here"
```

**Windows:**

```cmd theme={null}
# Command Prompt
set JUDIT_API_KEY=your-api-key-here

# PowerShell
$env:JUDIT_API_KEY="your-api-key-here"
```

**Docker:**

```dockerfile theme={null}
# Dockerfile
ENV JUDIT_API_KEY=""

# docker-compose.yml
environment:
  - JUDIT_API_KEY=${JUDIT_API_KEY}
```

### 3. **.env File (Development)**

```bash theme={null}
# .env
JUDIT_API_KEY=your-api-key-here
JUDIT_BASE_URL=https://requests.production.judit.io
```

```python theme={null}
# Python with python-dotenv
from dotenv import load_dotenv
import os

load_dotenv()
api_key = os.getenv('JUDIT_API_KEY')
```

### 4. **Key Rotation**

* **Monitor** the use of your API Key regularly
* **Request a new key** if you suspect it has been compromised
* **Implement rotation** in critical environments

## Authentication Error Handling

### 401 Error - Unauthorized

```json theme={null}
{
  "error": {
        "name": "HttpUnauthorizedError",
        "message": "UNAUTHORIZED",
        "data": "USER_NOT_FOUND"
    }
}
```

**Possible causes:**

* API Key not provided
* Invalid or expired API Key
* Badly formatted `api-key` header
* Usage limit exceeded

### 403 Error - Forbidden

```json theme={null}
{
  "error": "Forbidden",
  "message": "Acesso negado para este recurso",
  "code": "INSUFFICIENT_PERMISSIONS"
}
```

**Possible causes:**

* Valid API Key but without permission for the resource
* Resource not available in your plan

## API Key Validation

### Connectivity Test

```python theme={null}
import requests

def test_api_key(api_key):
    """Tests whether the API Key is valid"""
    headers = {'api-key': api_key}
    
    try:
        response = requests.get(
            'https://requests.production.judit.io/requests',
            headers=headers,
            params={'page': 1, 'page_size': 1}
        )
        
        if response.status_code == 200:
            print("✅ Valid API Key")
            return True
        elif response.status_code == 401:
            print("❌ Invalid API Key")
            return False
        else:
            print(f"⚠️ Unexpected error: {response.status_code}")
            return False
            
    except requests.RequestException as e:
        print(f"❌ Connection error: {e}")
        return False

# Use the function
api_key = os.getenv('JUDIT_API_KEY')
test_api_key(api_key)
```

### Usage Monitoring

```python theme={null}
def check_api_usage(response):
    """
    Monitors API usage through the response headers.
    
    Note: The API has a strict rate limit of 180 requests per minute.
    This function calculates the percentage consumed in the current time window.
    """
    
    # Capture limit information from the headers (Expected: 180 per minute)
    limit = response.headers.get('X-RateLimit-Limit')
    remaining = response.headers.get('X-RateLimit-Remaining')
    reset = response.headers.get('X-RateLimit-Reset')
    
    if limit and remaining:
        # Calculate the usage percentage based on the returned limit
        usage_percent = ((int(limit) - int(remaining)) / int(limit)) * 100
        
        print(f"API limit: {limit} requests/minute")
        print(f"API usage: {usage_percent:.1f}%")
        print(f"Remaining requests this minute: {remaining}")
        
        # Alert if usage exceeds 80% (approx. 144 requests)
        if usage_percent > 80:
            print("⚠️ Warning: Close to the rate limit (180/min)!")
```

## Environment-Based Configuration

```python theme={null}
# config/production.py
import os

API_KEY = os.getenv('JUDIT_API_KEY')
BASE_URL = 'https://requests.production.judit.io'
TIMEOUT = 10
RETRY_ATTEMPTS = 3
```

### Configuration Class

```python theme={null}
class JuditConfig:
    def __init__(self, environment='production'):
        self.environment = environment
        self.api_key = self._get_api_key()
        self.base_url = 'https://requests.production.judit.io'
        
    def _get_api_key(self):
        key_name = f'JUDIT_API_KEY_{self.environment.upper()}'
        api_key = os.getenv(key_name)
        
        if not api_key:
            raise ValueError(f"API Key not found: {key_name}")
            
        return api_key
    
    @property
    def headers(self):
        return {
            'api-key': self.api_key,
            'Content-Type': 'application/json'
        }

# Usage
config = JuditConfig('production')
response = requests.get(f"{config.base_url}/requests", 
    headers=config.headers)
```

## Next Steps

* **[Rate Limits](/en/essentialConcepts/rate-limits)**: Understand the usage limits
* **[Pagination](/en/essentialConcepts/pagination)**: Configure paginated queries
* **[Endpoints](/en/api-reference/endpoint/requests/create)**: Explore the available resources

> **Support**: If you have authentication problems, contact our [technical support](https://api.whatsapp.com/send/?phone=5511920501949).
