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

# Revoke API Key

<RequestExample>
  ```bash cURL theme={null}
  curl -X DELETE "https://api.strike.markets/api-key/revoke" \
    -H "X-API-Key: stk_your_api_key_here" \
    -H "Content-Type: application/json"
  ```

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

  headers = {
      'X-API-Key': os.environ['STRIKE_API_KEY'],
      'Content-Type': 'application/json'
  }

  response = requests.delete(
      'https://api.strike.markets/api-key/revoke',
      headers=headers
  )

  if response.status_code == 200:
      print("API key successfully revoked")
  else:
      print(f"Error: {response.json()}")
  ```

  ```typescript TypeScript theme={null}
  const response = await fetch('https://api.strike.markets/api-key/revoke', {
    method: 'DELETE',
    headers: {
      'X-API-Key': process.env.STRIKE_API_KEY,
      'Content-Type': 'application/json'
    }
  });

  if (response.ok) {
    console.log("API key successfully revoked");
  } else {
    const error = await response.json();
    console.error(`Error: ${error.message}`);
  }
  ```
</RequestExample>

<ResponseExample>
  ```json Success Response theme={null}
  {
    "success": true,
    "message": "API key revoked successfully",
    "wallet_address": "0x742d35cc6c6c7532b1140da4c8a2f6c8ecfc9b46",
    "revoked_at": "2024-01-15T14:30:00Z"
  }
  ```

  ```json Error - No Key Found theme={null}
  {
    "error": "API_KEY_NOT_FOUND",
    "message": "No API key found for this wallet"
  }
  ```

  ```json Error - Invalid Key theme={null}
  {
    "error": "INVALID_API_KEY",
    "message": "Invalid or already revoked API key"
  }
  ```
</ResponseExample>

## Description

Revoke an existing API key. Once revoked, the key cannot be used for authentication and cannot be recovered. You'll need to generate a new key if you want to continue using the API.

## Important Notes

<Warning>
  **This action is irreversible!** Once an API key is revoked, it cannot be recovered or reactivated. Make sure you want to revoke the key before calling this endpoint.
</Warning>

<Note>
  After revoking a key, you can immediately generate a new one using the `/api-key/generate` endpoint.
</Note>

## Authentication

This endpoint requires:

* The API key you want to revoke (it authenticates itself for revocation)
* Or a service key with the wallet address

## Request Headers

| Header       | Type   | Required | Description                |
| ------------ | ------ | -------- | -------------------------- |
| X-API-Key    | string | Yes      | The API key to revoke      |
| Content-Type | string | Yes      | Must be `application/json` |

## Response Fields

| Field           | Type    | Description                                   |
| --------------- | ------- | --------------------------------------------- |
| success         | boolean | Whether the operation was successful          |
| message         | string  | Confirmation message                          |
| wallet\_address | string  | The wallet address that owned the revoked key |
| revoked\_at     | string  | ISO 8601 timestamp of revocation              |

## Error Codes

| Code                 | Description                                    |
| -------------------- | ---------------------------------------------- |
| API\_KEY\_NOT\_FOUND | No API key exists for this wallet              |
| INVALID\_API\_KEY    | The provided key is invalid or already revoked |
| UNAUTHORIZED         | Missing authentication                         |
| INTERNAL\_ERROR      | Server error during revocation                 |

## Common Use Cases

### 1. Security Breach

If you suspect your API key has been compromised:

```python theme={null}
# Immediately revoke the compromised key
response = requests.delete(
    'https://api.strike.markets/api-key/revoke',
    headers={'X-API-Key': compromised_key}
)

# Generate a new key through the web interface
# Update all your applications with the new key
```

### 2. Key Rotation

Regular key rotation for security:

```python theme={null}
def rotate_api_key(old_key: str, wallet_address: str, service_key: str):
    # Step 1: Revoke old key
    revoke_response = requests.delete(
        'https://api.strike.markets/api-key/revoke',
        headers={'X-API-Key': old_key}
    )
    
    if revoke_response.status_code != 200:
        raise Exception("Failed to revoke old key")
    
    # Step 2: Generate new key
    generate_response = requests.post(
        'https://api.strike.markets/api-key/generate',
        headers={
            'X-API-Key': service_key,
            'X-Wallet-Address': wallet_address
        }
    )
    
    if generate_response.status_code == 200:
        new_key = generate_response.json()['api_key']
        # Save new key securely
        return new_key
    else:
        raise Exception("Failed to generate new key")
```

### 3. Cleanup Before Account Migration

```javascript theme={null}
async function cleanupApiKey(apiKey) {
  // Revoke API key before migrating or closing account
  const response = await fetch('https://api.strike.markets/api-key/revoke', {
    method: 'DELETE',
    headers: {
      'X-API-Key': apiKey,
      'Content-Type': 'application/json'
    }
  });
  
  if (response.ok) {
    console.log("API key cleaned up successfully");
    // Proceed with account migration/closure
  }
}
```

## Rate Limiting

This endpoint is rate-limited to prevent abuse:

* 5 requests per minute per API key
* 10 requests per hour per wallet address

## After Revocation

Once you've revoked your API key:

1. **All active sessions using that key will be terminated**
2. **Any pending requests will fail with authentication errors**
3. **You'll need to generate a new key to continue using the API**
4. **Update all applications and scripts with the new key**

## Example: Complete Key Rotation Flow

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

class APIKeyRotation:
    def __init__(self, base_url="https://api.strike.markets"):
        self.base_url = base_url
    
    def rotate_key(self, current_key: str, wallet_address: str, service_key: str):
        """Complete key rotation with error handling"""
        
        try:
            # Step 1: Test current key is valid
            test_response = requests.get(
                f"{self.base_url}/api-key/status",
                headers={'X-API-Key': current_key}
            )
            
            if test_response.status_code != 200:
                raise Exception("Current key is invalid")
            
            # Step 2: Revoke current key
            print("Revoking current API key...")
            revoke_response = requests.delete(
                f"{self.base_url}/api-key/revoke",
                headers={'X-API-Key': current_key}
            )
            
            if revoke_response.status_code != 200:
                raise Exception(f"Revocation failed: {revoke_response.json()}")
            
            print("Key revoked successfully")
            
            # Step 3: Small delay to ensure revocation is processed
            time.sleep(1)
            
            # Step 4: Generate new key
            print("Generating new API key...")
            generate_response = requests.post(
                f"{self.base_url}/api-key/generate",
                headers={
                    'X-API-Key': service_key,
                    'X-Wallet-Address': wallet_address,
                    'Content-Type': 'application/json'
                }
            )
            
            if generate_response.status_code == 200:
                new_key = generate_response.json()['api_key']
                print(f"New API key generated successfully")
                print(f"IMPORTANT: Save this key: {new_key}")
                return new_key
            else:
                raise Exception(f"Generation failed: {generate_response.json()}")
                
        except Exception as e:
            print(f"Key rotation failed: {e}")
            raise

# Usage
rotator = APIKeyRotation()
new_key = rotator.rotate_key(
    current_key=os.environ['OLD_STRIKE_API_KEY'],
    wallet_address="0x742d35cc6c6c7532b1140da4c8a2f6c8ecfc9b46",
    service_key=os.environ['STRIKE_SERVICE_KEY']
)

# Update environment variable with new key
os.environ['STRIKE_API_KEY'] = new_key
```
