Quick Start
To access GenreX API, you must obtain the keys from the platform. Please contact us. to apply for an API key.
To generate music via API, follow these two steps:
-
Request the generation and immediately receive the
queryID
via the endpointv1/text2music/generateMusic
. -
Obtain the audio URL by continuously checking the query status using the
queryID
in a loop until it is completed via the endpointv1/text2music/retrieve
.
Both steps require a user signature to verify identity.
Here is a sample code snippet to get you started
Request Generation
Construct the payload
Suppose you want to create a 10-second song by prompting something like "intense EDM," your API request payload body should be like this:
- Node.js
- Python
const payload = JSON.stringify({
duration: 10,
text: "intense EDM",
});
payload = {
"duration": 10,
"text": "intense EDM",
}
Create signature
To avoid directly passing the API secret to our API and prevent forgery, you can create the signature by encrypting ${timestamp}.${payload}
with the API secret using the SHA-256 HMAC algorithm.
- Node.js
- Python
const timestamp = Date.now();
const dataToSign = `${timestamp}.${payload}`;
const hmac = crypto.createHmac("sha256", apiSecret);
const signature = hmac.update(dataToSign).digest("hex");
timestamp = str(int(time.time() * 1000))
payload_json = json.dumps(payload, separators=(",", ":"))
data_to_sign = f"{timestamp}.{payload_json}"
signature = hmac.new(
api_secret.encode(), data_to_sign.encode(), hashlib.sha256
).hexdigest()
Create headers
- Node.js
- Python
const headers = {
"gx-key": apiKey,
"gx-signature": `t=${timestamp},v=${signature}`,
"Content-Type": "application/json",
};
headers = {
"gx-key": api_key,
"gx-signature": f"t={timestamp},v={signature}",
"Content-Type": "application/json",
}
Send request and receive queryId
- Node.js
- Python
axios
.post("https://api.genrex.com/v1/text2music/generateMusic", payload, {
headers,
})
.then((response) => {
console.log("queryId:", response.data.id);
})
.catch((error) => {
console.error(
"Error:",
error.response ? error.response.data : error.message
);
});
try:
response = requests.post(
"https://api.genrex.com/v1/text2music/generateMusic",
data=payload_json,
headers=headers,
)
response.raise_for_status()
print("queryId:", response.json().get("id"))
except requests.exceptions.RequestException as e:
if e.response:
print("Error:", e.response.json())
else:
print("Error:", str(e))
Let's put everything together 😃✌️
- Node.js
- Python
const crypto = require("crypto");
const axios = require("axios");
const apiKey = "<YOUR-API-KEY>";
const apiSecret = "<YOUR-API-SECRET>";
// construct the payload
const payload = JSON.stringify({
duration: 10,
text: "intense EDM",
});
// create signature
const timestamp = Date.now();
const dataToSign = `${timestamp}.${payload}`;
const hmac = crypto.createHmac("sha256", apiSecret);
const signature = hmac.update(dataToSign).digest("hex");
// create headers
const headers = {
"gx-key": apiKey,
"gx-signature": `t=${timestamp},v=${signature}`,
"Content-Type": "application/json",
};
// Send post request
axios
.post("https://api.genrex.com/v1/text2music/generateMusic", payload, {
headers,
})
.then((response) => {
console.log("queryId:", response.data.id);
})
.catch((error) => {
console.error(
"Error:",
error.response ? error.response.data : error.message
);
});
import hashlib
import hmac
import json
import requests
import time
api_key = "<YOUR-API-KEY>"
api_secret = "<YOUR-API-SECRET>"
# construct the payload
payload = {
"duration": 10,
"text": "intense EDM",
}
# create signature
timestamp = str(int(time.time() * 1000))
payload_json = json.dumps(payload, separators=(",", ":"))
data_to_sign = f"{timestamp}.{payload_json}"
signature = hmac.new(
api_secret.encode(), data_to_sign.encode(), hashlib.sha256
).hexdigest()
# Create headers
headers = {
"gx-key": api_key,
"gx-signature": f"t={timestamp},v={signature}",
"Content-Type": "application/json",
}
# Send post request
try:
response = requests.post(
"https://api.genrex.com/v1/text2music/generateMusic",
data=payload_json,
headers=headers,
)
response.raise_for_status()
print("queryId:", response.json().get("id"))
except requests.exceptions.RequestException as e:
if e.response:
print("Error:", e.response.json())
else:
print("Error:", str(e))
Obtain the audio assets
Once you submit the generation request, you can use the queryID
to check if the generation is ready.
Similarly, we request signature as logic in request generation.
Construct the payload
- Node.js
- Python
const createPayload = (queryId) => JSON.stringify({queryId});
def create_payload(query_id):
return json.dumps({"queryId": query_id}, separators=(",", ":"))
Create signature
- Node.js
- Python
const createSignature = (apiSecret, dataToSign) => {
const hmac = crypto.createHmac("sha256", apiSecret);
return hmac.update(dataToSign).digest("hex");
};
def create_signature(api_secret, data_to_sign):
return hmac.new(
api_secret.encode(), data_to_sign.encode(), hashlib.sha256
).hexdigest()
Create headers
- Node.js
- Python
const createHeaders = (apiKey, apiSecret, payload) => {
const timestamp = Date.now();
const dataToSign = `${timestamp}.${payload}`;
const signature = createSignature(apiSecret, dataToSign);
return {
"gx-key": apiKey,
"gx-signature": `t=${timestamp},v=${signature}`,
"Content-Type": "application/json",
};
};
def create_headers(api_key, api_secret, payload):
timestamp = str(int(time.time() * 1000))
data_to_sign = f"{timestamp}.{payload}"
signature = create_signature(api_secret, data_to_sign)
return {
"gx-key": api_key,
"gx-signature": f"t={timestamp},v={signature}",
"Content-Type": "application/json",
}
Check the status of the generation
- Node.js
- Python
const checkStatus = async (payload, headers) => {
try {
const response = await axios.post(
"https://api.genrex.com/v1/text2music/retrieve",
payload,
{ headers }
);
switch (response.data.status) {
case "Completed":
return response.data.response[0].content.url;
case "Processing":
console.log("Generation in progress, checking again...");
return null;
case "Failed":
console.error(
"The generation failed. Please submit a new generation request."
);
process.exit(1);
default:
console.log("Unknown status, exiting.");
process.exit(1);
}
} catch (error) {
console.error(
"Error checking status:",
error.response ? error.response.data : error.message
);
throw error;
}
};
def check_status(payload, headers):
try:
response = requests.post(
"https://api.genrex.com/v1/text2music/retrieve",
data=payload,
headers=headers,
)
response.raise_for_status()
data = response.json()
status = data.get("status")
if status == "Completed":
return data["response"][0]["content"]["url"]
elif status == "Processing":
print("Generation in progress, checking again...")
return None
elif status == "Failed":
print("The generation failed. Please submit a new generation request.")
exit(1)
else:
print("Unknown status, exiting.")
exit(1)
except requests.exceptions.RequestException as e:
print("Error checking status:", e.response.json() if e.response else str(e))
raise
Loop the checking process
- Node.js
- Python
// Main function to get the audio URL
const getAudioUrl = async (apiKey, apiSecret, queryId) => {
const pollingInterval = 5000; // Set the polling interval in milliseconds
const payload = createPayload(queryId);
const headers = createHeaders(apiKey, apiSecret, payload);
while (true) {
const audioUrl = await checkStatus(payload, headers);
if (audioUrl) return audioUrl;
await new Promise((resolve) => setTimeout(resolve, pollingInterval));
}
};
# Main function to get the audio URL
def get_audio_url(api_key, api_secret, query_id):
polling_interval = 5 # Set the polling interval in seconds
payload = create_payload(query_id)
headers = create_headers(api_key, api_secret, payload)
while True:
audio_url = check_status(payload, headers)
if audio_url:
return audio_url
time.sleep(polling_interval)
Let's put everything together AGAIN 😃✌️
- Node.js
- Python
const axios = require("axios");
const crypto = require("crypto");
const apiKey = "<YOUR-API-KEY>";
const apiSecret = "<YOUR-API-SECRET>";
const queryId = "<YOUR-QUERY-ID>"; // Replace this with your actual Query ID
// Function to create payload with the queryId
const createPayload = (queryId) => JSON.stringify({ queryId });
// Function to create signature
const createSignature = (apiSecret, dataToSign) => {
const hmac = crypto.createHmac("sha256", apiSecret);
return hmac.update(dataToSign).digest("hex");
};
// Function to create headers
const createHeaders = (apiKey, apiSecret, payload) => {
const timestamp = Date.now();
const dataToSign = `${timestamp}.${payload}`;
const signature = createSignature(apiSecret, dataToSign);
return {
"gx-key": apiKey,
"gx-signature": `t=${timestamp},v=${signature}`,
"Content-Type": "application/json",
};
};
// Function to check the status of the generation
const checkStatus = async (payload, headers) => {
try {
const response = await axios.post(
"https://api.genrex.com/v1/text2music/retrieve",
payload,
{ headers }
);
switch (response.data.status) {
case "Completed":
return response.data.response[0].content.url;
case "Processing":
console.log("Generation in progress, checking again...");
return null;
case "Failed":
console.error(
"The generation failed. Please submit a new generation request."
);
process.exit(1);
default:
console.log("Unknown status, exiting.");
process.exit(1);
}
} catch (error) {
console.error(
"Error checking status:",
error.response ? error.response.data : error.message
);
throw error;
}
};
// Main function to get the audio URL
const getAudioUrl = async (apiKey, apiSecret, queryId) => {
const pollingInterval = 5000; // Set the polling interval in milliseconds
const payload = createPayload(queryId);
const headers = createHeaders(apiKey, apiSecret, payload);
while (true) {
const audioUrl = await checkStatus(payload, headers);
if (audioUrl) return audioUrl;
await new Promise((resolve) => setTimeout(resolve, pollingInterval));
}
};
// Self-invoking function to use getAudioUrl
(async () => {
try {
const audioUrl = await getAudioUrl(apiKey, apiSecret, queryId);
console.log("Audio URL:", audioUrl);
} catch (error) {
console.error("Failed to retrieve audio URL:", error);
}
})();
import hashlib
import hmac
import json
import requests
import time
api_key = "<YOUR-API-KEY>"
api_secret = "<YOUR-API-SECRET>"
query_id = "<YOUR-QUERY-ID>" # Replace this with your actual Query ID
# Function to create payload with the queryId
def create_payload(query_id):
return json.dumps({"queryId": query_id}, separators=(",", ":"))
# Function to create signature
def create_signature(api_secret, data_to_sign):
return hmac.new(
api_secret.encode(), data_to_sign.encode(), hashlib.sha256
).hexdigest()
# Function to create headers
def create_headers(api_key, api_secret, payload):
timestamp = str(int(time.time() * 1000))
data_to_sign = f"{timestamp}.{payload}"
signature = create_signature(api_secret, data_to_sign)
return {
"gx-key": api_key,
"gx-signature": f"t={timestamp},v={signature}",
"Content-Type": "application/json",
}
# Function to check the status of the generation
def check_status(payload, headers):
try:
response = requests.post(
"https://api.genrex.com/v1/text2music/retrieve",
data=payload,
headers=headers,
)
response.raise_for_status()
data = response.json()
status = data.get("status")
if status == "Completed":
return data["response"][0]["content"]["url"]
elif status == "Processing":
print("Generation in progress, checking again...")
return None
elif status == "Failed":
print("The generation failed. Please submit a new generation request.")
exit(1)
else:
print("Unknown status, exiting.")
exit(1)
except requests.exceptions.RequestException as e:
print("Error checking status:", e.response.json() if e.response else str(e))
raise
# Main function to get the audio URL
def get_audio_url(api_key, api_secret, query_id):
polling_interval = 5 # Set the polling interval in seconds
payload = create_payload(query_id)
headers = create_headers(api_key, api_secret, payload)
while True:
audio_url = check_status(payload, headers)
if audio_url:
return audio_url
time.sleep(polling_interval)
# Self-invoking function to use get_audio_url
if __name__ == "__main__":
try:
audio_url = get_audio_url(api_key, api_secret, query_id)
print("Audio URL:", audio_url)
except Exception as e:
print("Failed to retrieve audio URL:", str(e))
How to Check Your Balance?
We highly recommend that users frequently self-monitor their remaining balance. Here is the code to check your quota and credits:
- Node.js
- Python
const crypto = require("crypto");
const axios = require("axios");
const apiKey = "<YOUR-API-KEY>"; // Replace this with your actual API Key
const apiSecret = "<YOUR-API-SECRET>"; // Replace this with your actual API Secret
// create signature
const timestamp = Date.now();
const payload = JSON.stringify({});
const dataToSign = `${timestamp}.${payload}`;
const hmac = crypto.createHmac("sha256", apiSecret);
const signature = hmac.update(dataToSign).digest("hex");
// create headers
const headers = {
"gx-key": apiKey,
"gx-signature": `t=${timestamp},v=${signature}`,
"Content-Type": "application/json",
};
// Send post request
axios
.post("https://api.genrex.com/v1/text2music/getBalance", payload, {
headers,
})
.then((response) => {
console.log("Response:", response.data);
})
.catch((error) => {
console.error(
"Error:",
error.response ? error.response.data : error.message
);
});
import time
import hmac
import hashlib
import requests
api_key = "<YOUR-API-KEY>" # Replace this with your actual API Key
api_secret = "<YOUR-API-SECRET>" # Replace this with your actual API Secret
# Create signature
timestamp = str(int(time.time() * 1000))
payload_str = "{}"
data_to_sign = f"{timestamp}.{payload_str}"
signature = hmac.new(api_secret.encode(), data_to_sign.encode(), hashlib.sha256).hexdigest()
# Create headers
headers = {
"gx-key": api_key,
"gx-signature": f"t={timestamp},v={signature}",
"Content-Type": "application/json",
}
# Send POST request
response = requests.post("https://api.genrex.com/v1/text2music/getBalance", json=payload, headers=headers)
# Handle response
print(response)
if response.status_code == 201:
print("Response:", response.json())
else:
print("Error:", response.json() if response.content else response.status_code)
As a result, you will receive a response like this:
{
"durationLimit": 60,
"creditQuota": 54,
"usedCredit": 0,
"userId": "a6f434b6-a475-40b1-81e3-3ce9868945ff",
"createdAt": "2024-06-01T16:47:17.054Z",
"updatedAt": "2024-06-03T03:26:42.735Z"
}