Skip to main content

Quick Start

Prerequisite

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:

  1. Request the generation and immediately receive the queryID via the endpoint v1/text2music/generateMusic.

  2. Obtain the audio URL by continuously checking the query status using the queryID in a loop until it is completed via the endpoint v1/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:

const payload = JSON.stringify({
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.

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 request and receive queryId

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
);
});

Let's put everything together 😃✌️

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
);
});

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

const createPayload = (queryId) => JSON.stringify({queryId}); 

Create signature

const createSignature = (apiSecret, dataToSign) => {
const hmac = crypto.createHmac("sha256", apiSecret);
return hmac.update(dataToSign).digest("hex");
};

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",
};
};

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;
}
};

Loop the checking process

// 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));
}
};

Let's put everything together AGAIN 😃✌️

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);
}
})();

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:

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
);
});

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"
}