Authentication
All Suno API requests require authentication using Bearer Token. This guide explains how to obtain and properly use your API key.
Getting Your API Key
- Visit the API Key Management Page
- Follow the instructions to generate your unique API key
- Store your API key securely for future use
Using Your API Key
Add your API key to all request headers as a Bearer token:
Authorization: Bearer YOUR_API_KEY
Security Notice
- Keep your API key secure and never share it with others
- Store your API key in environment variables, not in your code
- Reset your API key immediately if you suspect it has been compromised
Implementation Examples
Basic API Request (JavaScript)
const SUNO_API_KEY = process.env.SUNO_API_KEY; // Store in environment variable
const BASE_URL = "https://apibox.erweima.ai";
async function callSunoApi(endpoint, data) {
try {
const response = await fetch(`${BASE_URL}${endpoint}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${SUNO_API_KEY}`
},
body: JSON.stringify(data)
});
const result = await response.json();
if (result.code !== 200) {
throw new Error(`API error: ${result.msg}`);
}
return result;
} catch (error) {
console.error("API request failed:", error);
throw error;
}
}
// Example: Generate audio
async function generateAudio() {
const data = {
prompt: "A calm piano track with soft melodies",
customMode: true,
instrumental: true,
model: "V3_5",
callBackUrl: "https://your-callback-url.com/webhook"
};
return callSunoApi("/api/v1/generate", data);
}
Python Example
import os
import requests
import json
SUNO_API_KEY = os.environ.get("SUNO_API_KEY") # Store in environment variable
BASE_URL = "https://apibox.erweima.ai"
def call_suno_api(endpoint, data):
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {SUNO_API_KEY}"
}
response = requests.post(f"{BASE_URL}{endpoint}", headers=headers, json=data)
result = response.json()
if result.get("code") != 200:
raise Exception(f"API error: {result.get('msg')}")
return result
# Example: Generate lyrics
def generate_lyrics():
data = {
"prompt": "A song about peaceful night in the city",
"callBackUrl": "https://your-callback-url.com/webhook"
}
return call_suno_api("/api/v1/lyrics", data)
Security Best Practices
1. Secure Key Storage
- Never hardcode API keys in your source code or client-side applications
- Use environment variables or secure secret management systems
- Maintain separate API keys for development and production environments
// Using dotenv for environment variables
require('dotenv').config();
const apiKey = process.env.SUNO_API_KEY;
if (!apiKey) {
throw new Error("API key not configured in environment");
}
2. Implement Key Rotation
- Regularly rotate your API keys to limit the impact of potential exposure
- Develop a process for safely updating keys in all your services
- Keep track of when keys were last rotated
3. Monitor API Usage
- Regularly check your API usage for any unusual patterns
- Set up alerts for unexpected spikes in API requests
- Track credit consumption to avoid unexpected service interruptions
Error Handling
Properly handle authentication errors in your applications:
async function handleApiRequest(endpoint, data) {
try {
const result = await callSunoApi(endpoint, data);
return result;
} catch (error) {
// Handle specific error codes
if (error.code === 401) {
console.error("Authentication failed: Invalid or expired API key");
// Implement your authentication error recovery logic
} else if (error.code === 429) {
console.error("Insufficient credits to complete request");
// Handle insufficient credits scenario
} else {
console.error("API request failed:", error);
}
throw error;
}
}
Troubleshooting
Issue | Possible Solution |
---|---|
"Unauthorized" error (401) | Check if your API key is valid and correctly formatted in the request header |
"Insufficient Credits" error (429) | Check your account balance and add more credits if needed |
"Rate Limited" error (405) | Reduce your request frequency or implement request throttling |
Connection timeout | Check your network connection and try again with exponential backoff |
Best Practice
When implementing callbacks in your application, ensure your callback URL is publicly accessible and can properly handle the response data from Suno API.
If you encounter persistent authentication issues, please contact our support team at [email protected].