# Authentication Guide

The Renesas Web Data API uses API key authentication to secure access to product data. This guide covers how to obtain, configure, and use API keys for authentication.

## Overview

All API requests require authentication using an API key passed in the `x-api-key` header. The API uses this key to:

- Identify and authorize your application
- Track usage and rate limiting
- Provide access to appropriate data based on your permissions


## Authentication Method

### API Key Authentication

The API uses a simple API key authentication scheme:

```http
GET /web-data/v1/product-parts HTTP/1.1
Host: api.renesas.com
x-api-key: YOUR_API_KEY_HERE
Accept: application/json
```

## Getting an API Key

### Request Process

To obtain an API key for the Renesas Web Data API:

1. **Contact Renesas**: Reach out to your Renesas representative or contact support
2. **Provide Requirements**: Specify your intended use case and expected API usage
3. **Review Terms**: Accept the terms of service and usage agreement
4. **Receive Credentials**: You'll receive your API key via secure communication


### Key Information Provided

When you receive your API key, you'll get:

- **API Key**: The secret key for authentication
- **Base URLs**: Production and staging endpoints
- **Rate Limits**: Your allowed requests per time period
- **Access Scope**: Which endpoints and data you can access


## Using Your API Key

### Header Authentication

Include your API key in the `x-api-key` header with every request:

```bash
curl -H "x-api-key: YOUR_API_KEY" \
  -H "Accept: application/json" \
  "https://api.renesas.com/web-data/v1/product-parts"
```

### Code Examples

#### Python

```python
import requests

API_KEY = "your-api-key-here"
BASE_URL = "https://api.renesas.com/web-data/v1"

def make_api_request(endpoint, params=None):
    headers = {
        "x-api-key": API_KEY,
        "Accept": "application/json"
    }
    
    response = requests.get(f"{BASE_URL}/{endpoint}", 
                          headers=headers, 
                          params=params)
    
    if response.status_code == 200:
        return response.json()
    else:
        response.raise_for_status()

# Usage
parts = make_api_request("product-parts", {"limit": 10})
```

#### JavaScript/Node.js

```javascript
const API_KEY = 'your-api-key-here';
const BASE_URL = 'https://api.renesas.com/web-data/v1';

async function makeApiRequest(endpoint, params = {}) {
    const url = new URL(`${BASE_URL}/${endpoint}`);
    
    // Add query parameters
    Object.keys(params).forEach(key => 
        url.searchParams.append(key, params[key])
    );
    
    const response = await fetch(url, {
        headers: {
            'x-api-key': API_KEY,
            'Accept': 'application/json'
        }
    });
    
    if (!response.ok) {
        throw new Error(`API error: ${response.status} ${response.statusText}`);
    }
    
    return await response.json();
}

// Usage
const parts = await makeApiRequest('product-parts', { limit: 10 });
```

#### cURL

```bash
# Basic request
curl -H "x-api-key: YOUR_API_KEY" \
  "https://api.renesas.com/web-data/v1/product-parts"

# With query parameters
curl -H "x-api-key: YOUR_API_KEY" \
  "https://api.renesas.com/web-data/v1/product-parts?limit=50&product_family=RX"

# Pretty-printed JSON response
curl -H "x-api-key: YOUR_API_KEY" \
  "https://api.renesas.com/web-data/v1/product-parts" | jq
```

## Environment Configuration

### Production vs Staging

Use appropriate base URLs for your environment:

**Production:**

```
https://api.renesas.com/web-data/v1
```

**Staging/Development:**

```
https://api.renesas-dev.com/web-data/v1
```

### Environment Variables

Store your API key securely using environment variables:

```bash
# .env file
RENESAS_API_KEY=your-production-api-key
RENESAS_DEV_API_KEY=your-staging-api-key
RENESAS_API_BASE_URL=https://api.renesas.com/web-data/v1
```

## Security Best Practices

### API Key Protection

1. **Never Commit Keys**: Don't include API keys in version control
2. **Use Environment Variables**: Store keys in environment variables or secure configuration
3. **Rotate Keys Regularly**: Request new keys periodically
4. **Limit Scope**: Only request access to endpoints you need
5. **Monitor Usage**: Track your API usage for unusual activity


### Secure Storage

#### Server-Side Applications

```python
import os
from typing import Optional

class ReneasAPI:
    def __init__(self):
        self.api_key = os.getenv('RENESAS_API_KEY')
        if not self.api_key:
            raise ValueError("RENESAS_API_KEY environment variable required")
        
        self.base_url = os.getenv('RENESAS_API_BASE_URL', 
                                 'https://api.renesas.com/web-data/v1')
    
    def get_headers(self) -> dict:
        return {
            'x-api-key': self.api_key,
            'Accept': 'application/json'
        }
```

#### Client-Side Applications

For client-side applications, use a proxy server to protect your API key:

