Skip to main content

Authentication

Overview

Authentication is required for all Kie.ai API requests. We use a secure Bearer Token authentication system to ensure API access is properly authorized.

Getting Your API Key

To access the API services, you'll need to:

  1. Visit the API Key Management Page
  2. Sign in to your Kie.ai account
  3. Generate your unique API key
  4. Copy and store your key securely
Important

Your API key gives direct access to your account and resources. Never share it publicly or include it in client-side code.

Using Your API Key

All API requests must include your API key in the Authorization header:

Authorization: Bearer YOUR_API_KEY

Example Request with Bearer Token

curl -X POST https://kieai.erweima.ai/api/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"model": "deepseek-chat",
"messages": [
{"role": "user", "content": "Hello, how are you?"}
]
}'

Implementation Examples

JavaScript/Node.js

const fetchData = async (endpoint, data) => {
const API_KEY = process.env.KIE_API_KEY; // Store keys in environment variables

const response = await fetch(`https://kieai.erweima.ai${endpoint}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`
},
body: JSON.stringify(data)
});

if (!response.ok) {
throw new Error(`API request failed: ${response.status}`);
}

return response.json();
};

// Example usage
try {
const response = await fetchData('/api/v1/chat/completions', {
model: 'deepseek-chat',
messages: [
{role: 'user', content: 'Hello!'}
]
});
console.log(response);
} catch (error) {
console.error('API Error:', error.message);
}

Python

import os
import requests

def call_api(endpoint, data):
api_key = os.environ.get('KIE_API_KEY') # Secure key management

if not api_key:
raise ValueError("API key not found in environment variables")

headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {api_key}'
}

response = requests.post(
f'https://kieai.erweima.ai{endpoint}',
headers=headers,
json=data
)

response.raise_for_status() # Handle HTTP errors

return response.json()

# Example usage
try:
result = call_api('/api/v1/chat/completions', {
'model': 'deepseek-chat',
'messages': [
{'role': 'user', 'content': 'Hello!'}
]
})
print(result)
except requests.exceptions.HTTPError as err:
print(f"HTTP Error: {err}")
except Exception as err:
print(f"Error: {err}")

Security Best Practices

1. API Key Storage

Keep your API key secure by following these guidelines:

  • Never hardcode API keys in your application code
  • Do not include API keys in version control systems
  • Use environment variables or secure secret management services
  • Set up different keys for development and production environments
// Example using environment variables (Node.js)
require('dotenv').config();
const apiKey = process.env.KIE_API_KEY;

// Verify key exists before making requests
if (!apiKey) {
throw new Error('API key not configured');
}

2. Regular Key Rotation

Rotating your API keys periodically enhances security:

  • Rotate keys every 90-180 days
  • Immediately rotate keys if there's any suspicion of compromise
  • Implement seamless rotation to avoid service disruption

3. Access Monitoring

Keep track of your API key usage:

  • Log API access patterns
  • Set up alerts for unusual activity
  • Review usage regularly

Handling Authentication Errors

When authentication fails, the API returns a 401 Unauthorized status code. Common causes include:

  • Invalid API key
  • Expired API key
  • Missing Authorization header
  • Incorrect header format

Example Error Response

{
"code": 401,
"msg": "Authentication required or failed"
}

Error Handling Example

async function secureApiCall(endpoint, data) {
try {
const response = await fetch(`https://kieai.erweima.ai${endpoint}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify(data)
});

if (response.status === 401) {
// Handle authentication errors
console.error('Authentication failed: Please check your API key');
// Implement key refresh or user notification logic
return;
}

if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}

return await response.json();
} catch (error) {
console.error('Request failed:', error.message);
}
}

Rate Limiting and Quotas

Authentication also relates to your account's rate limits and quotas:

  • Authenticated requests are counted against your account's quota
  • Rate limiting is applied per API key
  • Exceeding quotas results in 429 error responses
  • Monitor your credit usage via the Account API
Pro Tip

For production applications, implement retry logic with exponential backoff when handling rate limit errors. Always check the remaining credits before making expensive API calls.

Need Help?

If you're experiencing authentication issues:

  • Verify your API key is correct and active
  • Check your implementation against the examples above
  • Review your account status in the Dashboard

For additional assistance, contact our support team at [email protected].