```javascript
// Client-side: Make request to your backend
const response = await fetch('/api/renesas/product-parts', {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json'
    }
});

// Backend proxy (Express.js example)
app.get('/api/renesas/*', async (req, res) => {
    const renesasPath = req.path.replace('/api/renesas', '');
    const renesasUrl = `https://api.renesas.com/web-data/v1${renesasPath}`;
    
    const response = await fetch(renesasUrl, {
        headers: {
            'x-api-key': process.env.RENESAS_API_KEY
        }
    });
    
    const data = await response.json();
    res.json(data);
});
```

## Error Handling

### Authentication Errors

#### 401 Unauthorized

Missing or invalid API key:

```json
{
  "error": "Unauthorized: Invalid or missing API key",
  "code": 401
}
```

**Solutions:**

- Verify your API key is correct
- Ensure the `x-api-key` header is included
- Check that your key hasn't expired


#### 403 Forbidden

Valid key but insufficient permissions:

```json
{
  "error": "Forbidden: Insufficient permissions for this endpoint",
  "code": 403
}
```

**Solutions:**

- Contact support to verify your access scope
- Ensure you're using the correct endpoint
- Check if additional permissions are needed


### Rate Limiting

#### 429 Too Many Requests

Exceeded rate limits:

```json
{
  "error": "Rate limit exceeded",
  "code": 429,
  "retry_after": 60
}
```

**Solutions:**

- Implement exponential backoff
- Reduce request frequency
- Contact support for higher limits if needed


## Rate Limiting

### Default Limits

Rate limits vary based on your API key tier and usage agreement. Common limits include:

- Requests per minute
- Requests per hour
- Concurrent connections
- Data transfer limits


### Handling Rate Limits

#### Python with Backoff

```python
import time
import requests
from functools import wraps

def rate_limit_retry(max_retries=3, backoff_factor=1):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(max_retries):
                try:
                    response = func(*args, **kwargs)
                    if response.status_code == 429:
                        retry_after = int(response.headers.get('Retry-After', 60))
                        time.sleep(retry_after * backoff_factor)
                        continue
                    return response
                except Exception as e:
                    if attempt == max_retries - 1:
                        raise e
                    time.sleep(backoff_factor * (2 ** attempt))
            return response
        return wrapper
    return decorator

@rate_limit_retry()
def make_request(url, headers):
    return requests.get(url, headers=headers)
```

#### JavaScript with Retry Logic

```javascript
async function makeRequestWithRetry(url, options, maxRetries = 3) {
    for (let attempt = 0; attempt < maxRetries; attempt++) {
        try {
            const response = await fetch(url, options);
            
            if (response.status === 429) {
                const retryAfter = response.headers.get('Retry-After');
                const delay = retryAfter ? parseInt(retryAfter) * 1000 : 1000 * (2 ** attempt);
                
                console.log(`Rate limited. Waiting ${delay}ms before retry...`);
                await new Promise(resolve => setTimeout(resolve, delay));
                continue;
            }
            
            return response;
        } catch (error) {
            if (attempt === maxRetries - 1) throw error;
            await new Promise(resolve => setTimeout(resolve, 1000 * (2 ** attempt)));
        }
    }
}
```

## Testing Authentication

### Verify API Key

Test your API key with a simple request:

```bash
curl -I -H "x-api-key: YOUR_API_KEY" \
  "https://api.renesas.com/web-data/v1/product-parts?limit=1"
```

Expected response headers:

```
HTTP/2 200
content-type: application/json
x-ratelimit-remaining: 999
x-ratelimit-limit: 1000
```

### Health Check Script

```python
import requests

def test_api_key(api_key, base_url):
    headers = {"x-api-key": api_key}
    
    try:
        response = requests.get(f"{base_url}/product-parts", 
                              headers=headers, 
                              params={"limit": 1},
                              timeout=10)
        
        if response.status_code == 200:
            print("✅ API key is valid and working")
            print(f"Rate limit remaining: {response.headers.get('x-ratelimit-remaining', 'Unknown')}")
            return True
        elif response.status_code == 401:
            print("❌ Invalid API key")
            return False
        elif response.status_code == 403:
            print("❌ API key valid but insufficient permissions")
            return False
        else:
            print(f"⚠️  Unexpected response: {response.status_code}")
            return False
            
    except requests.exceptions.RequestException as e:
        print(f"❌ Connection error: {e}")
        return False

# Test your API key
test_api_key("your-api-key", "https://api.renesas.com/web-data/v1")
```

## Troubleshooting

### Common Issues

**API Key Not Working:**

1. Check for typos in the key
2. Verify correct header name (`x-api-key`)
3. Ensure key hasn't expired
4. Test with a simple request first


**Rate Limiting Issues:**

1. Monitor your request frequency
2. Implement proper retry logic
3. Consider caching responses
4. Contact support for limit increases


**Access Denied:**

1. Verify endpoint permissions
2. Check API key scope
3. Ensure using correct environment
4. Contact support for access review


## Next Steps

- Learn about [Product Parts API](/guides/product-parts) endpoints
- Explore [Documents API](/guides/documents) for technical documentation
- Review the [Quickstart Guide](/guides/quickstart) for complete examples